@docstack/react 0.0.9 → 0.1.0
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/lib/components/StackProvider/index.d.ts +24 -7
- package/lib/components/StackProvider/index.js +102 -24
- package/lib/hooks/class.d.ts +1 -1
- package/lib/hooks/class.js +76 -18
- package/lib/hooks/domain.d.ts +1 -2
- package/lib/hooks/domain.js +75 -18
- package/lib/hooks/index.d.ts +23 -5
- package/lib/hooks/index.js +112 -77
- package/lib/hooks/sync.d.ts +27 -0
- package/lib/hooks/sync.js +76 -0
- package/lib/index.d.ts +11 -1
- package/lib/index.js +2 -1
- package/package.json +2 -3
- package/src/components/StackProvider/index.tsx +118 -34
- package/src/hooks/class.ts +69 -21
- package/src/hooks/domain.ts +68 -22
- package/src/hooks/index.ts +138 -59
- package/src/hooks/sync.ts +84 -0
- package/src/index.ts +36 -2
- package/lib/index.js.LICENSE.txt +0 -9
- package/lib/index.js.map +0 -1
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { useCallback, useEffect, useState } from 'react';
|
|
2
|
+
import { useDocStack } from '../components/StackProvider/index.js';
|
|
3
|
+
import type { SyncStatus } from '@docstack/client';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Subscribes to replication state for one stack, or for all of them.
|
|
7
|
+
*
|
|
8
|
+
* Reads the state DocStack's sync layer keeps rather than tracking replication in the
|
|
9
|
+
* component: `lastConvergedAt` is the honest "last synced" value - the moment a cycle
|
|
10
|
+
* finished with nothing left to send - while `lastActiveAt` only says documents moved.
|
|
11
|
+
*
|
|
12
|
+
* The subscription is on the stacks, not on the replication handles, so it survives a
|
|
13
|
+
* {@link StackSyncHandle.restart} (a refreshed credential, say) and works whether it
|
|
14
|
+
* mounts before or after `sync()` was called.
|
|
15
|
+
*
|
|
16
|
+
* @param stackName - Narrow to a single stack. Omit for every open stack.
|
|
17
|
+
* @returns A map of stack name to {@link SyncStatus}; empty for stacks that have never
|
|
18
|
+
* synced.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```tsx
|
|
22
|
+
* const SyncBadge = ({ stack }: { stack: string }) => {
|
|
23
|
+
* const status = useSyncStatus(stack)[stack];
|
|
24
|
+
* if (!status) return <span>Not syncing</span>;
|
|
25
|
+
* if (status.state === 'error') return <span>Offline - retrying</span>;
|
|
26
|
+
* return <span>Synced {status.lastConvergedAt ? timeAgo(status.lastConvergedAt) : 'never'}</span>;
|
|
27
|
+
* };
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export const useSyncStatus = (stackName?: string): Record<string, SyncStatus> => {
|
|
31
|
+
const docStack = useDocStack();
|
|
32
|
+
const [statuses, setStatuses] = useState<Record<string, SyncStatus>>({});
|
|
33
|
+
|
|
34
|
+
const collect = useCallback((): Record<string, SyncStatus> => {
|
|
35
|
+
if (!docStack) return {};
|
|
36
|
+
const stacks = stackName
|
|
37
|
+
? [docStack.getStack(stackName)].filter(Boolean)
|
|
38
|
+
: docStack.getStacks();
|
|
39
|
+
|
|
40
|
+
const next: Record<string, SyncStatus> = {};
|
|
41
|
+
for (const stack of stacks) {
|
|
42
|
+
const status = stack!.getSyncStatus();
|
|
43
|
+
if (status) next[stack!.name] = status;
|
|
44
|
+
}
|
|
45
|
+
return next;
|
|
46
|
+
}, [docStack, stackName]);
|
|
47
|
+
|
|
48
|
+
useEffect(() => {
|
|
49
|
+
if (!docStack) return;
|
|
50
|
+
|
|
51
|
+
let subscribed: { target: EventTarget; }[] = [];
|
|
52
|
+
|
|
53
|
+
const onStatus = () => setStatuses(collect());
|
|
54
|
+
|
|
55
|
+
const subscribe = () => {
|
|
56
|
+
for (const { target } of subscribed) {
|
|
57
|
+
target.removeEventListener('sync-status', onStatus);
|
|
58
|
+
}
|
|
59
|
+
const stacks = stackName
|
|
60
|
+
? [docStack.getStack(stackName)].filter(Boolean)
|
|
61
|
+
: docStack.getStacks();
|
|
62
|
+
subscribed = stacks.map(stack => ({ target: stack as unknown as EventTarget }));
|
|
63
|
+
for (const { target } of subscribed) {
|
|
64
|
+
target.addEventListener('sync-status', onStatus);
|
|
65
|
+
}
|
|
66
|
+
onStatus();
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
// The set of stacks is not fixed: one joined at runtime has to be picked up.
|
|
70
|
+
docStack.addEventListener('stack-added', subscribe);
|
|
71
|
+
docStack.addEventListener('stack-removed', subscribe);
|
|
72
|
+
subscribe();
|
|
73
|
+
|
|
74
|
+
return () => {
|
|
75
|
+
docStack.removeEventListener('stack-added', subscribe);
|
|
76
|
+
docStack.removeEventListener('stack-removed', subscribe);
|
|
77
|
+
for (const { target } of subscribed) {
|
|
78
|
+
target.removeEventListener('sync-status', onStatus);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}, [docStack, stackName, collect]);
|
|
82
|
+
|
|
83
|
+
return statuses;
|
|
84
|
+
};
|
package/src/index.ts
CHANGED
|
@@ -2,9 +2,43 @@ import StackProvider, {DocStackContext, useDocStack} from "./components/StackPro
|
|
|
2
2
|
import { useFind, useQuerySQL } from "./hooks/index.js";
|
|
3
3
|
import { useClass, useClassList, useClassDocs, useClassCreate } from "./hooks/class.js";
|
|
4
4
|
import { useDomainList, useDomain, useDomainRelations, useDomainCreate } from "./hooks/domain.js";
|
|
5
|
+
import { useSyncStatus } from "./hooks/sync.js";
|
|
5
6
|
|
|
6
7
|
export { StackProvider, DocStackContext, useDocStack };
|
|
7
|
-
export { useFind, useQuerySQL };
|
|
8
|
+
export { useFind, useQuerySQL, useSyncStatus };
|
|
8
9
|
|
|
9
10
|
export { useClassList, useClass, useClassDocs, useClassCreate };
|
|
10
|
-
export { useDomainList, useDomain, useDomainRelations, useDomainCreate };
|
|
11
|
+
export { useDomainList, useDomain, useDomainRelations, useDomainCreate };
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Document-modelling types, re-exported from `@docstack/client`.
|
|
15
|
+
*
|
|
16
|
+
* Sourced from the client rather than `@docstack/shared` on purpose: the two packages
|
|
17
|
+
* would otherwise resolve their own copies of `@docstack/shared`, and a consumer using
|
|
18
|
+
* both could end up holding two structurally-identical-but-distinct `Patch` types.
|
|
19
|
+
* One source means one copy.
|
|
20
|
+
*/
|
|
21
|
+
export type {
|
|
22
|
+
AttributeType,
|
|
23
|
+
AttributeTypeConfig,
|
|
24
|
+
AttributeModel,
|
|
25
|
+
ClassModel,
|
|
26
|
+
DomainModel,
|
|
27
|
+
TriggerModel,
|
|
28
|
+
Document,
|
|
29
|
+
RelationDocument,
|
|
30
|
+
Patch,
|
|
31
|
+
SelectAST,
|
|
32
|
+
UnionAST,
|
|
33
|
+
ClientCredentials,
|
|
34
|
+
DocstackReady,
|
|
35
|
+
StackConfig,
|
|
36
|
+
StackOptions,
|
|
37
|
+
SyncDirection,
|
|
38
|
+
SyncState,
|
|
39
|
+
SyncStatus,
|
|
40
|
+
StackSyncOptions,
|
|
41
|
+
DocStackSyncOptions,
|
|
42
|
+
RemoteResolver,
|
|
43
|
+
InternalDocFilterOptions,
|
|
44
|
+
} from "@docstack/client";
|
package/lib/index.js.LICENSE.txt
DELETED
package/lib/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","mappings":";qOAWIA,EAAqBC,OAAOC,IAAI,8BACZD,OAAOC,IAAI,kBAoBnCC,EAAQC,IAnBR,SAAiBC,EAAMC,EAAQC,GAC7B,IAAIC,EAAM,KAGV,QAFA,IAAWD,IAAaC,EAAM,GAAKD,QACnC,IAAWD,EAAOE,MAAQA,EAAM,GAAKF,EAAOE,KACxC,QAASF,EAEX,IAAK,IAAIG,KADTF,EAAW,CAAC,EACSD,EACnB,QAAUG,IAAaF,EAASE,GAAYH,EAAOG,SAChDF,EAAWD,EAElB,OADAA,EAASC,EAASG,IACX,CACLC,SAAUX,EACVK,KAAMA,EACNG,IAAKA,EACLE,SAAK,IAAWJ,EAASA,EAAS,KAClCM,MAAOL,EAEX,C,aC3BEM,EAAOV,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B2D,EAAOK,aAAavE,GAC9CkD,EAAQnG,QAAUwD,EAClBD,EAAQ4C,EAAQnG,QACpB,CACA,MAAOkD,GACHN,EAASM,EACb,CACA,QACIR,GAAW,EACf,CACA,MAAMkB,EAAkBC,IACpB,MAAMwB,EAAMxB,EAAOyB,OAAOD,IAC1B,GAAKA,EAAIE,OAUJ,CAEDrF,QAAQC,IAAI,kDAAmD,CAAEkF,QACjE,MAAMG,EAAWW,EAAQnG,QAAQyF,UAAW7G,GAAMA,EAAE+G,KAAON,EAAIM,MAC9C,GAAbH,GAEAtF,QAAQC,IAAI,yCAA0C,CAAEkF,QACxDc,EAAQnG,QAAU,IACXmG,EAAQnG,QAAQ4F,MAAM,EAAGJ,GAC5BH,KACGc,EAAQnG,QAAQ4F,MAAMJ,EAAW,EAAGW,EAAQnG,QAAQC,WAK3DC,QAAQC,IAAI,uCAAwC,CAAEkF,QACtDc,EAAQnG,QAAQoF,KAAKC,GAE7B,KA5BiB,CAEb,MAAMG,EAAWW,EAAQnG,QAAQyF,UAAW7G,GAAMA,EAAE+G,KAAON,EAAIM,MAC9C,GAAbH,IACAW,EAAQnG,QAAU,IACXmG,EAAQnG,QAAQ4F,MAAM,EAAGJ,MACzBW,EAAQnG,QAAQ4F,MAAMJ,EAAW,EAAGW,EAAQnG,QAAQC,SAGnE,CAoBAsD,EAAQ,IAAI4C,EAAQnG,WAGxB,OADAmH,EAAOrG,iBAAiB,MAAO8C,GACxB,KACHuD,EAAOrD,oBAAoB,MAAOF,GAE1C,IAED,CAACuD,EAAQpD,KAAKC,UAAUf,KACpB,CAAEK,OAAMb,UAASE,iB","sources":["webpack://@docstack/react/./node_modules/react/cjs/react-jsx-runtime.production.js","webpack://@docstack/react/./node_modules/react/jsx-runtime.js","webpack://@docstack/react/webpack/bootstrap","webpack://@docstack/react/webpack/runtime/define property getters","webpack://@docstack/react/webpack/runtime/hasOwnProperty shorthand","webpack://@docstack/react/./src/components/StackProvider/index.tsx","webpack://@docstack/react/./src/hooks/index.ts","webpack://@docstack/react/./src/hooks/class.ts","webpack://@docstack/react/./src/hooks/domain.ts"],"sourcesContent":["/**\n * @license React\n * react-jsx-runtime.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nfunction jsxProd(type, config, maybeKey) {\n var key = null;\n void 0 !== maybeKey && (key = \"\" + maybeKey);\n void 0 !== config.key && (key = \"\" + config.key);\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n config = maybeKey.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== config ? config : null,\n props: maybeKey\n };\n}\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { createContext, useContext, useRef, useCallback, useEffect, useState } from 'react';\nimport { DocStack } from '@docstack/client'; // Import your DocStack class\n// You can give it a default value, e.g., null, which can be checked later.\n/**\n * Context object for the DocStack instance.\n * It provides the current DocStack instance or null if not initialized.\n */\nexport const DocStackContext = createContext(null);\n/**\n * Hook to access the DocStack instance.\n *\n * @returns The current {@link DocStack} instance or null if not yet initialized.\n *\n * @example\n * ```tsx\n * const MyComponent = () => {\n * const docStack = useDocStack();\n *\n * if (!docStack) return <div>Loading...</div>;\n *\n * return <div>Connected to {docStack.getStacks().length} stacks</div>;\n * };\n * ```\n */\nexport const useDocStack = () => {\n return useContext(DocStackContext);\n};\n/**\n * A provider component that initializes the DocStack client and makes it available\n * to child components via the {@link useDocStack} hook.\n * It handles the asynchronous initialization of the stack(s).\n *\n * @example\n * ```tsx\n * import { StackProvider } from '@docstack/react';\n *\n * const App = () => (\n * <StackProvider config={[{ name: 'my-db' }]}>\n * <MyApp />\n * </StackProvider>\n * );\n * ```\n */\nconst StackProvider = (props) => {\n const { config, children, credentials } = props;\n // Use a ref to store the DocStack instance\n const docStackRef = useRef(null);\n const [docStack, setDocStack] = useState(null);\n const setsDocStackWhenReady = useCallback(() => {\n setDocStack(docStackRef.current);\n }, []);\n useEffect(() => {\n if (docStackRef.current === null && config.length) {\n console.log(\"DocStack provider - init instance\", { config });\n const mergedConfig = config.map((cfg, idx) => {\n const cred = Array.isArray(credentials) ? credentials[idx] : credentials;\n if (typeof cfg === \"string\") {\n return cred ? { connection: cfg, credentials: cred } : cfg;\n }\n return cred ? Object.assign(Object.assign({}, cfg), { credentials: cred }) : cfg;\n });\n const instance = new DocStack(...mergedConfig);\n docStackRef.current = instance;\n docStackRef.current.addEventListener(\"ready\", setsDocStackWhenReady);\n }\n // Optional: Cleanup function to remove listeners\n return () => {\n if (docStackRef.current) {\n // docStackRef.current.removeEventListener(\"ready\", setsDocStackWhenReady);\n // docStackRef.current.getStore().removeAllListeners();\n }\n };\n }, [config, credentials, setsDocStackWhenReady]);\n return (_jsx(DocStackContext.Provider, { value: docStack, children: children }));\n};\nexport default StackProvider;\n","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\n// src/hooks/useFind.js\nimport { useContext, useEffect, useRef, useState } from 'react';\nimport { DocStackContext } from '../components/StackProvider/index.js';\n/**\n * Hook to execute a SQL query against a specific stack.\n *\n * @param stack - The name of the stack to query.\n * @param sql - The SQL query string.\n * @param params - Optional parameters for the SQL query.\n * @returns Object containing the query result (rows and AST), loading state, and error.\n *\n * @example\n * ```tsx\n * const UserList = () => {\n * const { result, loading } = useQuerySQL('my-stack', 'SELECT * FROM User WHERE age > ?', 18);\n *\n * if (loading) return <div>Loading...</div>;\n *\n * return (\n * <ul>\n * {result.rows.map(user => <li key={user._id}>{user.name}</li>)}\n * </ul>\n * );\n * };\n * ```\n */\nexport const useQuerySQL = (stack, sql, ...params) => {\n const docStack = useContext(DocStackContext);\n const [result, setResult] = useState({ rows: [], ast: [] });\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n // [TODO] Solve bounce of component because of StrictMode or other reasons\n const queryRef = useRef(false);\n useEffect(() => {\n if (!docStack) {\n // Handle the case where the provider is not yet initialized or missing\n // You could throw an error or return an empty state.\n console.error('useClassList must be used within a DocStackProvider.');\n setLoading(false);\n return;\n }\n const runQuery = () => __awaiter(void 0, void 0, void 0, function* () {\n try {\n const stackInstance = docStack.getStack(stack);\n if (stackInstance) {\n // Run the initial query\n console.log(\"Preparing to run query\", { sql, params });\n // debugger\n const queryResult = yield stackInstance.query(sql, ...params);\n setResult(queryResult);\n }\n else {\n console.log(\"Could not find corresponding stack\", { stack });\n }\n }\n catch (err) {\n console.log(\"Got error while running query\", { error: err });\n setError(err);\n }\n finally {\n setLoading(false);\n }\n });\n if (!queryRef.current) {\n queryRef.current = true;\n setLoading(true);\n runQuery();\n }\n else {\n console.log(\"Already performing query\");\n }\n return () => {\n //\n };\n }, [docStack, stack, params]);\n return { loading, result, error };\n};\n/**\n * Hook to find documents in a stack using a Mango selector.\n *\n * @param stack - The name of the stack to query.\n * @param query - Object containing the selector and optional fields projection.\n * @param sort - Optional sort criteria.\n * @param limit - Maximum number of documents to return (default: 50).\n * @returns Object containing the list of documents, loading state, and error.\n *\n * @example\n * ```tsx\n * const ActiveTasks = () => {\n * const { docs, loading } = useFind('my-stack', {\n * selector: {\n * \"~class\": \"Task\",\n * active: true\n * },\n * fields: ['_id', 'title']\n * });\n *\n * if (loading) return <div>Loading...</div>;\n *\n * return (\n * <ul>\n * {docs.map(doc => <li key={doc._id}>{doc.title}</li>)}\n * </ul>\n * );\n * };\n * ```\n */\nexport const useFind = (stack, query, sort, limit = 50) => {\n const docStack = useContext(DocStackContext);\n const [docs, setDocs] = useState([]);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n useEffect(() => {\n // Check if the docStack instance is available\n if (!docStack) {\n // Handle the case where the provider is not yet initialized or missing\n // You could throw an error or return an empty state.\n console.error('useFind must be used within a DocStackProvider.');\n setLoading(false);\n return;\n }\n setLoading(true);\n const runQuery = () => __awaiter(void 0, void 0, void 0, function* () {\n try {\n const stackInstance = docStack.getStack(stack);\n if (stackInstance) {\n // Run the initial query\n const initialDocs = yield stackInstance.findDocuments(query.selector, query.fields);\n if (initialDocs.docs.length) {\n let docs = initialDocs.docs; // [TODO] Check types\n setDocs(docs);\n }\n }\n }\n catch (err) {\n setError(err);\n }\n finally {\n setLoading(false);\n }\n });\n runQuery();\n // Set up the listener for changes\n const changeListener = (change) => {\n // Logic to handle the change and update the docs state\n // This part is crucial for real-time updates.\n // You'll need to re-run the query or intelligently update the docs array\n // based on the change object (add, update, delete).\n // A simple way is to re-run the query.\n // runQuery();\n };\n // [TODO] Implement events\n docStack.addEventListener('change', changeListener);\n // Cleanup function: remove the listener when the component unmounts\n return () => {\n docStack.removeEventListener('change', changeListener);\n };\n }, [docStack, JSON.stringify(query)]); // Re-run if docStack or query changes\n return { docs, loading, error };\n};\nexport const useClassCreate = () => {\n};\n","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nimport { useContext, useCallback, useEffect, useRef, useState } from \"react\";\nimport { DocStackContext } from \"../components/StackProvider/index.js\";\nimport { Class } from \"@docstack/client\";\n/**\n * Hook to create a new Class in a specific stack.\n *\n * @param stack - The name of the stack to create the class in.\n * @returns A callback function to create the class.\n *\n * @example\n * ```tsx\n * const MyComponent = () => {\n * const createClass = useClassCreate('my-stack');\n *\n * const handleCreate = async () => {\n * const newClass = await createClass('NewClass', 'Description of new class');\n * if (newClass) {\n * console.log('Class created:', newClass.name);\n * }\n * };\n *\n * return <button onClick={handleCreate}>Create Class</button>;\n * };\n * ```\n */\nexport const useClassCreate = (stack) => {\n const docStack = useContext(DocStackContext);\n return useCallback((className, classDesc) => __awaiter(void 0, void 0, void 0, function* () {\n try {\n if (!docStack) {\n // Handle the case where the provider is not yet initialized or missing\n // You could throw an error or return an empty state.\n console.error('useClassCreate must be used within a DocStackProvider.');\n // setLoading(false);\n return Promise.resolve(null);\n }\n // Run the initial query\n const stackInstance = docStack.getStack(stack);\n if (stackInstance) {\n const classObj_ = yield Class.create(stackInstance, className, \"class\", classDesc);\n yield stackInstance.addClass(classObj_);\n return classObj_;\n }\n return null;\n }\n catch (err) {\n // setError(err);\n console.error(err);\n return null;\n }\n }), [docStack, stack]);\n};\n/**\n * Hook to retrieve a list of classes from a stack based on a selector.\n * Maintains a real-time list of classes matching the selector.\n *\n * @param stack - The name of the stack to query.\n * @param selector - Mango selector to filter classes.\n * @returns Object containing the list of classes, loading state, and error.\n *\n * @example\n * ```tsx\n * const ClassList = () => {\n * const { classList, loading } = useClassList('my-stack', {\n * name: { $regex: '^User' }\n * });\n *\n * if (loading) return <div>Loading...</div>;\n *\n * return (\n * <ul>\n * {classList.map(cls => <li key={cls.id}>{cls.name}</li>)}\n * </ul>\n * );\n * };\n * ```\n */\nexport const useClassList = (stack, selector) => {\n const docStack = useContext(DocStackContext);\n const [originClass, setOriginClass] = useState();\n const [classList, setClassList] = useState([]);\n const classListRef = useRef([]);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n useEffect(() => {\n // Only run if the docStack is available and a className is provided\n if (!docStack) {\n setLoading(false);\n return;\n }\n const fetchClass = () => __awaiter(void 0, void 0, void 0, function* () {\n setLoading(true);\n setError(null);\n try {\n const stackInstance = docStack.getStack(stack);\n if (stackInstance) {\n const retrievedClass = yield stackInstance.getClass('class');\n if (retrievedClass) {\n setOriginClass(retrievedClass);\n }\n }\n }\n catch (err) {\n setError(err);\n setLoading(false);\n }\n });\n fetchClass();\n return () => {\n // clean what?\n };\n }, [docStack, stack]); // Dependency on docStack and stack\n useEffect(() => {\n if (!originClass) {\n return;\n }\n const runQueryAndListen = () => __awaiter(void 0, void 0, void 0, function* () {\n setLoading(true);\n try {\n const initialClassModelList = yield originClass.getCards(selector);\n const initialClassList = [];\n const stackInstance = docStack.getStack(stack);\n for (const cls of initialClassModelList) {\n const classInstance = yield Class.buildFromModel(stackInstance, cls);\n initialClassList.push(classInstance);\n }\n classListRef.current = initialClassList;\n setClassList(classListRef.current);\n }\n catch (err) {\n setError(err);\n }\n finally {\n setLoading(false);\n }\n const changeListener = (change) => {\n const doc = change.detail.doc;\n console.log(\"useClassDocs - detail\", { detail: change.detail });\n if (!doc.active) {\n // A doc was deleted\n console.log(\"useClassDocs - a doc was deleted\", { doc });\n const docIndex = classListRef.current.findIndex((d) => d.id == doc._id);\n if (docIndex != -1) {\n classListRef.current = [\n ...classListRef.current.slice(0, docIndex),\n ...classListRef.current.slice(docIndex + 1, classListRef.current.length)\n ];\n }\n }\n else {\n // A doc was changed or added\n const docIndex = classListRef.current.findIndex((d) => d.id == doc._id);\n if (docIndex != -1) {\n // A doc was changed\n classListRef.current = [\n ...classListRef.current.slice(0, docIndex),\n doc,\n ...classListRef.current.slice(docIndex + 1, classListRef.current.length)\n ];\n }\n else {\n // A doc was added\n classListRef.current.push(doc);\n }\n }\n setClassList([...classListRef.current]);\n };\n originClass.addEventListener('doc', changeListener);\n return () => {\n originClass.removeEventListener('doc', changeListener);\n };\n });\n runQueryAndListen();\n }, [originClass, JSON.stringify(selector)]); // Dependency on classObj and query\n return { classList, loading, error };\n};\n/**\n * Hook to retrieve a single Class instance by name.\n *\n * @param stack - The name of the stack.\n * @param className - The name of the class to retrieve.\n * @returns Object containing the Class instance, loading state, and error.\n *\n * @example\n * ```tsx\n * const ClassDetails = () => {\n * const { classObj, loading } = useClass('my-stack', 'User');\n *\n * if (loading) return <div>Loading...</div>;\n * if (!classObj) return <div>Class not found</div>;\n *\n * return <div>Class Description: {classObj.description}</div>;\n * };\n * ```\n */\nexport const useClass = (stack, className) => {\n const docStack = useContext(DocStackContext);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState();\n const [classObj, setClass] = useState();\n const reqRef = useRef(false);\n useEffect(() => {\n if (!docStack) {\n // Handle the case where the provider is not yet initialized or missing\n // You could throw an error or return an empty state.\n console.error('useClass must be used within a DocStackProvider.');\n setLoading(false);\n return;\n }\n const fetchClass = () => __awaiter(void 0, void 0, void 0, function* () {\n try {\n const stackInstance = docStack.getStack(stack);\n if (stackInstance) {\n const res = yield stackInstance.getClass(className);\n // TODO: manage class model (schema!) updates\n if (res) {\n setClass(res);\n }\n }\n }\n catch (e) {\n setError(e);\n }\n finally {\n setLoading(false);\n }\n });\n if (!reqRef.current) {\n reqRef.current = true;\n setLoading(true);\n fetchClass();\n }\n return () => {\n // reqRef.current = false;\n };\n }, [docStack, stack, className]);\n return { loading, error, classObj };\n};\n/**\n * Hook to retrieve documents (cards) of a specific class.\n * Maintains a real-time list of documents matching the query.\n *\n * @param stack - The name of the stack.\n * @param className - The class name to fetch documents for.\n * @param query - Optional Mango selector to filter documents.\n * @returns Object containing the list of documents, loading state, and error.\n *\n * @example\n * ```tsx\n * const UserList = () => {\n * const { docs, loading } = useClassDocs('my-stack', 'User', {\n * age: { $gt: 18 }\n * });\n *\n * if (loading) return <div>Loading...</div>;\n *\n * return (\n * <ul>\n * {docs.map(doc => <li key={doc._id}>{doc.name}</li>)}\n * </ul>\n * );\n * };\n * ```\n */\nexport const useClassDocs = (stack, className, query = {}) => {\n const docStack = useContext(DocStackContext);\n const [classObj, setClass] = useState();\n const [docs, setDocs] = useState([]);\n const docsRef = useRef([]);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n useEffect(() => {\n // Only run if the docStack is available and a className is provided\n if (!docStack || !className) {\n setLoading(false);\n return;\n }\n const fetchClass = () => __awaiter(void 0, void 0, void 0, function* () {\n setLoading(true);\n setError(null);\n try {\n const stackInstance = docStack.getStack(stack);\n if (stackInstance) {\n const retrievedClass = yield stackInstance.getClass(className);\n if (retrievedClass) {\n setClass(retrievedClass);\n }\n }\n }\n catch (err) {\n setError(err);\n setLoading(false);\n }\n });\n fetchClass();\n return () => {\n // clean what?\n };\n }, [docStack, stack, className]); // Dependency on docStack and className\n useEffect(() => {\n if (!classObj) {\n return;\n }\n const runQueryAndListen = () => __awaiter(void 0, void 0, void 0, function* () {\n setLoading(true);\n try {\n debugger;\n const initialDocs = yield classObj.getCards(query);\n docsRef.current = initialDocs;\n setDocs(docsRef.current);\n }\n catch (err) {\n setError(err);\n }\n finally {\n setLoading(false);\n }\n const changeListener = (change) => {\n const doc = change.detail.doc;\n console.log(\"useClassDocs - detail\", { detail: change.detail });\n if (!doc.active) {\n // A doc was deleted\n console.log(\"useClassDocs - a doc was deleted\", { doc });\n const docIndex = docsRef.current.findIndex((d) => d._id == doc._id);\n if (docIndex != -1) {\n docsRef.current = [\n ...docsRef.current.slice(0, docIndex),\n ...docsRef.current.slice(docIndex + 1, docsRef.current.length)\n ];\n }\n }\n else {\n // A doc was changed or added\n console.log(\"useClassDocs - a doc was changed or added\", { doc });\n const docIndex = docsRef.current.findIndex((d) => d._id == doc._id);\n if (docIndex != -1) {\n // A doc was changed\n console.log(\"useClassDocs - a doc was changed\", { doc });\n docsRef.current = [\n ...docsRef.current.slice(0, docIndex),\n doc,\n ...docsRef.current.slice(docIndex + 1, docsRef.current.length)\n ];\n }\n else {\n // A doc was added\n console.log(\"useClassDocs - a doc was added\", { doc });\n docsRef.current.push(doc);\n }\n }\n setDocs([...docsRef.current]);\n };\n classObj.addEventListener('doc', changeListener);\n return () => {\n classObj.removeEventListener('doc', changeListener);\n };\n });\n runQueryAndListen();\n }, [classObj, JSON.stringify(query)]); // Dependency on classObj and query\n return { docs, loading, error };\n};\n","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nimport { useContext, useCallback, useEffect, useRef, useState } from \"react\";\nimport { DocStackContext } from \"../components/StackProvider/index.js\";\nimport { Domain } from \"@docstack/shared\";\n/**\n * Hook to create a new Domain in a specific stack.\n *\n * @param stack - The name of the stack to create the domain in.\n * @returns A callback function to create the domain.\n *\n * @example\n * ```tsx\n * const CreateDomain = () => {\n * const createDomain = useDomainCreate('my-stack');\n * // Assume sourceClass and targetClass are available Class instances\n *\n * const handleCreate = async () => {\n * const newDomain = await createDomain(\n * 'UserProjects',\n * '1:N',\n * userClass,\n * projectClass,\n * 'User has many projects'\n * );\n * };\n *\n * return <button onClick={handleCreate}>Create Domain</button>;\n * };\n * ```\n */\nexport const useDomainCreate = (stack) => {\n const docStack = useContext(DocStackContext);\n return useCallback((domainName, cardinality, sourceClass, targetClass, domainDesc) => __awaiter(void 0, void 0, void 0, function* () {\n try {\n if (!docStack) {\n // Handle the case where the provider is not yet initialized or missing\n // You could throw an error or return an empty state.\n console.error('useDomainCreate must be used within a DocStackProvider.');\n // setLoading(false);\n return Promise.resolve(null);\n }\n // Run the initial query\n const stackInstance = docStack.getStack(stack);\n if (stackInstance) {\n const domain = yield Domain.create(stackInstance, null, domainName, \"domain\", cardinality, sourceClass, targetClass, domainDesc);\n return domain;\n }\n return null;\n }\n catch (err) {\n // setError(err);\n console.error(err);\n return null;\n }\n }), [docStack, stack]);\n};\n/**\n * Hook to retrieve a list of domains from a stack based on a selector.\n * Maintains a real-time list of domains matching the selector.\n *\n * @param stack - The name of the stack to query.\n * @param selector - Mango selector to filter domains.\n * @returns Object containing the list of domains, loading state, and error.\n *\n * @example\n * ```tsx\n * const DomainList = () => {\n * const { domainList, loading } = useDomainList('my-stack', {\n * relation: { $eq: '1:N' }\n * });\n *\n * if (loading) return <div>Loading...</div>;\n *\n * return (\n * <ul>\n * {domainList.map(d => <li key={d.id}>{d.name} ({d.relation})</li>)}\n * </ul>\n * );\n * };\n * ```\n */\nexport const useDomainList = (stack, selector) => {\n const docStack = useContext(DocStackContext);\n const [originClass, setOriginClass] = useState();\n const [domainList, setDomainList] = useState([]);\n const domainListRef = useRef([]);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n useEffect(() => {\n // Only run if the docStack is available and a className is provided\n if (!docStack) {\n setLoading(false);\n return;\n }\n const fetchClass = () => __awaiter(void 0, void 0, void 0, function* () {\n setLoading(true);\n setError(null);\n try {\n const stackInstance = docStack.getStack(stack);\n if (stackInstance) {\n const retrievedClass = yield stackInstance.getClass('domain');\n if (retrievedClass) {\n setOriginClass(retrievedClass);\n }\n }\n }\n catch (err) {\n setError(err);\n setLoading(false);\n }\n });\n fetchClass();\n return () => {\n // clean what?\n };\n }, [docStack, stack]); // Dependency on docStack and stack\n useEffect(() => {\n if (!originClass) {\n return;\n }\n const runQueryAndListen = () => __awaiter(void 0, void 0, void 0, function* () {\n setLoading(true);\n try {\n const stackInstance = docStack.getStack(stack);\n const initialDomainModelList = yield originClass.getCards(selector);\n const initDomainList = yield Promise.all(initialDomainModelList.map((dm) => __awaiter(void 0, void 0, void 0, function* () { return yield Domain.buildFromModel(stackInstance, dm); })));\n domainListRef.current = initDomainList;\n setDomainList(domainListRef.current);\n }\n catch (err) {\n setError(err);\n }\n finally {\n setLoading(false);\n }\n const changeListener = (change) => {\n const doc = change.detail.doc;\n if (!doc.active) {\n // A doc was deleted\n const docIndex = domainListRef.current.findIndex((d) => d.id == doc._id);\n if (docIndex != -1) {\n domainListRef.current = [\n ...domainListRef.current.slice(0, docIndex),\n ...domainListRef.current.slice(docIndex + 1, domainListRef.current.length)\n ];\n }\n }\n else {\n // A doc was changed or added\n const docIndex = domainListRef.current.findIndex((d) => d.id == doc._id);\n if (docIndex != -1) {\n // A doc was changed\n domainListRef.current = [\n ...domainListRef.current.slice(0, docIndex),\n doc,\n ...domainListRef.current.slice(docIndex + 1, domainListRef.current.length)\n ];\n }\n else {\n // A doc was added\n domainListRef.current.push(doc);\n }\n }\n setDomainList([...domainListRef.current]);\n };\n originClass.addEventListener('doc', changeListener);\n return () => {\n originClass.removeEventListener('doc', changeListener);\n };\n });\n runQueryAndListen();\n }, [originClass, JSON.stringify(selector)]); // Dependency on classObj and query\n return { domainList, loading, error };\n};\n/**\n * Hook to retrieve a single Domain instance by name.\n *\n * @param stack - The name of the stack.\n * @param domainName - The name of the domain to retrieve.\n * @returns Object containing the Domain instance, loading state, and error.\n *\n * @example\n * ```tsx\n * const DomainDetails = () => {\n * const { domain, loading } = useDomain('my-stack', 'UserProjects');\n *\n * if (loading) return <div>Loading...</div>;\n * if (!domain) return <div>Domain not found</div>;\n *\n * return <div>Relation Type: {domain.relation}</div>;\n * };\n * ```\n */\nexport const useDomain = (stack, domainName) => {\n const docStack = useContext(DocStackContext);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState();\n const [domain, setDomain] = useState();\n const reqRef = useRef(false);\n useEffect(() => {\n if (!docStack) {\n // Handle the case where the provider is not yet initialized or missing\n // You could throw an error or return an empty state.\n console.error('useDomain must be used within a DocStackProvider.');\n setLoading(false);\n return;\n }\n const fetchClass = () => __awaiter(void 0, void 0, void 0, function* () {\n try {\n const stackInstance = docStack.getStack(stack);\n if (stackInstance) {\n const res = yield stackInstance.getDomain(domainName);\n // TODO: manage class model (schema!) updates\n if (res) {\n setDomain(res);\n }\n }\n }\n catch (e) {\n setError(e);\n }\n finally {\n setLoading(false);\n }\n });\n if (!reqRef.current) {\n reqRef.current = true;\n setLoading(true);\n fetchClass();\n }\n return () => {\n // reqRef.current = false;\n };\n }, [docStack, stack, domainName]);\n return { loading, error, domain };\n};\n/**\n * Hook to retrieve relation documents for a specific domain.\n * Maintains a real-time list of relations matching the query.\n *\n * @param stack - The name of the stack.\n * @param domainName - The domain name to fetch relations for.\n * @param query - Optional Mango selector to filter relations.\n * @returns Object containing the list of relation documents, loading state, and error.\n *\n * @example\n * ```tsx\n * const ProjectTasks = () => {\n * const { docs, loading } = useDomainRelations('my-stack', 'ProjectTasks', {\n * sourceId: { $eq: 'Project-123' }\n * });\n *\n * if (loading) return <div>Loading...</div>;\n *\n * return (\n * <ul>\n * {docs.map(rel => (\n * <li key={rel._id}>Linked Task: {rel.targetId}</li>\n * ))}\n * </ul>\n * );\n * };\n * ```\n */\nexport const useDomainRelations = (stack, domainName, query = {}) => {\n const docStack = useContext(DocStackContext);\n const [domain, setDomain] = useState();\n const [docs, setDocs] = useState([]);\n const docsRef = useRef([]);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n useEffect(() => {\n // Only run if the docStack is available and a className is provided\n if (!docStack || !domainName) {\n setLoading(false);\n return;\n }\n const fetchClass = () => __awaiter(void 0, void 0, void 0, function* () {\n setLoading(true);\n setError(null);\n try {\n const stackInstance = docStack.getStack(stack);\n if (stackInstance) {\n const retrievedDomain = yield stackInstance.getDomain(domainName);\n if (retrievedDomain) {\n setDomain(retrievedDomain);\n }\n }\n }\n catch (err) {\n setError(err);\n setLoading(false);\n }\n });\n fetchClass();\n return () => {\n // clean what?\n };\n }, [docStack, stack, domainName]); // Dependency on docStack and className\n useEffect(() => {\n if (!domain) {\n return;\n }\n const runQueryAndListen = () => __awaiter(void 0, void 0, void 0, function* () {\n setLoading(true);\n try {\n const initialDocs = yield domain.getRelations(query);\n docsRef.current = initialDocs;\n setDocs(docsRef.current);\n }\n catch (err) {\n setError(err);\n }\n finally {\n setLoading(false);\n }\n const changeListener = (change) => {\n const doc = change.detail.doc;\n if (!doc.active) {\n // A doc was deleted\n const docIndex = docsRef.current.findIndex((d) => d._id == doc._id);\n if (docIndex != -1) {\n docsRef.current = [\n ...docsRef.current.slice(0, docIndex),\n ...docsRef.current.slice(docIndex + 1, docsRef.current.length)\n ];\n }\n }\n else {\n // A doc was changed or added\n console.log(\"useDomainRelations - a doc was changed or added\", { doc });\n const docIndex = docsRef.current.findIndex((d) => d._id == doc._id);\n if (docIndex != -1) {\n // A doc was changed\n console.log(\"useDomainRelations - a doc was changed\", { doc });\n docsRef.current = [\n ...docsRef.current.slice(0, docIndex),\n doc,\n ...docsRef.current.slice(docIndex + 1, docsRef.current.length)\n ];\n }\n else {\n // A doc was added\n console.log(\"useDomainRelations - a doc was added\", { doc });\n docsRef.current.push(doc);\n }\n }\n setDocs([...docsRef.current]);\n };\n domain.addEventListener('doc', changeListener);\n return () => {\n domain.removeEventListener('doc', changeListener);\n };\n });\n runQueryAndListen();\n }, [domain, JSON.stringify(query)]); // Dependency on classObj and query\n return { docs, loading, error };\n};\n"],"names":["REACT_ELEMENT_TYPE","Symbol","for","exports","jsx","type","config","maybeKey","key","propName","ref","$$typeof","props","module","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","d","definition","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","DocStackContext","useDocStack","children","credentials","docStackRef","docStack","setDocStack","setsDocStackWhenReady","current","length","console","log","mergedConfig","map","cfg","idx","cred","Array","isArray","connection","assign","instance","addEventListener","Provider","value","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","step","next","e","rejected","result","done","then","apply","useQuerySQL","stack","sql","params","setResult","rows","ast","loading","setLoading","error","setError","queryRef","stackInstance","getStack","queryResult","query","err","useFind","sort","limit","docs","setDocs","initialDocs","findDocuments","selector","fields","changeListener","change","removeEventListener","JSON","stringify","className","classDesc","classObj_","create","addClass","useClassList","originClass","setOriginClass","classList","setClassList","classListRef","retrievedClass","getClass","initialClassModelList","getCards","initialClassList","cls","classInstance","buildFromModel","push","doc","detail","active","docIndex","findIndex","id","_id","slice","useClass","classObj","setClass","reqRef","res","useClassDocs","docsRef","useDomainCreate","domainName","cardinality","sourceClass","targetClass","domainDesc","useDomainList","domainList","setDomainList","domainListRef","initialDomainModelList","initDomainList","all","dm","useDomain","domain","setDomain","getDomain","useDomainRelations","retrievedDomain","getRelations"],"ignoreList":[],"sourceRoot":""}
|