@copilotkit/react-core 0.17.0-alpha.1 → 0.17.0-alpha.3
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/.turbo/turbo-build.log +70 -70
- package/CHANGELOG.md +12 -0
- package/dist/components/copilot-provider/copilot-provider-props.mjs +1 -2
- package/dist/components/copilot-provider/copilot-provider-props.mjs.map +1 -1
- package/dist/components/copilot-provider/copilot-provider.mjs +468 -7
- package/dist/components/copilot-provider/copilot-provider.mjs.map +1 -1
- package/dist/components/copilot-provider/index.mjs +467 -8
- package/dist/components/copilot-provider/index.mjs.map +1 -1
- package/dist/components/copilot-provider/standard-copilot-api-config.mjs +12 -3
- package/dist/components/copilot-provider/standard-copilot-api-config.mjs.map +1 -1
- package/dist/components/index.mjs +467 -9
- package/dist/components/index.mjs.map +1 -1
- package/dist/context/copilot-context.mjs +70 -3
- package/dist/context/copilot-context.mjs.map +1 -1
- package/dist/context/index.mjs +69 -4
- package/dist/context/index.mjs.map +1 -1
- package/dist/hooks/index.mjs +646 -17
- package/dist/hooks/index.mjs.map +1 -1
- package/dist/hooks/use-chat.mjs +452 -5
- package/dist/hooks/use-chat.mjs.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +591 -13
- package/dist/hooks/use-copilot-chat.mjs.map +1 -1
- package/dist/hooks/use-flat-category-store.mjs +68 -3
- package/dist/hooks/use-flat-category-store.mjs.map +1 -1
- package/dist/hooks/use-make-copilot-actionable.mjs +95 -4
- package/dist/hooks/use-make-copilot-actionable.mjs.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +87 -4
- package/dist/hooks/use-make-copilot-document-readable.mjs.map +1 -1
- package/dist/hooks/use-make-copilot-readable.mjs +87 -4
- package/dist/hooks/use-make-copilot-readable.mjs.map +1 -1
- package/dist/hooks/use-tree.mjs +153 -3
- package/dist/hooks/use-tree.mjs.map +1 -1
- package/dist/index.mjs +1194 -26
- package/dist/index.mjs.map +1 -1
- package/dist/openai/chat-completion-client.mjs +353 -4
- package/dist/openai/chat-completion-client.mjs.map +1 -1
- package/dist/openai/chat-completion-stream.mjs +217 -4
- package/dist/openai/chat-completion-stream.mjs.map +1 -1
- package/dist/openai/chat-completion-transport.mjs +179 -3
- package/dist/openai/chat-completion-transport.mjs.map +1 -1
- package/dist/openai/index.mjs +217 -5
- package/dist/openai/index.mjs.map +1 -1
- package/dist/openai-assistants/hooks/index.mjs +235 -14
- package/dist/openai-assistants/hooks/index.mjs.map +1 -1
- package/dist/openai-assistants/hooks/use-assistants.mjs +52 -8
- package/dist/openai-assistants/hooks/use-assistants.mjs.map +1 -1
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +236 -13
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs.map +1 -1
- package/dist/openai-assistants/index.mjs +236 -15
- package/dist/openai-assistants/index.mjs.map +1 -1
- package/dist/openai-assistants/utils/index.mjs +46 -4
- package/dist/openai-assistants/utils/index.mjs.map +1 -1
- package/dist/openai-assistants/utils/process-message-stream.mjs +46 -3
- package/dist/openai-assistants/utils/process-message-stream.mjs.map +1 -1
- package/dist/types/annotated-function.mjs +0 -2
- package/dist/types/annotated-function.mjs.map +1 -1
- package/dist/types/base.mjs +0 -2
- package/dist/types/base.mjs.map +1 -1
- package/dist/types/document-pointer.mjs +0 -2
- package/dist/types/document-pointer.mjs.map +1 -1
- package/dist/types/index.mjs +0 -2
- package/dist/types/index.mjs.map +1 -1
- package/dist/types/message.mjs +0 -2
- package/dist/types/message.mjs.map +1 -1
- package/dist/utils/utils.mjs +0 -2
- package/dist/utils/utils.mjs.map +1 -1
- package/dist/utils/utils.test.mjs +0 -1
- package/dist/utils/utils.test.mjs.map +1 -1
- package/package.json +3 -3
- package/src/hooks/use-chat.ts +1 -3
- package/dist/chunk-5UGLWBZJ.mjs +0 -3
- package/dist/chunk-5UGLWBZJ.mjs.map +0 -1
- package/dist/chunk-6A4PCNMZ.mjs +0 -48
- package/dist/chunk-6A4PCNMZ.mjs.map +0 -1
- package/dist/chunk-6SOQYBNX.mjs +0 -44
- package/dist/chunk-6SOQYBNX.mjs.map +0 -1
- package/dist/chunk-7GFKOIO7.mjs +0 -3
- package/dist/chunk-7GFKOIO7.mjs.map +0 -1
- package/dist/chunk-7P4OYNP3.mjs +0 -19
- package/dist/chunk-7P4OYNP3.mjs.map +0 -1
- package/dist/chunk-BABVSMJR.mjs +0 -3
- package/dist/chunk-BABVSMJR.mjs.map +0 -1
- package/dist/chunk-EFZPSZWO.mjs +0 -3
- package/dist/chunk-EFZPSZWO.mjs.map +0 -1
- package/dist/chunk-F2JIAPZQ.mjs +0 -13
- package/dist/chunk-F2JIAPZQ.mjs.map +0 -1
- package/dist/chunk-FP4EXCGS.mjs +0 -27
- package/dist/chunk-FP4EXCGS.mjs.map +0 -1
- package/dist/chunk-FRAKUJWH.mjs +0 -3
- package/dist/chunk-FRAKUJWH.mjs.map +0 -1
- package/dist/chunk-HW5IH6PV.mjs +0 -19
- package/dist/chunk-HW5IH6PV.mjs.map +0 -1
- package/dist/chunk-JD7BAH7U.mjs +0 -3
- package/dist/chunk-JD7BAH7U.mjs.map +0 -1
- package/dist/chunk-MRXNTQOX.mjs +0 -55
- package/dist/chunk-MRXNTQOX.mjs.map +0 -1
- package/dist/chunk-MZ5UN3BY.mjs +0 -28
- package/dist/chunk-MZ5UN3BY.mjs.map +0 -1
- package/dist/chunk-PUFR5OAI.mjs +0 -3
- package/dist/chunk-PUFR5OAI.mjs.map +0 -1
- package/dist/chunk-QTET3FBV.mjs +0 -165
- package/dist/chunk-QTET3FBV.mjs.map +0 -1
- package/dist/chunk-SM3XH2NJ.mjs +0 -77
- package/dist/chunk-SM3XH2NJ.mjs.map +0 -1
- package/dist/chunk-SPCZTZCY.mjs +0 -3
- package/dist/chunk-SPCZTZCY.mjs.map +0 -1
- package/dist/chunk-TDH7XE4X.mjs +0 -104
- package/dist/chunk-TDH7XE4X.mjs.map +0 -1
- package/dist/chunk-TKXPMMND.mjs +0 -177
- package/dist/chunk-TKXPMMND.mjs.map +0 -1
- package/dist/chunk-TU4DNDO7.mjs +0 -125
- package/dist/chunk-TU4DNDO7.mjs.map +0 -1
- package/dist/chunk-VK25FIML.mjs +0 -144
- package/dist/chunk-VK25FIML.mjs.map +0 -1
- package/dist/chunk-VNRDQJXW.mjs +0 -3
- package/dist/chunk-VNRDQJXW.mjs.map +0 -1
- package/dist/chunk-VUY2K2DI.mjs +0 -135
- package/dist/chunk-VUY2K2DI.mjs.map +0 -1
- package/dist/chunk-YULKJPY3.mjs +0 -70
- package/dist/chunk-YULKJPY3.mjs.map +0 -1
package/dist/chunk-TU4DNDO7.mjs
DELETED
|
@@ -1,125 +0,0 @@
|
|
|
1
|
-
import { processMessageStream } from './chunk-MZ5UN3BY.mjs';
|
|
2
|
-
import { defaultCopilotContextCategories } from './chunk-QTET3FBV.mjs';
|
|
3
|
-
import { CopilotContext } from './chunk-6A4PCNMZ.mjs';
|
|
4
|
-
import { __async, __spreadValues } from './chunk-MRXNTQOX.mjs';
|
|
5
|
-
import { useContext, useState, useMemo } from 'react';
|
|
6
|
-
import { parseStreamPart } from '@copilotkit/shared';
|
|
7
|
-
|
|
8
|
-
function useCopilotChatV2(options) {
|
|
9
|
-
const {
|
|
10
|
-
getContextString,
|
|
11
|
-
getChatCompletionFunctionDescriptions,
|
|
12
|
-
getFunctionCallHandler,
|
|
13
|
-
copilotApiConfig
|
|
14
|
-
} = useContext(CopilotContext);
|
|
15
|
-
const [messages, setMessages] = useState([]);
|
|
16
|
-
const [input, setInput] = useState("");
|
|
17
|
-
const [threadId, setThreadId] = useState(void 0);
|
|
18
|
-
const [status, setStatus] = useState("awaiting_message");
|
|
19
|
-
const [error, setError] = useState(void 0);
|
|
20
|
-
useMemo(() => {
|
|
21
|
-
const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage;
|
|
22
|
-
const contextString = getContextString([], defaultCopilotContextCategories);
|
|
23
|
-
return {
|
|
24
|
-
id: "system",
|
|
25
|
-
content: systemMessageMaker(contextString),
|
|
26
|
-
role: "system"
|
|
27
|
-
};
|
|
28
|
-
}, [getContextString, options.makeSystemMessage]);
|
|
29
|
-
const handleInputChange = (e) => {
|
|
30
|
-
setInput(e.target.value);
|
|
31
|
-
};
|
|
32
|
-
const submitMessage = (e) => __async(this, null, function* () {
|
|
33
|
-
var _a, _b;
|
|
34
|
-
e.preventDefault();
|
|
35
|
-
if (input === "") {
|
|
36
|
-
return;
|
|
37
|
-
}
|
|
38
|
-
setStatus("in_progress");
|
|
39
|
-
setMessages((messages2) => [...messages2, { id: "", role: "user", content: input }]);
|
|
40
|
-
setInput("");
|
|
41
|
-
const apiUrl = copilotApiConfig.chatApiEndpointV2;
|
|
42
|
-
const functions = getChatCompletionFunctionDescriptions();
|
|
43
|
-
const result = yield fetch(apiUrl, {
|
|
44
|
-
method: "POST",
|
|
45
|
-
headers: __spreadValues(__spreadValues({
|
|
46
|
-
"Content-Type": "application/json"
|
|
47
|
-
}, copilotApiConfig.headers), options.headers),
|
|
48
|
-
body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues({
|
|
49
|
-
// always use user-provided threadId when available:
|
|
50
|
-
threadId: (_b = (_a = options.threadId) != null ? _a : threadId) != null ? _b : null,
|
|
51
|
-
message: input
|
|
52
|
-
}, functions.length > 0 && { functions }), copilotApiConfig.body), options.body))
|
|
53
|
-
});
|
|
54
|
-
if (result.body == null) {
|
|
55
|
-
throw new Error("The response body is empty.");
|
|
56
|
-
}
|
|
57
|
-
yield processMessageStream(result.body.getReader(), (message) => {
|
|
58
|
-
try {
|
|
59
|
-
const { type, value } = parseStreamPart(message);
|
|
60
|
-
switch (type) {
|
|
61
|
-
case "assistant_message": {
|
|
62
|
-
setMessages((messages2) => [
|
|
63
|
-
...messages2,
|
|
64
|
-
{
|
|
65
|
-
id: value.id,
|
|
66
|
-
role: value.role,
|
|
67
|
-
content: value.content[0].text.value
|
|
68
|
-
}
|
|
69
|
-
]);
|
|
70
|
-
break;
|
|
71
|
-
}
|
|
72
|
-
case "assistant_control_data": {
|
|
73
|
-
setThreadId(value.threadId);
|
|
74
|
-
setMessages((messages2) => {
|
|
75
|
-
const lastMessage = messages2[messages2.length - 1];
|
|
76
|
-
lastMessage.id = value.messageId;
|
|
77
|
-
return [...messages2.slice(0, messages2.length - 1), lastMessage];
|
|
78
|
-
});
|
|
79
|
-
break;
|
|
80
|
-
}
|
|
81
|
-
case "error": {
|
|
82
|
-
setError(value);
|
|
83
|
-
break;
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
} catch (error2) {
|
|
87
|
-
setError(error2);
|
|
88
|
-
}
|
|
89
|
-
});
|
|
90
|
-
setStatus("awaiting_message");
|
|
91
|
-
});
|
|
92
|
-
return {
|
|
93
|
-
messages,
|
|
94
|
-
input,
|
|
95
|
-
handleInputChange,
|
|
96
|
-
submitMessage,
|
|
97
|
-
status,
|
|
98
|
-
error
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
function defaultSystemMessage(contextString) {
|
|
102
|
-
return `
|
|
103
|
-
Please act as an efficient, competent, conscientious, and industrious professional assistant.
|
|
104
|
-
|
|
105
|
-
Help the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.
|
|
106
|
-
Always be polite and respectful, and prefer brevity over verbosity.
|
|
107
|
-
|
|
108
|
-
The user has provided you with the following context:
|
|
109
|
-
\`\`\`
|
|
110
|
-
${contextString}
|
|
111
|
-
\`\`\`
|
|
112
|
-
|
|
113
|
-
They have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.
|
|
114
|
-
|
|
115
|
-
Please assist them as best you can.
|
|
116
|
-
|
|
117
|
-
You can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.
|
|
118
|
-
|
|
119
|
-
If you would like to call a function, call it without saying anything else.
|
|
120
|
-
`;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
export { defaultSystemMessage, useCopilotChatV2 };
|
|
124
|
-
//# sourceMappingURL=out.js.map
|
|
125
|
-
//# sourceMappingURL=chunk-TU4DNDO7.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/openai-assistants/hooks/use-copilot-chat-v2.ts"],"names":["messages","error"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,YAAY,SAAS,gBAAgB;AAE9C,SAAkB,uBAAuB;AA6ClC,SAAS,iBAAiB,SAA0D;AACzF,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,WAAW,cAAc;AAE7B,QAAM,CAAC,UAAU,WAAW,IAAI,SAAoB,CAAC,CAAC;AACtD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAS,EAAE;AACrC,QAAM,CAAC,UAAU,WAAW,IAAI,SAA6B,MAAS;AACtE,QAAM,CAAC,QAAQ,SAAS,IAAI,SAA0B,kBAAkB;AACxE,QAAM,CAAC,OAAO,QAAQ,IAAI,SAA8B,MAAS;AAEjE,QAAM,gBAAyB,QAAQ,MAAM;AAC3C,UAAM,qBAAqB,QAAQ,qBAAqB;AACxD,UAAM,gBAAgB,iBAAiB,CAAC,GAAG,+BAA+B;AAE1E,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,SAAS,mBAAmB,aAAa;AAAA,MACzC,MAAM;AAAA,IACR;AAAA,EACF,GAAG,CAAC,kBAAkB,QAAQ,iBAAiB,CAAC;AAEhD,QAAM,oBAAoB,CAAC,MAAW;AACpC,aAAS,EAAE,OAAO,KAAK;AAAA,EACzB;AAEA,QAAM,gBAAgB,CAAO,MAAW;AA5E1C;AA6EI,MAAE,eAAe;AAEjB,QAAI,UAAU,IAAI;AAChB;AAAA,IACF;AAEA,cAAU,aAAa;AAEvB,gBAAY,CAACA,cAAa,CAAC,GAAGA,WAAU,EAAE,IAAI,IAAI,MAAM,QAAQ,SAAS,MAAM,CAAC,CAAC;AAEjF,aAAS,EAAE;AAEX,UAAM,SAA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EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,qBAAqB,eAA+B;AAClE,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWF","sourcesContent":["import { useContext, useMemo, useState } from \"react\";\nimport { processMessageStream } from \"../utils\";\nimport { Message, parseStreamPart } from \"@copilotkit/shared\";\nimport { CopilotContext } from \"../../context\";\nimport { defaultCopilotContextCategories } from \"../../components\";\n\nexport type AssistantStatus = \"in_progress\" | \"awaiting_message\";\n\nexport interface RequestForwardingOptions {\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * Extra body object to be sent with the API request.\n * @example\n * Send a `sessionId` to the API along with the messages.\n * ```js\n * useChat({\n * body: {\n * sessionId: '123',\n * }\n * })\n * ```\n */\n body?: object;\n}\nexport interface UseCopilotChatOptionsV2 extends RequestForwardingOptions {\n makeSystemMessage?: (contextString: string) => string;\n threadId?: string | undefined;\n}\n\nexport interface UseCopilotChatV2Result {\n messages: Message[];\n input: string;\n handleInputChange: (e: any) => void;\n submitMessage: (e: any) => Promise<void>;\n status: AssistantStatus;\n error: unknown;\n}\n\nexport function useCopilotChatV2(options: UseCopilotChatOptionsV2): UseCopilotChatV2Result {\n const {\n getContextString,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n copilotApiConfig,\n } = useContext(CopilotContext);\n\n const [messages, setMessages] = useState<Message[]>([]);\n const [input, setInput] = useState(\"\");\n const [threadId, setThreadId] = useState<string | undefined>(undefined);\n const [status, setStatus] = useState<AssistantStatus>(\"awaiting_message\");\n const [error, setError] = useState<unknown | undefined>(undefined);\n\n const systemMessage: Message = useMemo(() => {\n const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage;\n const contextString = getContextString([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return {\n id: \"system\",\n content: systemMessageMaker(contextString),\n role: \"system\",\n };\n }, [getContextString, options.makeSystemMessage]);\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const submitMessage = async (e: any) => {\n e.preventDefault();\n\n if (input === \"\") {\n return;\n }\n\n setStatus(\"in_progress\");\n\n setMessages((messages) => [...messages, { id: \"\", role: \"user\", content: input }]);\n\n setInput(\"\");\n\n const apiUrl = copilotApiConfig.chatApiEndpointV2;\n\n const functions = getChatCompletionFunctionDescriptions();\n\n const result = await fetch(apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...copilotApiConfig.headers,\n ...options.headers,\n },\n body: JSON.stringify({\n // always use user-provided threadId when available:\n threadId: options.threadId ?? threadId ?? null,\n message: input,\n ...(functions.length > 0 && { functions: functions }),\n ...copilotApiConfig.body,\n ...options.body,\n }),\n });\n\n if (result.body == null) {\n throw new Error(\"The response body is empty.\");\n }\n\n await processMessageStream(result.body.getReader(), (message: string) => {\n try {\n const { type, value } = parseStreamPart(message);\n\n switch (type) {\n case \"assistant_message\": {\n // append message:\n setMessages((messages) => [\n ...messages,\n {\n id: value.id,\n role: value.role,\n content: value.content[0].text.value,\n },\n ]);\n break;\n }\n\n case \"assistant_control_data\": {\n setThreadId(value.threadId);\n\n // set id of last message:\n setMessages((messages) => {\n const lastMessage = messages[messages.length - 1];\n lastMessage.id = value.messageId;\n return [...messages.slice(0, messages.length - 1), lastMessage];\n });\n\n break;\n }\n\n case \"error\": {\n setError(value);\n break;\n }\n }\n } catch (error) {\n setError(error);\n }\n });\n\n setStatus(\"awaiting_message\");\n };\n\n return {\n messages,\n input,\n handleInputChange,\n submitMessage,\n status,\n error,\n };\n}\n\nexport function defaultSystemMessage(contextString: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\n`;\n}\n"]}
|
package/dist/chunk-VK25FIML.mjs
DELETED
|
@@ -1,144 +0,0 @@
|
|
|
1
|
-
import { __async, __spreadValues } from './chunk-MRXNTQOX.mjs';
|
|
2
|
-
import EventEmitter from 'eventemitter3';
|
|
3
|
-
|
|
4
|
-
var DEFAULT_MODEL = "gpt-4-1106-preview";
|
|
5
|
-
var ChatCompletionTransport = class extends EventEmitter {
|
|
6
|
-
constructor(params) {
|
|
7
|
-
super();
|
|
8
|
-
this.buffer = new Uint8Array();
|
|
9
|
-
this.bodyReader = null;
|
|
10
|
-
}
|
|
11
|
-
cleanup() {
|
|
12
|
-
return __async(this, null, function* () {
|
|
13
|
-
if (this.bodyReader) {
|
|
14
|
-
try {
|
|
15
|
-
yield this.bodyReader.cancel();
|
|
16
|
-
} catch (error) {
|
|
17
|
-
console.warn("Failed to cancel body reader:", error);
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
this.bodyReader = null;
|
|
21
|
-
this.buffer = new Uint8Array();
|
|
22
|
-
});
|
|
23
|
-
}
|
|
24
|
-
fetch(_0) {
|
|
25
|
-
return __async(this, arguments, function* ({
|
|
26
|
-
copilotConfig,
|
|
27
|
-
model,
|
|
28
|
-
messages,
|
|
29
|
-
functions,
|
|
30
|
-
temperature,
|
|
31
|
-
headers,
|
|
32
|
-
body,
|
|
33
|
-
signal
|
|
34
|
-
}) {
|
|
35
|
-
yield this.cleanup();
|
|
36
|
-
temperature || (temperature = 0.5);
|
|
37
|
-
functions || (functions = []);
|
|
38
|
-
model || (model = DEFAULT_MODEL);
|
|
39
|
-
const cleanedMessages = messages.map((message) => {
|
|
40
|
-
const { content, role, name, function_call } = message;
|
|
41
|
-
return { content, role, name, function_call };
|
|
42
|
-
});
|
|
43
|
-
try {
|
|
44
|
-
const response = yield fetch(copilotConfig.chatApiEndpoint, {
|
|
45
|
-
method: "POST",
|
|
46
|
-
headers: __spreadValues(__spreadValues({
|
|
47
|
-
"Content-Type": "application/json"
|
|
48
|
-
}, copilotConfig.headers), headers ? __spreadValues({}, headers) : {}),
|
|
49
|
-
body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
|
|
50
|
-
model,
|
|
51
|
-
messages: cleanedMessages,
|
|
52
|
-
stream: true
|
|
53
|
-
}, functions.length ? { functions } : {}), temperature ? { temperature } : {}), functions.length != 0 ? { function_call: "auto" } : {}), copilotConfig.body), body ? __spreadValues({}, body) : {})),
|
|
54
|
-
signal
|
|
55
|
-
});
|
|
56
|
-
if (!response.ok) {
|
|
57
|
-
try {
|
|
58
|
-
const errorText = yield response.text();
|
|
59
|
-
yield this.cleanup();
|
|
60
|
-
const msg = `Error ${response.status}: ${errorText}`;
|
|
61
|
-
this.emit("error", new Error(msg));
|
|
62
|
-
} catch (_error) {
|
|
63
|
-
yield this.cleanup();
|
|
64
|
-
const msg = `Error ${response.status}: ${response.statusText}`;
|
|
65
|
-
this.emit("error", new Error(msg));
|
|
66
|
-
}
|
|
67
|
-
return;
|
|
68
|
-
}
|
|
69
|
-
if (response.body == null) {
|
|
70
|
-
yield this.cleanup();
|
|
71
|
-
const msg = "Response body is null";
|
|
72
|
-
this.emit("error", new Error(msg));
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
75
|
-
this.bodyReader = response.body.getReader();
|
|
76
|
-
yield this.streamBody();
|
|
77
|
-
} catch (error) {
|
|
78
|
-
yield this.cleanup();
|
|
79
|
-
this.emit("error", error);
|
|
80
|
-
return;
|
|
81
|
-
}
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
streamBody() {
|
|
85
|
-
return __async(this, null, function* () {
|
|
86
|
-
while (true) {
|
|
87
|
-
try {
|
|
88
|
-
const { done, value } = yield this.bodyReader.read();
|
|
89
|
-
if (done) {
|
|
90
|
-
yield this.cleanup();
|
|
91
|
-
this.emit("end");
|
|
92
|
-
return;
|
|
93
|
-
}
|
|
94
|
-
const shouldContinue = yield this.processData(value);
|
|
95
|
-
if (!shouldContinue) {
|
|
96
|
-
return;
|
|
97
|
-
}
|
|
98
|
-
} catch (error) {
|
|
99
|
-
yield this.cleanup();
|
|
100
|
-
this.emit("error", error);
|
|
101
|
-
return;
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
});
|
|
105
|
-
}
|
|
106
|
-
processData(data) {
|
|
107
|
-
return __async(this, null, function* () {
|
|
108
|
-
const newBuffer = new Uint8Array(this.buffer.length + data.length);
|
|
109
|
-
newBuffer.set(this.buffer);
|
|
110
|
-
newBuffer.set(data, this.buffer.length);
|
|
111
|
-
this.buffer = newBuffer;
|
|
112
|
-
const dataString = new TextDecoder("utf-8").decode(this.buffer);
|
|
113
|
-
let lines = dataString.split("\n").filter((line) => line.trim() !== "");
|
|
114
|
-
if (!dataString.endsWith("\n")) {
|
|
115
|
-
const lastLine = lines.pop() || "";
|
|
116
|
-
const remainingBytes = new TextEncoder().encode(lastLine);
|
|
117
|
-
this.buffer = new Uint8Array(remainingBytes);
|
|
118
|
-
} else {
|
|
119
|
-
this.buffer = new Uint8Array();
|
|
120
|
-
}
|
|
121
|
-
for (const line of lines) {
|
|
122
|
-
const cleanedLine = line.replace(/^data: /, "");
|
|
123
|
-
if (cleanedLine === "[DONE]") {
|
|
124
|
-
yield this.cleanup();
|
|
125
|
-
this.emit("end");
|
|
126
|
-
return false;
|
|
127
|
-
}
|
|
128
|
-
let json;
|
|
129
|
-
try {
|
|
130
|
-
json = JSON.parse(cleanedLine);
|
|
131
|
-
} catch (error) {
|
|
132
|
-
console.error("Failed to parse JSON:", error);
|
|
133
|
-
continue;
|
|
134
|
-
}
|
|
135
|
-
this.emit("data", json);
|
|
136
|
-
}
|
|
137
|
-
return true;
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
};
|
|
141
|
-
|
|
142
|
-
export { ChatCompletionTransport };
|
|
143
|
-
//# sourceMappingURL=out.js.map
|
|
144
|
-
//# sourceMappingURL=chunk-VK25FIML.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/openai/chat-completion-transport.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,kBAAkB;AAwBzB,IAAM,gBAAgB;AAEf,IAAM,0BAAN,cAAsC,aAA4C;AAAA,EAIvF,YAAY,QAA8C;AACxD,UAAM;AAJR,SAAQ,SAAS,IAAI,WAAW;AAChC,SAAQ,aAA6D;AAAA,EAIrE;AAAA,EAEc,UAAU;AAAA;AACtB,UAAI,KAAK,YAAY;AACnB,YAAI;AACF,gBAAM,KAAK,WAAW,OAAO;AAAA,QAC/B,SAAS,OAAP;AACA,kBAAQ,KAAK,iCAAiC,KAAK;AAAA,QACrD;AAAA,MACF;AACA,WAAK,aAAa;AAClB,WAAK,SAAS,IAAI,WAAW;AAAA,IAC/B;AAAA;AAAA,EAEa,MAAM,IASmC;AAAA,+CATnC;AAAA,MACjB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,GAAsD;AACpD,YAAM,KAAK,QAAQ;AAEnB,oCAAgB;AAChB,gCAAc,CAAC;AACf,wBAAU;AAGV,YAAM,kBAAkB,SAAS,IAAI,CAAC,YAAY;AAChD,cAAM,EAAE,SAAS,MAAM,MAAM,cAAc,IAAI;AAC/C,eAAO,EAAE,SAAS,MAAM,MAAM,cAAc;AAAA,MAC9C,CAAC;AAED,UAAI;AACF,cAAM,WAAW,MAA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from \"eventemitter3\";\nimport { Message, Function } from \"../types\";\nimport { CopilotApiConfig } from \"../context\";\n\nexport interface ChatCompletionTransportConfiguration {}\n\ninterface ChatCompletionTransportEvents {\n end: void;\n data: any;\n error: any;\n}\n\nexport interface ChatCompletionTransportFetchParams {\n copilotConfig: CopilotApiConfig;\n model?: string;\n messages: Message[];\n functions?: Function[];\n temperature?: number;\n maxTokens?: number;\n headers?: Record<string, string> | Headers;\n body?: object;\n signal?: AbortSignal;\n}\n\nconst DEFAULT_MODEL = \"gpt-4-1106-preview\";\n\nexport class ChatCompletionTransport extends EventEmitter<ChatCompletionTransportEvents> {\n private buffer = new Uint8Array();\n private bodyReader: ReadableStreamDefaultReader<Uint8Array> | null = null;\n\n constructor(params: ChatCompletionTransportConfiguration) {\n super();\n }\n\n private async cleanup() {\n if (this.bodyReader) {\n try {\n await this.bodyReader.cancel();\n } catch (error) {\n console.warn(\"Failed to cancel body reader:\", error);\n }\n }\n this.bodyReader = null;\n this.buffer = new Uint8Array();\n }\n\n public async fetch({\n copilotConfig,\n model,\n messages,\n functions,\n temperature,\n headers,\n body,\n signal,\n }: ChatCompletionTransportFetchParams): Promise<void> {\n await this.cleanup();\n\n temperature ||= 0.5;\n functions ||= [];\n model ||= DEFAULT_MODEL;\n\n // clean up any extra properties from messages\n const cleanedMessages = messages.map((message) => {\n const { content, role, name, function_call } = message;\n return { content, role, name, function_call };\n });\n\n try {\n const response = await fetch(copilotConfig.chatApiEndpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...copilotConfig.headers,\n ...(headers ? { ...headers } : {}),\n },\n body: JSON.stringify({\n model,\n messages: cleanedMessages,\n stream: true,\n ...(functions.length ? { functions } : {}),\n ...(temperature ? { temperature } : {}),\n ...(functions.length != 0 ? { function_call: \"auto\" } : {}),\n ...copilotConfig.body,\n ...(body ? { ...body } : {}),\n }),\n signal,\n });\n\n if (!response.ok) {\n try {\n const errorText = await response.text();\n await this.cleanup();\n const msg = `Error ${response.status}: ${errorText}`;\n this.emit(\"error\", new Error(msg));\n } catch (_error) {\n await this.cleanup();\n const msg = `Error ${response.status}: ${response.statusText}`;\n this.emit(\"error\", new Error(msg));\n }\n return;\n }\n\n if (response.body == null) {\n await this.cleanup();\n const msg = \"Response body is null\";\n this.emit(\"error\", new Error(msg));\n return;\n }\n\n this.bodyReader = response.body.getReader();\n\n await this.streamBody();\n } catch (error) {\n await this.cleanup();\n this.emit(\"error\", error);\n return;\n }\n }\n\n private async streamBody() {\n while (true) {\n try {\n const { done, value } = await this.bodyReader!.read();\n\n if (done) {\n await this.cleanup();\n this.emit(\"end\");\n return;\n }\n\n const shouldContinue = await this.processData(value);\n\n if (!shouldContinue) {\n return;\n }\n } catch (error) {\n await this.cleanup();\n this.emit(\"error\", error);\n return;\n }\n }\n }\n\n private async processData(data: Uint8Array): Promise<boolean> {\n // Append new data to the temp buffer\n const newBuffer = new Uint8Array(this.buffer.length + data.length);\n newBuffer.set(this.buffer);\n newBuffer.set(data, this.buffer.length);\n this.buffer = newBuffer;\n\n const dataString = new TextDecoder(\"utf-8\").decode(this.buffer);\n\n let lines = dataString.split(\"\\n\").filter((line) => line.trim() !== \"\");\n\n // If the last line isn't complete, keep it in the buffer for next time\n if (!dataString.endsWith(\"\\n\")) {\n const lastLine = lines.pop() || \"\";\n const remainingBytes = new TextEncoder().encode(lastLine);\n this.buffer = new Uint8Array(remainingBytes);\n } else {\n this.buffer = new Uint8Array();\n }\n\n for (const line of lines) {\n const cleanedLine = line.replace(/^data: /, \"\");\n\n if (cleanedLine === \"[DONE]\") {\n await this.cleanup();\n this.emit(\"end\");\n return false;\n }\n\n let json;\n try {\n json = JSON.parse(cleanedLine);\n } catch (error) {\n console.error(\"Failed to parse JSON:\", error);\n continue;\n }\n\n this.emit(\"data\", json);\n }\n return true;\n }\n}\n"]}
|
package/dist/chunk-VNRDQJXW.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":""}
|
package/dist/chunk-VUY2K2DI.mjs
DELETED
|
@@ -1,135 +0,0 @@
|
|
|
1
|
-
import { __spreadProps, __spreadValues } from './chunk-MRXNTQOX.mjs';
|
|
2
|
-
import { nanoid } from 'nanoid';
|
|
3
|
-
import { useReducer, useCallback } from 'react';
|
|
4
|
-
|
|
5
|
-
var removeNode = (nodes, id) => {
|
|
6
|
-
return nodes.reduce((result, node) => {
|
|
7
|
-
if (node.id !== id) {
|
|
8
|
-
const newNode = __spreadProps(__spreadValues({}, node), { children: removeNode(node.children, id) });
|
|
9
|
-
result.push(newNode);
|
|
10
|
-
}
|
|
11
|
-
return result;
|
|
12
|
-
}, []);
|
|
13
|
-
};
|
|
14
|
-
var addNode = (nodes, newNode, parentId) => {
|
|
15
|
-
if (!parentId) {
|
|
16
|
-
return [...nodes, newNode];
|
|
17
|
-
}
|
|
18
|
-
return nodes.map((node) => {
|
|
19
|
-
if (node.id === parentId) {
|
|
20
|
-
return __spreadProps(__spreadValues({}, node), { children: [...node.children, newNode] });
|
|
21
|
-
} else if (node.children.length) {
|
|
22
|
-
return __spreadProps(__spreadValues({}, node), { children: addNode(node.children, newNode, parentId) });
|
|
23
|
-
}
|
|
24
|
-
return node;
|
|
25
|
-
});
|
|
26
|
-
};
|
|
27
|
-
var treeIndentationRepresentation = (index, indentLevel) => {
|
|
28
|
-
if (indentLevel === 0) {
|
|
29
|
-
return (index + 1).toString();
|
|
30
|
-
} else if (indentLevel === 1) {
|
|
31
|
-
return String.fromCharCode(65 + index);
|
|
32
|
-
} else if (indentLevel === 2) {
|
|
33
|
-
return String.fromCharCode(97 + index);
|
|
34
|
-
} else {
|
|
35
|
-
return "-";
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
var printNode = (node, prefix = "", indentLevel = 0) => {
|
|
39
|
-
const indent = " ".repeat(3).repeat(indentLevel);
|
|
40
|
-
const prefixPlusIndentLength = prefix.length + indent.length;
|
|
41
|
-
const subsequentLinesPrefix = " ".repeat(prefixPlusIndentLength);
|
|
42
|
-
const valueLines = node.value.split("\n");
|
|
43
|
-
const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;
|
|
44
|
-
const outputSubsequentLines = valueLines.slice(1).map((line) => `${subsequentLinesPrefix}${line}`).join("\n");
|
|
45
|
-
let output = `${outputFirstLine}
|
|
46
|
-
`;
|
|
47
|
-
if (outputSubsequentLines) {
|
|
48
|
-
output += `${outputSubsequentLines}
|
|
49
|
-
`;
|
|
50
|
-
}
|
|
51
|
-
const childPrePrefix = " ".repeat(prefix.length);
|
|
52
|
-
node.children.forEach(
|
|
53
|
-
(child, index) => output += printNode(
|
|
54
|
-
child,
|
|
55
|
-
`${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `,
|
|
56
|
-
indentLevel + 1
|
|
57
|
-
)
|
|
58
|
-
);
|
|
59
|
-
return output;
|
|
60
|
-
};
|
|
61
|
-
function treeReducer(state, action) {
|
|
62
|
-
switch (action.type) {
|
|
63
|
-
case "ADD_NODE": {
|
|
64
|
-
const { value, parentId, id: newNodeId } = action;
|
|
65
|
-
const newNode = {
|
|
66
|
-
id: newNodeId,
|
|
67
|
-
value,
|
|
68
|
-
children: [],
|
|
69
|
-
categories: new Set(action.categories)
|
|
70
|
-
};
|
|
71
|
-
try {
|
|
72
|
-
return addNode(state, newNode, parentId);
|
|
73
|
-
} catch (error) {
|
|
74
|
-
console.error(`Error while adding node with id ${newNodeId}: ${error}`);
|
|
75
|
-
return state;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
case "REMOVE_NODE":
|
|
79
|
-
return removeNode(state, action.id);
|
|
80
|
-
default:
|
|
81
|
-
return state;
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
var useTree = () => {
|
|
85
|
-
const [tree, dispatch] = useReducer(treeReducer, []);
|
|
86
|
-
const addElement = useCallback(
|
|
87
|
-
(value, categories, parentId) => {
|
|
88
|
-
const newNodeId = nanoid();
|
|
89
|
-
dispatch({
|
|
90
|
-
type: "ADD_NODE",
|
|
91
|
-
value,
|
|
92
|
-
parentId,
|
|
93
|
-
id: newNodeId,
|
|
94
|
-
categories
|
|
95
|
-
});
|
|
96
|
-
return newNodeId;
|
|
97
|
-
},
|
|
98
|
-
[]
|
|
99
|
-
);
|
|
100
|
-
const removeElement = useCallback((id) => {
|
|
101
|
-
dispatch({ type: "REMOVE_NODE", id });
|
|
102
|
-
}, []);
|
|
103
|
-
const printTree = useCallback(
|
|
104
|
-
(categories) => {
|
|
105
|
-
const categoriesSet = new Set(categories);
|
|
106
|
-
let output = "";
|
|
107
|
-
tree.forEach((node, index) => {
|
|
108
|
-
if (!setsHaveIntersection(categoriesSet, node.categories)) {
|
|
109
|
-
return;
|
|
110
|
-
}
|
|
111
|
-
if (index !== 0) {
|
|
112
|
-
output += "\n";
|
|
113
|
-
}
|
|
114
|
-
output += printNode(node, `${treeIndentationRepresentation(index, 0)}. `);
|
|
115
|
-
});
|
|
116
|
-
return output;
|
|
117
|
-
},
|
|
118
|
-
[tree]
|
|
119
|
-
);
|
|
120
|
-
return { tree, addElement, printTree, removeElement };
|
|
121
|
-
};
|
|
122
|
-
var use_tree_default = useTree;
|
|
123
|
-
function setsHaveIntersection(setA, setB) {
|
|
124
|
-
const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
|
|
125
|
-
for (let item of smallerSet) {
|
|
126
|
-
if (largerSet.has(item)) {
|
|
127
|
-
return true;
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
return false;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
export { use_tree_default };
|
|
134
|
-
//# sourceMappingURL=out.js.map
|
|
135
|
-
//# sourceMappingURL=chunk-VUY2K2DI.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-tree.ts"],"names":[],"mappings":";;;;;;AAAA,SAAS,cAAc;AACvB,SAAS,aAAa,kBAAkB;AAkCxC,IAAM,aAAa,CAAC,OAAa,O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,OAAyB;AAC1D,aAAS,EAAE,MAAM,eAAe,GAAG,CAAC;AAAA,EACtC,GAAG,CAAC,CAAC;AAEL,QAAM,YAAY;AAAA,IAChB,CAAC,eAAiC;AAChC,YAAM,gBAAgB,IAAI,IAAI,UAAU;AAExC,UAAI,SAAS;AACb,WAAK,QAAQ,CAAC,MAAM,UAAU;AAE5B,YAAI,CAAC,qBAAqB,eAAe,KAAK,UAAU,GAAG;AACzD;AAAA,QACF;AAGA,YAAI,UAAU,GAAG;AACf,oBAAU;AAAA,QACZ;AAEA,kBAAU,UAAU,MAAM,GAAG,8BAA8B,OAAO,CAAC,KAAK;AAAA,MAC1E,CAAC;AACD,aAAO;AAAA,IACT;AAAA,IACA,CAAC,IAAI;AAAA,EACP;AAEA,SAAO,EAAE,MAAM,YAAY,WAAW,cAAc;AACtD;AAEA,IAAO,mBAAQ;AAEf,SAAS,qBAAwB,MAAc,MAAuB;AACpE,QAAM,CAAC,YAAY,SAAS,IAAI,KAAK,QAAQ,KAAK,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,IAAI;AAEnF,WAAS,QAAQ,YAAY;AAC3B,QAAI,UAAU,IAAI,IAAI,GAAG;AACvB,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT","sourcesContent":["import { nanoid } from \"nanoid\";\nimport { useCallback, useReducer } from \"react\";\n\nexport type TreeNodeId = string;\n\nexport interface TreeNode {\n id: TreeNodeId;\n value: string;\n children: TreeNode[];\n parentId?: TreeNodeId;\n categories: Set<string>;\n}\n\nexport type Tree = TreeNode[];\n\nexport interface UseTreeReturn {\n tree: Tree;\n addElement: (value: string, categories: string[], parentId?: TreeNodeId) => TreeNodeId;\n printTree: (categories: string[]) => string;\n removeElement: (id: TreeNodeId) => void;\n}\n\nconst findNode = (nodes: Tree, id: TreeNodeId): TreeNode | undefined => {\n for (const node of nodes) {\n if (node.id === id) {\n return node;\n }\n const result = findNode(node.children, id);\n if (result) {\n return result;\n }\n }\n return undefined;\n};\n\nconst removeNode = (nodes: Tree, id: TreeNodeId): Tree => {\n return nodes.reduce((result: Tree, node) => {\n if (node.id !== id) {\n const newNode = { ...node, children: removeNode(node.children, id) };\n result.push(newNode);\n }\n return result;\n }, []);\n};\n\nconst addNode = (nodes: Tree, newNode: TreeNode, parentId?: TreeNodeId): Tree => {\n if (!parentId) {\n return [...nodes, newNode];\n }\n return nodes.map((node) => {\n if (node.id === parentId) {\n return { ...node, children: [...node.children, newNode] };\n } else if (node.children.length) {\n return { ...node, children: addNode(node.children, newNode, parentId) };\n }\n return node;\n });\n};\n\nconst treeIndentationRepresentation = (index: number, indentLevel: number): string => {\n if (indentLevel === 0) {\n return (index + 1).toString();\n } else if (indentLevel === 1) {\n return String.fromCharCode(65 + index); // 65 is the ASCII value for 'A'\n } else if (indentLevel === 2) {\n return String.fromCharCode(97 + index); // 97 is the ASCII value for 'a'\n } else {\n return \"-\";\n }\n};\n\nconst printNode = (node: TreeNode, prefix = \"\", indentLevel = 0): string => {\n const indent = \" \".repeat(3).repeat(indentLevel);\n\n const prefixPlusIndentLength = prefix.length + indent.length;\n const subsequentLinesPrefix = \" \".repeat(prefixPlusIndentLength);\n\n const valueLines = node.value.split(\"\\n\");\n\n const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;\n const outputSubsequentLines = valueLines\n .slice(1)\n .map((line) => `${subsequentLinesPrefix}${line}`)\n .join(\"\\n\");\n\n let output = `${outputFirstLine}\\n`;\n if (outputSubsequentLines) {\n output += `${outputSubsequentLines}\\n`;\n }\n\n const childPrePrefix = \" \".repeat(prefix.length);\n\n node.children.forEach(\n (child, index) =>\n (output += printNode(\n child,\n `${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `,\n indentLevel + 1,\n )),\n );\n return output;\n};\n\n// Action types\ntype Action =\n | {\n type: \"ADD_NODE\";\n value: string;\n parentId?: string;\n id: string;\n categories: string[];\n }\n | { type: \"REMOVE_NODE\"; id: string };\n\n// Reducer function\nfunction treeReducer(state: Tree, action: Action): Tree {\n switch (action.type) {\n case \"ADD_NODE\": {\n const { value, parentId, id: newNodeId } = action;\n const newNode: TreeNode = {\n id: newNodeId,\n value,\n children: [],\n categories: new Set(action.categories),\n };\n\n try {\n return addNode(state, newNode, parentId);\n } catch (error) {\n console.error(`Error while adding node with id ${newNodeId}: ${error}`);\n return state;\n }\n }\n case \"REMOVE_NODE\":\n return removeNode(state, action.id);\n default:\n return state;\n }\n}\n\n// useTree hook\nconst useTree = (): UseTreeReturn => {\n const [tree, dispatch] = useReducer(treeReducer, []);\n\n const addElement = useCallback(\n (value: string, categories: string[], parentId?: string): TreeNodeId => {\n const newNodeId = nanoid(); // Generate new ID outside of dispatch\n dispatch({\n type: \"ADD_NODE\",\n value,\n parentId,\n id: newNodeId,\n categories: categories,\n });\n return newNodeId; // Return the new ID\n },\n [],\n );\n\n const removeElement = useCallback((id: TreeNodeId): void => {\n dispatch({ type: \"REMOVE_NODE\", id });\n }, []);\n\n const printTree = useCallback(\n (categories: string[]): string => {\n const categoriesSet = new Set(categories);\n\n let output = \"\";\n tree.forEach((node, index) => {\n // if the node does not have any of the desired categories, continue to the next node\n if (!setsHaveIntersection(categoriesSet, node.categories)) {\n return;\n }\n\n // add a new line before each node except the first one\n if (index !== 0) {\n output += \"\\n\";\n }\n\n output += printNode(node, `${treeIndentationRepresentation(index, 0)}. `);\n });\n return output;\n },\n [tree],\n );\n\n return { tree, addElement, printTree, removeElement };\n};\n\nexport default useTree;\n\nfunction setsHaveIntersection<T>(setA: Set<T>, setB: Set<T>): boolean {\n const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];\n\n for (let item of smallerSet) {\n if (largerSet.has(item)) {\n return true;\n }\n }\n\n return false;\n}\n"]}
|
package/dist/chunk-YULKJPY3.mjs
DELETED
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import { nanoid } from 'nanoid';
|
|
2
|
-
import { useReducer, useCallback } from 'react';
|
|
3
|
-
|
|
4
|
-
// src/hooks/use-flat-category-store.ts
|
|
5
|
-
var useFlatCategoryStore = () => {
|
|
6
|
-
const [elements, dispatch] = useReducer(flatCategoryStoreReducer, /* @__PURE__ */ new Map());
|
|
7
|
-
const addElement = useCallback((value, categories) => {
|
|
8
|
-
const newId = nanoid();
|
|
9
|
-
dispatch({
|
|
10
|
-
type: "ADD_ELEMENT",
|
|
11
|
-
value,
|
|
12
|
-
id: newId,
|
|
13
|
-
categories
|
|
14
|
-
});
|
|
15
|
-
return newId;
|
|
16
|
-
}, []);
|
|
17
|
-
const removeElement = useCallback((id) => {
|
|
18
|
-
dispatch({ type: "REMOVE_ELEMENT", id });
|
|
19
|
-
}, []);
|
|
20
|
-
const allElements = useCallback(
|
|
21
|
-
(categories) => {
|
|
22
|
-
const categoriesSet = new Set(categories);
|
|
23
|
-
const result = [];
|
|
24
|
-
elements.forEach((element) => {
|
|
25
|
-
if (setsHaveIntersection(categoriesSet, element.categories)) {
|
|
26
|
-
result.push(element.value);
|
|
27
|
-
}
|
|
28
|
-
});
|
|
29
|
-
return result;
|
|
30
|
-
},
|
|
31
|
-
[elements]
|
|
32
|
-
);
|
|
33
|
-
return { addElement, removeElement, allElements };
|
|
34
|
-
};
|
|
35
|
-
var use_flat_category_store_default = useFlatCategoryStore;
|
|
36
|
-
function flatCategoryStoreReducer(state, action) {
|
|
37
|
-
switch (action.type) {
|
|
38
|
-
case "ADD_ELEMENT": {
|
|
39
|
-
const { value, id, categories } = action;
|
|
40
|
-
const newElement = {
|
|
41
|
-
id,
|
|
42
|
-
value,
|
|
43
|
-
categories: new Set(categories)
|
|
44
|
-
};
|
|
45
|
-
const newState = new Map(state);
|
|
46
|
-
newState.set(id, newElement);
|
|
47
|
-
return newState;
|
|
48
|
-
}
|
|
49
|
-
case "REMOVE_ELEMENT": {
|
|
50
|
-
const newState = new Map(state);
|
|
51
|
-
newState.delete(action.id);
|
|
52
|
-
return newState;
|
|
53
|
-
}
|
|
54
|
-
default:
|
|
55
|
-
return state;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
function setsHaveIntersection(setA, setB) {
|
|
59
|
-
const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
|
|
60
|
-
for (let item of smallerSet) {
|
|
61
|
-
if (largerSet.has(item)) {
|
|
62
|
-
return true;
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
return false;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export { use_flat_category_store_default };
|
|
69
|
-
//# sourceMappingURL=out.js.map
|
|
70
|
-
//# sourceMappingURL=chunk-YULKJPY3.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-flat-category-store.ts"],"names":[],"mappings":";AAAA,SAAS,cAAc;AACvB,SAAS,aAAa,kBAAkB;AAgBxC,IAAM,uBAAuB,MAAwC;AACnE,QAAM,CAAC,UAAU,QAAQ,IAAI,WAE3B,0BAA0B,oBAAI,IAAsD,CAAC;AAEvF,QAAM,aAAa,YAAY,CAAC,OAAU,eAA8C;AACtF,UAAM,QAAQ,OAAO;AACrB,aAAS;AAAA,MACP,MAAM;AAAA,MACN;AAAA,MACA,IAAI;AAAA,MACJ;AAAA,IACF,CAAC;AACD,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AAEL,QAAM,gBAAgB,YAAY,CAAC,OAAkC;AACnE,aAAS,EAAE,MAAM,kBAAkB,GAAG,CAAC;AAAA,EACzC,GAAG,CAAC,CAAC;AAEL,QAAM,cAAc;AAAA,IAClB,CAAC,eAA8B;AAC7B,YAAM,gBAAgB,IAAI,IAAI,UAAU;AACxC,YAAM,SAAc,CAAC;AACrB,eAAS,QAAQ,CAAC,YAAY;AAC5B,YAAI,qBAAqB,eAAe,QAAQ,UAAU,GAAG;AAC3D,iBAAO,KAAK,QAAQ,KAAK;AAAA,QAC3B;AAAA,MACF,CAAC;AACD,aAAO;AAAA,IACT;AAAA,IACA,CAAC,QAAQ;AAAA,EACX;AAEA,SAAO,EAAE,YAAY,eAAe,YAAY;AAClD;AAEA,IAAO,kCAAQ;AAaf,SAAS,yBACP,OACA,QACuD;AACvD,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK,eAAe;AAClB,YAAM,EAAE,OAAO,IAAI,WAAW,IAAI;AAClC,YAAM,aAA0C;AAAA,QAC9C;AAAA,QACA;AAAA,QACA,YAAY,IAAI,IAAI,UAAU;AAAA,MAChC;AACA,YAAM,WAAW,IAAI,IAAI,KAAK;AAC9B,eAAS,IAAI,IAAI,UAAU;AAC3B,aAAO;AAAA,IACT;AAAA,IACA,KAAK,kBAAkB;AACrB,YAAM,WAAW,IAAI,IAAI,KAAK;AAC9B,eAAS,OAAO,OAAO,EAAE;AACzB,aAAO;AAAA,IACT;AAAA,IACA;AACE,aAAO;AAAA,EACX;AACF;AAEA,SAAS,qBAAwB,MAAc,MAAuB;AACpE,QAAM,CAAC,YAAY,SAAS,IAAI,KAAK,QAAQ,KAAK,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,IAAI;AAEnF,WAAS,QAAQ,YAAY;AAC3B,QAAI,UAAU,IAAI,IAAI,GAAG;AACvB,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT","sourcesContent":["import { nanoid } from \"nanoid\";\nimport { useCallback, useReducer } from \"react\";\n\nexport type FlatCategoryStoreId = string;\n\nexport interface UseFlatCategoryStoreReturn<T> {\n addElement: (value: T, categories: string[]) => FlatCategoryStoreId;\n removeElement: (id: FlatCategoryStoreId) => void;\n allElements: (categories: string[]) => T[];\n}\n\ninterface FlatCategoryStoreElement<T> {\n id: FlatCategoryStoreId;\n value: T;\n categories: Set<string>;\n}\n\nconst useFlatCategoryStore = <T>(): UseFlatCategoryStoreReturn<T> => {\n const [elements, dispatch] = useReducer<\n React.Reducer<Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>>, Action<T>>\n >(flatCategoryStoreReducer, new Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>>());\n\n const addElement = useCallback((value: T, categories: string[]): FlatCategoryStoreId => {\n const newId = nanoid();\n dispatch({\n type: \"ADD_ELEMENT\",\n value,\n id: newId,\n categories,\n });\n return newId;\n }, []);\n\n const removeElement = useCallback((id: FlatCategoryStoreId): void => {\n dispatch({ type: \"REMOVE_ELEMENT\", id });\n }, []);\n\n const allElements = useCallback(\n (categories: string[]): T[] => {\n const categoriesSet = new Set(categories);\n const result: T[] = [];\n elements.forEach((element) => {\n if (setsHaveIntersection(categoriesSet, element.categories)) {\n result.push(element.value);\n }\n });\n return result;\n },\n [elements],\n );\n\n return { addElement, removeElement, allElements };\n};\n\nexport default useFlatCategoryStore;\n\n// Action types\ntype Action<T> =\n | {\n type: \"ADD_ELEMENT\";\n value: T;\n id: FlatCategoryStoreId;\n categories: string[];\n }\n | { type: \"REMOVE_ELEMENT\"; id: FlatCategoryStoreId };\n\n// Reducer\nfunction flatCategoryStoreReducer<T>(\n state: Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>>,\n action: Action<T>,\n): Map<FlatCategoryStoreId, FlatCategoryStoreElement<T>> {\n switch (action.type) {\n case \"ADD_ELEMENT\": {\n const { value, id, categories } = action;\n const newElement: FlatCategoryStoreElement<T> = {\n id,\n value,\n categories: new Set(categories),\n };\n const newState = new Map(state);\n newState.set(id, newElement);\n return newState;\n }\n case \"REMOVE_ELEMENT\": {\n const newState = new Map(state);\n newState.delete(action.id);\n return newState;\n }\n default:\n return state;\n }\n}\n\nfunction setsHaveIntersection<T>(setA: Set<T>, setB: Set<T>): boolean {\n const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];\n\n for (let item of smallerSet) {\n if (largerSet.has(item)) {\n return true;\n }\n }\n\n return false;\n}\n"]}
|