@rebasepro/plugin-ai 0.0.1-canary.4829d6e
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/LICENSE +22 -0
- package/README.md +81 -0
- package/dist/api.d.ts +34 -0
- package/dist/components/DataEnhancementControllerProvider.d.ts +14 -0
- package/dist/components/FormEnhanceAction.d.ts +3 -0
- package/dist/editor/useEditorAIController.d.ts +4 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.es.js +741 -0
- package/dist/index.es.js.map +1 -0
- package/dist/index.umd.js +772 -0
- package/dist/index.umd.js.map +1 -0
- package/dist/types/data_enhancement_controller.d.ts +71 -0
- package/dist/useDataEnhancementPlugin.d.ts +29 -0
- package/dist/utils/diffStrings.d.ts +7 -0
- package/dist/utils/properties.d.ts +3 -0
- package/dist/utils/strings_counter.d.ts +2 -0
- package/dist/utils/suggestions.d.ts +1 -0
- package/dist/utils/values.d.ts +1 -0
- package/package.json +99 -0
- package/src/api.ts +198 -0
- package/src/components/DataEnhancementControllerProvider.tsx +342 -0
- package/src/components/FormEnhanceAction.tsx +277 -0
- package/src/editor/useEditorAIController.tsx +37 -0
- package/src/index.ts +9 -0
- package/src/tests/diffStrings.test.ts +128 -0
- package/src/tests/strings_counter.test.ts +117 -0
- package/src/tests/suggestions.test.ts +53 -0
- package/src/tests/useDataEnhancementPlugin.test.tsx +51 -0
- package/src/tests/values.test.ts +87 -0
- package/src/types/data_enhancement_controller.tsx +75 -0
- package/src/useDataEnhancementPlugin.tsx +66 -0
- package/src/utils/diffStrings.ts +70 -0
- package/src/utils/properties.ts +168 -0
- package/src/utils/strings_counter.ts +22 -0
- package/src/utils/suggestions.ts +6 -0
- package/src/utils/values.ts +12 -0
- package/src/vite-env.d.ts +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.umd.js","names":[],"sources":["../src/utils/values.ts","../src/api.ts","../src/utils/suggestions.ts","../src/utils/properties.ts","../src/editor/useEditorAIController.tsx","../src/components/DataEnhancementControllerProvider.tsx","../src/components/FormEnhanceAction.tsx","../src/useDataEnhancementPlugin.tsx"],"sourcesContent":["export function flatMapEntityValues<M extends object>(values: M, path = \"\"): object {\n if (!values) return {};\n return Object.entries(values).flatMap(([key, value]) => {\n const currentPath = path ? `${path}.${key}` : key;\n if (typeof value === \"object\") {\n return flatMapEntityValues(value, currentPath);\n } else {\n return { [currentPath]: value };\n }\n }).reduce((acc, curr) => ({ ...acc,\n...curr }), {})\n}\n","import {\n DataEnhancementRequest,\n EnhancedDataResult,\n InputEntity,\n InputProperty,\n SamplePromptsResult\n} from \"./types/data_enhancement_controller\";\nimport { EntityValues } from \"@rebasepro/types\";\nimport { flatMapEntityValues } from \"./utils/values\";\n\n// const DEFAULT_SERVER = \"http://localhost:5001/rebase-dev-2da42/europe-west3/api\"; // Local\n\nconst DEFAULT_SERVER = \"https://api.rebase.pro\";\n\nexport async function enhanceDataAPIStream<M extends Record<string, unknown>>(props: {\n apiKey: string,\n entityId?: string | number,\n entityName: string,\n entityDescription?: string,\n propertyKey?: string,\n propertyInstructions?: string;\n values: EntityValues<M>,\n path: string,\n properties: Record<string, InputProperty>,\n\n instructions?: string,\n firebaseToken: string,\n onUpdate: (suggestions: Record<string, string | number>) => void;\n onUpdateDelta: (propertyKey: string, partialValue: string) => void;\n onError: (error: Error) => void;\n onEnd: (result: EnhancedDataResult) => void;\n host?: string;\n}) {\n\n const flatValues = flatMapEntityValues(props.values);\n\n const properties = props.properties;\n\n const inputEntity: InputEntity = {\n entityId: props.entityId,\n values: flatValues\n }\n\n const request: DataEnhancementRequest = {\n inputEntity,\n properties,\n entityName: props.entityName,\n entityDescription: props.entityDescription,\n propertyKey: props.propertyKey,\n propertyInstructions: props.propertyInstructions,\n instructions: props.instructions\n };\n\n console.debug(\"enhanceDataAPIStream\", request);\n\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/enhance_stream/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`,\n \"x-de-api-key\": `Basic ${props.apiKey}`\n // \"x-de-version\": version\n },\n body: JSON.stringify(request)\n })\n .then(async (res) => {\n if (!res.ok) {\n console.error(\"enhanceDataAPIStream error\", res)\n throw await res.json();\n }\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"No reader\");\n }\n\n for await (const chunk of readChunks(reader)) {\n const str = new TextDecoder().decode(chunk);\n try {\n str.split(\"&$# \").forEach((s) => {\n if (s && s.length > 0) {\n const data = JSON.parse(s.trim());\n if (data.type === \"suggestion_delta\")\n props.onUpdateDelta(data.data.propertyKey, data.data.partialValue);\n else if (data.type === \"suggestion\")\n props.onUpdate(data.data);\n else if (data.type === \"result\")\n props.onEnd(data.data);\n }\n });\n } catch (e: unknown) {\n console.error(\"str\", str);\n console.error(\"Error parsing stream\", e);\n props.onError(e instanceof Error ? e : new Error(String(e)));\n }\n }\n\n });\n\n}\n\nfunction readChunks(reader: ReadableStreamDefaultReader) {\n return {\n async *[Symbol.asyncIterator]() {\n let readResult = await reader.read();\n while (!readResult.done) {\n yield readResult.value;\n readResult = await reader.read();\n }\n }\n };\n}\n\nexport async function fetchEntityPromptSuggestion<M extends object>(props: {\n input?: string,\n entityName: string,\n firebaseToken: string,\n apiKey: string,\n host?: string\n}): Promise<SamplePromptsResult> {\n\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/prompt_autocomplete/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`,\n \"x-de-api-key\": `Basic ${props.apiKey}`\n },\n body: JSON.stringify({\n entityName: props.entityName,\n input: props.input ?? null\n })\n })\n .then(async (res) => {\n const data = await res.json();\n if (!res.ok) {\n console.error(\"fetchEntityPromptSuggestion\", data);\n throw Error(data.message);\n }\n return {\n prompts: data.data.prompts.map((e: string) => ({\n prompt: e,\n type: \"sample\"\n }))\n };\n });\n\n}\n\nexport async function autocompleteStream(props: {\n firebaseToken: string,\n textBefore?: string,\n textAfter: string,\n host?: string;\n onUpdate: (delta: string) => void;\n}) {\n\n let result = \"\";\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/autocomplete/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`\n // \"x-de-version\": version\n },\n body: JSON.stringify({\n textBefore: props.textBefore,\n textAfter: props.textAfter\n })\n })\n .then(async (res) => {\n if (!res.ok) {\n console.error(\"enhanceDataAPIStream error\", res)\n throw await res.json();\n }\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"No reader\");\n }\n\n for await (const chunk of readChunks(reader)) {\n const str = new TextDecoder().decode(chunk);\n result += str;\n console.debug(\"Autocomplete update:\", str);\n props.onUpdate(str);\n }\n\n }).then(() => {\n console.debug(\"Autocomplete result:\", result);\n return result;\n });\n\n}\n","export function getAppendableSuggestion(suggestion: string | number | undefined, value: unknown): string | undefined {\n const suggestionIncludesValue = typeof suggestion === \"string\" && typeof value === \"string\" && suggestion.toLowerCase().trim().startsWith(value.toLowerCase().trim());\n return (typeof value === \"string\" && suggestionIncludesValue)\n ? suggestion.substring(suggestion.toLowerCase().trim().indexOf(value.toLowerCase().trim()) + value.trim().length)\n : undefined;\n}\n","import { getFieldId } from \"@rebasepro/admin\";\nimport { EnumValues, Properties, Property } from \"@rebasepro/types\";\nimport { isPropertyBuilder } from \"@rebasepro/common\";\nimport { InputProperty } from \"../types/data_enhancement_controller\";\nimport { getValueInPath } from \"@rebasepro/utils\";\n\nexport function getSimplifiedProperties<M extends Record<string, any>>(properties: Properties, values: M, path = \"\"): Record<string, InputProperty> {\n if (!properties) return {};\n return Object.entries(properties)\n .map(([key, property]) => {\n if (isPropertyBuilder(property)) return {};\n const fullKey = path ? `${path}.${key}` : key;\n const valueInPath = getValueInPath(values, fullKey);\n return getSimplifiedProperty(property, fullKey, valueInPath)\n })\n .reduce((a, b) => ({ ...a,\n...b }), {});\n}\n\nfunction getSimpleProperty(property: Property): InputProperty {\n const fieldId = getFieldId(property);\n if (!fieldId) {\n console.error(\"No fieldId found for property\", property);\n throw new Error(\"Field id not found\");\n }\n return {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: fieldId,\n enum: \"enum\" in property && property.enum\n ? getSimpleEnumValues(property.enum)\n : undefined,\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly)\n };\n}\n\nfunction getSimplifiedProperty(property: Property, path: string, value?: unknown): Record<string, InputProperty> {\n if (isPropertyBuilder(property)) return {};\n if (property.type === \"array\") {\n\n if (property.of && !Array.isArray(property.of) && !isPropertyBuilder(property.of)) {\n const arrayParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"repeat\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly),\n of: getSimpleProperty(property.of as Property)\n };\n\n const result = { [path]: arrayParentProperty };\n // if (Array.isArray(value)) {\n // result = {\n // ...result,\n // ...value\n // .map((v, i) => getSimplifiedProperty(property.of, `${path}.${i}`, v))\n // .reduce((a, b) => ({ ...a, ...b }), {})\n // };\n // }\n //\n // const existingValuesCount = Array.isArray(value) ? value.length : 0;\n //\n // const newValuesCount = property.of && !isPropertyBuilder<any, any>(property.of) && (property.of as Property).type === \"map\" ? 1 : 3;\n // result = {\n // ...result,\n // // ...Array.from(Array(newValuesCount))\n // // .map((v, i) => getSimplifiedProperty(property.of, `${path}.${i + existingValuesCount}`, v))\n // // .reduce((a, b) => ({ ...a, ...b }), {})\n // }\n\n return result;\n } else if (property.oneOf) {\n\n const arrayParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"block\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly),\n oneOf: {\n typeField: property.oneOf.typeField,\n valueField: property.oneOf.valueField,\n properties: Object.entries(property.oneOf.properties)\n .map(([key, prop]) => ({ [key]: getSimpleProperty(prop) }))\n .reduce((a, b) => ({ ...a,\n...b }), {})\n }\n };\n\n if (!Array.isArray(value)) {\n return { [path]: arrayParentProperty };\n }\n\n return value.map((v, i) => {\n if (v == null) return {};\n const typeKey = property.oneOf!.typeField ?? \"type\";\n const oneOfType = v[typeKey];\n const valueKey = property.oneOf!.valueField ?? \"value\";\n const oneOfValue = v[valueKey];\n const childProperty = property.oneOf!.properties[oneOfType];\n if (childProperty === undefined) {\n console.error(`No property found for type ${oneOfType}`, property.oneOf!.properties);\n return {};\n }\n const simplifiedProperty = getSimplifiedProperty(childProperty, `${path}.${i}.${valueKey}`, oneOfValue);\n return {\n [`${path}.${i}.${typeKey}`]: oneOfType,\n ...simplifiedProperty\n };\n }).reduce((a, b) => ({ ...a,\n...b }), { [path]: arrayParentProperty });\n }\n } else if (property.type === \"map\") {\n if (property.properties) {\n const mapProperties: Record<string, InputProperty> = Object.entries(property.properties)\n .map(([key, childProperty]) => {\n const childValue = value && typeof value === \"object\" ? (value as Record<string, unknown>)[key] : undefined;\n return getSimplifiedProperty(childProperty, key, childValue);\n })\n .map(o => attachPathToKeys(o, path))\n .reduce((a, b) => ({ ...a,\n...b }), {});\n\n if (Object.keys(mapProperties).length === 0) return {};\n const mapParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"group\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly)\n };\n return {\n [path]: mapParentProperty,\n ...mapProperties\n } as Record<string, InputProperty>;\n }\n } else {\n const fieldId = getFieldId(property);\n if (!fieldId) {\n console.warn(`No fieldId found for property ${path} with type ${property.type}`);\n return {};\n }\n return {\n [path]: getSimpleProperty(property)\n };\n }\n return {};\n}\n\n// attach a path to every key in an object\nfunction attachPathToKeys(obj: Record<string, InputProperty>, path = \"\"): Record<string, InputProperty> {\n return Object.entries(obj)\n .map(([key, value]) => {\n const fullKey = path ? `${path}.${key}` : key;\n return { [fullKey]: value };\n })\n .reduce((a, b) => ({ ...a,\n...b }), {});\n}\n\nfunction getSimpleEnumValues(enumValues: EnumValues): string[] {\n if (Array.isArray(enumValues))\n return enumValues.map(v => String(v.id));\n if (typeof enumValues === \"object\")\n return Object.keys(enumValues);\n throw Error(\"getSimpleEnumValues: Invalid enumValues\");\n}\n","import { autocompleteStream } from \"../api\";\nimport { EditorAIController } from \"@rebasepro/admin\";\n\nexport function useEditorAIController({ getAuthToken }: { getAuthToken?: () => Promise<string> }): EditorAIController {\n const autocomplete = async (textBefore: string, textAfter: string, onUpdate: (delta: string) => void) => {\n if (!getAuthToken) {\n throw new Error(\"Firebase token is required\");\n }\n const firebaseToken = await getAuthToken();\n return autocompleteStream({\n firebaseToken,\n textBefore,\n textAfter,\n onUpdate\n });\n }\n\n return {\n autocomplete\n };\n}\n\n// async function * generateLoremIpsum(): AsyncGenerator<string> {\n// const loremIpsum = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\\n# Heading\\n\\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\";\n//\n// const words = loremIpsum.split(\" \");\n//\n// for (const word of words) {\n// yield word;\n// await new Promise(resolve => setTimeout(resolve, 100));\n// }\n// }\n//\n// const generator = generateLoremIpsum();\n// for await (const word of generator) {\n//\n// }\n","import React, { PropsWithChildren, useCallback, useContext, useEffect, useMemo, useRef, useState } from \"react\";\n\nimport {\n DataEnhancementController,\n EnhancedDataResult,\n EnhanceParams,\n InputProperty\n} from \"../types/data_enhancement_controller\";\nimport {\n useAuthController,\n useCustomizationController,\n useSnackbarController\n} from \"@rebasepro/app\";\nimport { useUrlController } from \"@rebasepro/admin\";\nimport { DataDriver, Entity, CollectionConfig, PluginFormActionProps } from \"@rebasepro/types\";\nimport { enhanceDataAPIStream, fetchEntityPromptSuggestion } from \"../api\";\nimport { getAppendableSuggestion } from \"../utils/suggestions\";\nimport { getSimplifiedProperties } from \"../utils/properties\";\nimport { useEditorAIController } from \"../editor/useEditorAIController\";\nimport { getValueInPath } from \"@rebasepro/utils\";\n\nconst DataEnhancementControllerContext = React.createContext<DataEnhancementController>(null! as DataEnhancementController);\n\ntype DataEnhancementControllerProviderProps = {\n\n apiKey: string;\n\n getConfigForPath?: (props: {\n path: string,\n collection: CollectionConfig\n }) => boolean;\n\n host?: string;\n}\n\nexport const useDataEnhancementController = (): DataEnhancementController => useContext(DataEnhancementControllerContext);\n\nfunction getPropertyFromKey(properties: Record<string, InputProperty>, propertyKey: string) {\n if (propertyKey in properties) {\n return properties[propertyKey];\n } else {\n //split the property key\n const split = propertyKey.split(\".\");\n if (split.length === 1) {\n return undefined;\n }\n const parentKey = split.slice(0, split.length - 1).join(\".\");\n return getPropertyFromKey(properties, parentKey);\n\n }\n}\n\nexport function DataEnhancementControllerProvider({\n apiKey,\n getConfigForPath,\n children,\n host,\n path,\n collection,\n formContext\n}: PropsWithChildren<DataEnhancementControllerProviderProps & PluginFormActionProps>) {\n\n const [enabled, setEnabled] = useState(false);\n const [suggestions, setSuggestions] = useState<Record<string, string | number>>({});\n const [loadingSuggestions, setLoadingSuggestions] = useState<string[]>([]);\n\n const enhancingInProgress = useRef(false);\n\n const authController = useAuthController();\n const snackbarController = useSnackbarController();\n\n\n const properties = useMemo(() => getSimplifiedProperties(collection.properties, formContext?.values ?? {}), [formContext?.values]);\n // const preEnhanceValuesRef = React.useRef(formContext?.values ?? {});\n const valuesRef = React.useRef(formContext?.values ?? {});\n useEffect(() => {\n if (!enhancingInProgress.current)\n valuesRef.current = formContext?.values ?? {};\n }, [formContext?.values]);\n\n const allowReferenceDataSelection = false;\n\n const updateConfig = useCallback(async () => {\n if (!getConfigForPath) return;\n const config = getConfigForPath({\n path,\n collection\n });\n if (config) {\n setEnabled(true);\n }\n }, [collection, getConfigForPath, path]);\n\n useEffect(() => {\n if (!getConfigForPath) {\n setEnabled(true);\n } else {\n updateConfig();\n }\n\n }, [getConfigForPath, updateConfig]);\n\n\n const urlController = useUrlController();\n\n const clearSuggestion = useCallback((propertyKey: string) => {\n setSuggestions((prev) => {\n //remove propertyKey from prev\n const {\n [propertyKey]: _,\n ...rest\n } = prev;\n return rest;\n });\n }, []);\n\n const appendValueDelta = useCallback((propertyKey: string, delta: string) => {\n\n const property = getPropertyFromKey(properties, propertyKey);\n if (delta === null || property?.disabled) {\n return;\n }\n\n // clearSuggestion(propertyKey);\n const value = getValueInPath(valuesRef.current, propertyKey);\n\n const currentValue = value ? (value as string) + \"\" : \"\";\n const updatedValue = currentValue + delta;\n // if (currentValue.length === 0) updatedValue = updatedValue.trimStart();\n valuesRef.current = {\n ...valuesRef.current,\n [propertyKey]: updatedValue\n };\n formContext?.setFieldValue(propertyKey, updatedValue, false);\n setSuggestions(prev => ({\n ...prev,\n [propertyKey]: (prev[propertyKey] ?? \"\") + delta\n }));\n }, [properties, formContext]);\n\n const updateSuggestedValues = useCallback((currentValues: object, updatedValues: Record<string, string | number>, replaceValues: boolean) => {\n\n setLoadingSuggestions((prev) => {\n return prev.filter(p => !Object.keys(updatedValues).includes(p));\n });\n\n Object.entries(updatedValues).forEach(([propertyKey, suggestion]) => {\n\n const value = getValueInPath(currentValues, propertyKey);\n const property = getPropertyFromKey(properties, propertyKey);\n\n if (!property || suggestion === null || property?.disabled) {\n return;\n }\n\n if (typeof suggestion === \"number\") {\n formContext?.setFieldValue(propertyKey, suggestion);\n return;\n }\n\n if (replaceValues) {\n formContext?.setFieldValue(propertyKey, suggestion);\n return;\n }\n\n const appendableValue = getAppendableSuggestion(suggestion, value);\n\n const currentValue = value ? (value as string) + \"\" : \"\";\n if (appendableValue) {\n formContext?.setFieldValue(propertyKey, suggestion);\n } else {\n const multiline = property?.fieldConfigId === \"multiline\" || property?.fieldConfigId === \"markdown\";\n const trimmedValue = currentValue.trimEnd();\n if (multiline && (trimmedValue.endsWith(\".\") || trimmedValue.endsWith(\"?\") || trimmedValue.endsWith(\"!\") || trimmedValue.endsWith(\":\"))) {\n formContext?.setFieldValue(propertyKey, trimmedValue + \"\\n\\n\" + (suggestion as string).trimStart());\n } else {\n formContext?.setFieldValue(propertyKey, trimmedValue + (trimmedValue.length > 0 ? \" \" : \"\") + (suggestion as string));\n }\n }\n });\n\n setSuggestions(prev => ({\n ...prev,\n ...Object.keys(updatedValues)\n .reduce((acc, key) => {\n const value = getValueInPath(formContext?.values, key);\n const suggestion = updatedValues[key];\n return {\n ...acc,\n [key]: getAppendableSuggestion(suggestion, value) ?? suggestion\n };\n }, {})\n }));\n }, [properties, formContext]);\n\n const displayNeededSubscriptionSnackbar = useCallback((projectId: unknown) => {\n snackbarController.open({\n type: \"warning\",\n message: \"A valid subscription is needed in order to use this function.\",\n autoHideDuration: 4000\n });\n }, [snackbarController]);\n\n const editorAIController = useEditorAIController({ getAuthToken: authController.getAuthToken });\n\n const clearAllSuggestions = useCallback(() => {\n setSuggestions({});\n }, []);\n\n const enhance = useCallback(async (props: EnhanceParams<Record<string, unknown>>): Promise<EnhancedDataResult | null> => {\n\n if (!authController.user) {\n snackbarController.open({\n type: \"warning\",\n message: \"You need to be logged in to enhance data\"\n });\n return Promise.reject(new Error(\"Not logged in\"));\n }\n\n const resolvedPath = urlController.resolveDatabasePathsFrom(path);\n const firebaseToken = await authController.getAuthToken();\n\n if (props.propertyKey) {\n clearSuggestion(props.propertyKey)\n } else {\n clearAllSuggestions();\n }\n\n setLoadingSuggestions((prev) => [...prev, ...(props.propertyKey ? [props.propertyKey] : Object.keys(properties))]);\n enhancingInProgress.current = true;\n\n const currentValues = valuesRef.current ?? {};\n\n return new Promise((resolve, reject) => {\n function onError(e: unknown) {\n setLoadingSuggestions([]);\n const err = e instanceof Error ? e : typeof e === \"object\" && e !== null ? e : new Error(String(e));\n const errorObj = err as Record<string, unknown>;\n if (errorObj.code === \"payment-required\") {\n const data = errorObj.data as Record<string, unknown> | undefined;\n const projectId = data?.projectId;\n displayNeededSubscriptionSnackbar(projectId);\n } else {\n console.error(\"Enhance error\", e);\n }\n reject(e);\n enhancingInProgress.current = false;\n }\n\n try {\n enhanceDataAPIStream({\n ...props,\n host,\n apiKey,\n properties,\n path: resolvedPath,\n entityName: collection.singularName ?? collection.name,\n entityDescription: collection.description,\n\n firebaseToken,\n onUpdate: (suggestions) => {\n console.debug(\"de onUpdate\", suggestions);\n updateSuggestedValues(currentValues, suggestions, props.replaceValues ?? false);\n },\n onUpdateDelta: (propertyKey: string, partialValue: string) => {\n // console.debug(\"de delta\", propertyKey, partialValue);\n appendValueDelta(propertyKey, partialValue);\n },\n onError,\n onEnd: (result) => {\n console.debug(\"de onEnd\", result);\n if (result.errors) {\n result.errors.forEach((error) => {\n snackbarController.open({\n type: \"warning\",\n message: error\n })\n });\n }\n if (Object.keys(result.suggestions).length === 0) {\n snackbarController.open({\n type: \"info\",\n autoHideDuration: 1800,\n message: \"No fields were updated\"\n })\n }\n setLoadingSuggestions([]);\n resolve(result);\n enhancingInProgress.current = false;\n }\n }).catch(onError);\n } catch (e: unknown) {\n onError(e);\n }\n });\n }, [\n authController, urlController, path, clearSuggestion, clearAllSuggestions,\n properties, host, apiKey, collection, updateSuggestedValues, appendValueDelta, displayNeededSubscriptionSnackbar, snackbarController\n ]);\n\n const getSamplePrompts = useCallback(async (entityName: string, input?: string) => {\n const firebaseToken = await authController.getAuthToken()\n return fetchEntityPromptSuggestion({\n host,\n entityName,\n firebaseToken,\n apiKey,\n input\n });\n }, [apiKey, authController.getAuthToken, host]);\n\n const dataEnhancementController: DataEnhancementController = useMemo(() => ({\n enabled,\n suggestions,\n clearSuggestion,\n enhance,\n allowReferenceDataSelection,\n clearAllSuggestions,\n getSamplePrompts,\n loadingSuggestions,\n editorAIController\n }), [\n enabled,\n suggestions,\n clearSuggestion,\n enhance,\n allowReferenceDataSelection,\n clearAllSuggestions,\n getSamplePrompts,\n loadingSuggestions,\n editorAIController\n ]);\n\n return (\n <DataEnhancementControllerContext.Provider\n value={dataEnhancementController}>\n {children}\n </DataEnhancementControllerContext.Provider>\n );\n}\n\n\n","\nimport React, { useCallback, useDeferredValue, useEffect, useRef } from \"react\";\n\nimport {\n Button,\n CircularProgress,\n cls,\n focusedDisabled,\n IconButton,\n iconSize,\n Menu,\n MenuItem,\n SendIcon,\n Separator,\n TextareaAutosize,\n XIcon\n} from \"@rebasepro/ui\";\nimport {\n AIIcon,\n useLargeLayout\n} from \"@rebasepro/app\";\nimport { EntityStatus, PluginFormActionProps, Properties, Property } from \"@rebasepro/types\";\nimport { isPropertyBuilder, stripCollectionPath } from \"@rebasepro/common\";\nimport { useDataEnhancementController } from \"./DataEnhancementControllerProvider\";\nimport { SamplePrompt } from \"../types/data_enhancement_controller\";\n\nexport function FormEnhanceAction({\n entityId,\n path,\n status,\n collection,\n formContext,\n openEntityMode\n}: PluginFormActionProps) {\n\n const largeLayout = useLargeLayout();\n\n const storageKey = createLocalStorageKey(path, status);\n\n const [loading, setLoading] = React.useState(false);\n const dataEnhancementController = useDataEnhancementController();\n\n const [samplePrompts, setSamplePrompts] = React.useState<SamplePrompt[] | undefined>(undefined);\n const [instructions, setInstructions] = React.useState<string>(\"\");\n\n const getSamplePrompts = dataEnhancementController?.getSamplePrompts;\n\n const loadingPrompts = useRef(false);\n const updateSuggestedPrompts = useCallback(async function updateSuggestedPrompts(instructions?: string) {\n if (!getSamplePrompts) return;\n if (loadingPrompts.current) return;\n loadingPrompts.current = true;\n const prompts = status === \"new\"\n ? (await getSamplePrompts(collection.singularName ?? collection.name, instructions)).prompts\n : getPromptsForExistingEntities(collection.properties);\n\n const recentPromptsFromStorage = getRecentPromptsFromStorage(storageKey);\n const recentPrompts = recentPromptsFromStorage.map(prompt => prompt.prompt);\n setSamplePrompts([...recentPromptsFromStorage, ...prompts.filter(p => !recentPrompts.includes(p.prompt))].slice(0, 5));\n loadingPrompts.current = false;\n },\n [collection.name, collection.singularName, getSamplePrompts, status]);\n\n const deferredValues = useDeferredValue(formContext?.values);\n // const enoughData = countStringCharacters(deferredValues, collection.properties) > 20;\n\n useEffect(() => {\n if (!dataEnhancementController) return;\n if (!samplePrompts) {\n setSamplePrompts(getRecentPromptsFromStorage(storageKey));\n updateSuggestedPrompts().then();\n }\n }, [dataEnhancementController, samplePrompts, storageKey, updateSuggestedPrompts, instructions, status]);\n\n useEffect(() => {\n if (!dataEnhancementController) return;\n updateSuggestedPrompts().then();\n }, [dataEnhancementController, status]);\n\n const enhance = (prompt?: string) => {\n if (!dataEnhancementController || !formContext?.values) return;\n setLoading(true);\n if (prompt) {\n addRecentPrompt(storageKey, prompt);\n setSamplePrompts([{\n prompt,\n type: \"recent\"\n }, ...(samplePrompts ?? []).slice(0, 5)]);\n }\n return dataEnhancementController.enhance({\n entityId,\n values: formContext!.values,\n instructions: prompt,\n replaceValues: true\n }).finally(() => {\n setLoading(false);\n });\n };\n\n if (!dataEnhancementController?.enabled)\n return null;\n\n const suggestions = dataEnhancementController.suggestions;\n const hasSuggestions = Object.values(suggestions).filter(Boolean).length > 0;\n\n const disabledSuggestionActions = !hasSuggestions;\n const promptSuggestionsEnabled = (samplePrompts ?? []).length > 0 && instructions.length === 0;\n\n // const noIdSet = !formContext?.entityId;\n\n function submit() {\n enhance(instructions);\n }\n\n return (\n <Menu\n align={\"end\"}\n sideOffset={8}\n className={\"max-w-[100vw]\"}\n trigger={<Button variant={\"filled\"}\n color={\"neutral\"}\n fullWidth={largeLayout && openEntityMode === \"full_screen\"}\n size={\"small\"}\n disabled={loading}>\n {!loading && <AIIcon size={\"small\"}/>}\n {loading && <CircularProgress size={\"small\"}/>}\n Autofill\n </Button>}>\n\n <MenuItem className={\"py-4\"}\n onClick={() => {\n enhance();\n }}>\n <AIIcon size={\"small\"}/>\n Autofill based on the current content\n </MenuItem>\n\n <Separator orientation={\"horizontal\"} className={\"mt-2\"}/>\n\n {samplePrompts?.map((samplePrompt, index) => {\n return <MenuItem\n key={index + \"_\" + samplePrompt.prompt}\n onClick={() => {\n setInstructions(samplePrompt.prompt);\n enhance(samplePrompt.prompt);\n }}\n >\n <div className={\"pl-9 grow text-text-secondary dark:text-text-secondary-dark\"}>\n {samplePrompt.prompt}\n </div>\n\n {samplePrompt.type === \"recent\" && <IconButton\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n removeRecentPrompt(storageKey, samplePrompt.prompt);\n setSamplePrompts((samplePrompts ?? []).filter(p => p.prompt !== samplePrompt.prompt));\n }}\n size={\"smallest\"}\n >\n <XIcon size={iconSize.smallest}/>\n </IconButton>\n }\n </MenuItem>;\n })}\n\n <Separator orientation={\"horizontal\"}/>\n\n <div\n className={cls(\n \"my-2 w-[500px] max-w-full flex items-start text-surface-700 dark:text-surface-200\"\n )}>\n\n <TextareaAutosize\n className={cls(\"p-4 rounded-lg resize-none bg-surface-100 dark:bg-surface-950 mx-2 w-full grow outline-hidden max-h-[300px] overflow-auto\", focusedDisabled)}\n value={instructions}\n autoFocus={status === \"new\"}\n disabled={loading}\n onFocus={(event) => {\n event.stopPropagation();\n }}\n placeholder={\"...or provide instructions\"}\n onKeyDown={(e) => {\n e.stopPropagation();\n if (e.key === \"Enter\" && !e.shiftKey) {\n e.preventDefault();\n submit();\n }\n\n }}\n onChange={(e) => {\n setInstructions(e.target.value);\n }}\n />\n\n <IconButton\n size={\"small\"}\n onClick={() => {\n setInstructions(\"\");\n }}\n color={!instructions ? \"primary\" : undefined}\n disabled={loading || !instructions}>\n <XIcon size={iconSize.small}/>\n </IconButton>\n\n <IconButton\n onClick={() => enhance(instructions)}\n size={\"small\"}\n color={!instructions ? \"primary\" : undefined}\n disabled={loading || !instructions}>\n {loading &&\n <CircularProgress size={\"smallest\"}/>}\n {!loading &&\n <SendIcon color={\"primary\"}/>}\n </IconButton>\n\n </div>\n\n </Menu>\n );\n}\n\nfunction getPromptsForExistingEntities(properties: Properties): SamplePrompt[] {\n\n const multilineProperties = Object.values(properties).filter((p: Property) => {\n if (isPropertyBuilder(p)) {\n return false;\n }\n return p.type === \"string\" && (p.ui?.markdown || p.ui?.multiline);\n });\n\n const multilinePrompt: Property | undefined = multilineProperties.length > 0\n ? multilineProperties[Math.floor(Math.random() * multilineProperties.length)] as Property\n : undefined;\n\n const prompts = [\n \"Fill the missing fields\",\n \"Translate the missing content\"\n ];\n if (multilinePrompt) {\n prompts.push(`Add 2 paragraphs to '${multilinePrompt.name}'`);\n }\n return prompts.map(p => ({\n prompt: p,\n type: \"sample\"\n }));\n}\n\nconst createLocalStorageKey = (path: string, status: EntityStatus) => {\n const statusString = status === \"new\" ? \"new\" : \"existing\";\n return `data_enhancement::${statusString}::${stripCollectionPath(path)}`;\n};\n\nconst getRecentPromptsFromStorage = (storageKey: string): SamplePrompt[] => {\n const item = localStorage.getItem(storageKey);\n return item ? JSON.parse(item).map((e: string) => ({\n prompt: e,\n type: \"recent\"\n })) : [];\n};\n\nconst addRecentPrompt = (storageKey: string, prompt: string) => {\n if (!prompt || prompt.trim().length === 0) {\n return;\n }\n const recentPrompts = getRecentPromptsFromStorage(storageKey);\n localStorage.setItem(storageKey, JSON.stringify([prompt, ...recentPrompts\n .map(e => e.prompt)\n .filter(e => e !== prompt)\n .slice(0, 5)]));\n};\n\nconst removeRecentPrompt = (storageKey: string, prompt: string) => {\n localStorage.setItem(storageKey, JSON.stringify(getRecentPromptsFromStorage(storageKey)\n .map(e => e.prompt)\n .filter(e => e !== prompt)));\n};\n","import React from \"react\";\n\nimport { CollectionConfig, RebasePlugin, User } from \"@rebasepro/types\";\nimport { DataEnhancementControllerProvider } from \"./components/DataEnhancementControllerProvider\";\nimport { FormEnhanceAction } from \"./components/FormEnhanceAction\";\n\nconst DEFAULT_API_KEY = \"fcms-U9jdDii0xXWSDC34asfrf54lbkFJBfKfRWcEDEwdc4V5wDWEDF\";\n\nexport interface DataEnhancementPluginProps {\n\n apiKey?: string;\n\n /**\n * Use this function to determine if the data enhancement plugin should be enabled for a given path.\n * If this function is not provided, the plugin will be enabled for all paths.\n * If the function returns false, the plugin will be disabled for the given path.\n * You can also return a configuration object to override the default configuration.\n *\n * @param path\n * @param collection\n */\n getConfigForPath?: (props: {\n path: string,\n collection: CollectionConfig,\n user: User | null\n }) => boolean;\n\n /**\n * Host to use for the data enhancement API.\n * This prop is only use in development mode.\n */\n host?: string;\n}\n\n/**\n * Use this hook to initialise the data enhancement plugin.\n * This is likely the only hook you will need to use.\n * @param props\n */\nexport function useDataEnhancementPlugin(props?: DataEnhancementPluginProps): RebasePlugin {\n\n const apiKey = props?.apiKey ?? DEFAULT_API_KEY;\n const getConfigForPath = props?.getConfigForPath;\n\n return React.useMemo(() => ({\n key: \"data_enhancement\",\n slots: [\n {\n slot: \"form.actions\",\n Component: FormEnhanceAction,\n order: 40\n }\n ],\n providers: [\n {\n scope: \"form\" as const,\n Component: DataEnhancementControllerProvider as React.ComponentType<any>,\n props: {\n apiKey,\n getConfigForPath,\n host: props?.host\n }\n }\n ]\n }), [apiKey, getConfigForPath, props?.host]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAAA,SAAgB,oBAAsC,QAAW,OAAO,IAAY;EAChF,IAAI,CAAC,QAAQ,OAAO,CAAC;EACrB,OAAO,OAAO,QAAQ,MAAM,EAAE,SAAS,CAAC,KAAK,WAAW;GACpD,MAAM,cAAc,OAAO,GAAG,KAAK,GAAG,QAAQ;GAC9C,IAAI,OAAO,UAAU,UACjB,OAAO,oBAAoB,OAAO,WAAW;QAE7C,OAAO,GAAG,cAAc,MAAM;EAEtC,CAAC,EAAE,QAAQ,KAAK,UAAU;GAAE,GAAG;GACnC,GAAG;EAAK,IAAI,CAAC,CAAC;CACd;;;CCCA,IAAM,iBAAiB;CAEvB,eAAsB,qBAAwD,OAkB3E;EAEC,MAAM,aAAa,oBAAoB,MAAM,MAAM;EAEnD,MAAM,aAAa,MAAM;EAOzB,MAAM,UAAkC;GACpC,aAAA;IALA,UAAU,MAAM;IAChB,QAAQ;GAIR;GACA;GACA,YAAY,MAAM;GAClB,mBAAmB,MAAM;GACzB,aAAa,MAAM;GACnB,sBAAsB,MAAM;GAC5B,cAAc,MAAM;EACxB;EAEA,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,+BAA+B,eAAuC;EACxE,MAAM,OAAO,aAAa,QAAQ,UAAU;EAC5C,OAAO,OAAO,KAAK,MAAM,IAAI,EAAE,KAAK,OAAe;GAC/C,QAAQ;GACR,MAAM;EACV,EAAE,IAAI,CAAC;CACX;CAEA,IAAM,mBAAmB,YAAoB,WAAmB;EAC5D,IAAI,CAAC,UAAU,OAAO,KAAK,EAAE,WAAW,GACpC;EAEJ,MAAM,gBAAgB,4BAA4B,UAAU;EAC5D,aAAa,QAAQ,YAAY,KAAK,UAAU,CAAC,QAAQ,GAAG,cACvD,KAAI,MAAK,EAAE,MAAM,EACjB,QAAO,MAAK,MAAM,MAAM,EACxB,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;CACtB;CAEA,IAAM,sBAAsB,YAAoB,WAAmB;EAC/D,aAAa,QAAQ,YAAY,KAAK,UAAU,4BAA4B,UAAU,EACjF,KAAI,MAAK,EAAE,MAAM,EACjB,QAAO,MAAK,MAAM,MAAM,CAAC,CAAC;CACnC;;;CC9QA,IAAM,kBAAkB;;;;;;CAiCxB,SAAgB,yBAAyB,OAAkD;EAEvF,MAAM,SAAS,OAAO,UAAU;EAChC,MAAM,mBAAmB,OAAO;EAEhC,OAAO,MAAA,QAAM,eAAe;GACxB,KAAK;GACL,OAAO,CACH;IACI,MAAM;IACN,WAAW;IACX,OAAO;GACX,CACJ;GACA,WAAW,CACP;IACI,OAAO;IACP,WAAW;IACX,OAAO;KACH;KACA;KACA,MAAM,OAAO;IACjB;GACJ,CACJ;EACJ,IAAI;GAAC;GAAQ;GAAkB,OAAO;EAAI,CAAC;CAC/C"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { EntityValues } from "@rebasepro/types";
|
|
2
|
+
import { EditorAIController } from "@rebasepro/admin";
|
|
3
|
+
export type EnhanceParams<M extends Record<string, unknown>> = {
|
|
4
|
+
entityId?: string | number;
|
|
5
|
+
propertyKey?: string;
|
|
6
|
+
propertyInstructions?: string;
|
|
7
|
+
values: EntityValues<M>;
|
|
8
|
+
instructions?: string;
|
|
9
|
+
replaceValues: boolean;
|
|
10
|
+
};
|
|
11
|
+
export type DataEnhancementController = {
|
|
12
|
+
/**
|
|
13
|
+
* Whether the data enhancement is enabled for the current path
|
|
14
|
+
*/
|
|
15
|
+
enabled: boolean;
|
|
16
|
+
suggestions: Record<string, string | number>;
|
|
17
|
+
enhance: <M extends Record<string, unknown>>(props: EnhanceParams<M>) => Promise<EnhancedDataResult | null>;
|
|
18
|
+
clearSuggestion: (key: string, suggestion: string | number) => void;
|
|
19
|
+
allowReferenceDataSelection: boolean;
|
|
20
|
+
clearAllSuggestions: () => void;
|
|
21
|
+
getSamplePrompts: (entityName: string, input?: string) => Promise<SamplePromptsResult>;
|
|
22
|
+
loadingSuggestions: string[];
|
|
23
|
+
editorAIController?: EditorAIController;
|
|
24
|
+
};
|
|
25
|
+
export type EnhancedDataResult = {
|
|
26
|
+
entityId?: string | number;
|
|
27
|
+
suggestions: {
|
|
28
|
+
[key: string]: string[];
|
|
29
|
+
};
|
|
30
|
+
errors: string[];
|
|
31
|
+
usage: {
|
|
32
|
+
promptTokens?: number;
|
|
33
|
+
completionTokens?: number;
|
|
34
|
+
totalTokens?: number;
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
export type SamplePrompt = {
|
|
38
|
+
prompt: string;
|
|
39
|
+
type: "recent" | "sample";
|
|
40
|
+
};
|
|
41
|
+
export type SamplePromptsResult = {
|
|
42
|
+
prompts: SamplePrompt[];
|
|
43
|
+
host?: string;
|
|
44
|
+
};
|
|
45
|
+
export type DataEnhancementRequest = {
|
|
46
|
+
entityName: string;
|
|
47
|
+
entityDescription?: string;
|
|
48
|
+
inputEntity: InputEntity;
|
|
49
|
+
properties: Record<string, InputProperty>;
|
|
50
|
+
propertyKey?: string;
|
|
51
|
+
propertyInstructions?: string;
|
|
52
|
+
instructions?: string;
|
|
53
|
+
};
|
|
54
|
+
export type InputEntity = {
|
|
55
|
+
entityId?: string | number;
|
|
56
|
+
values: Record<string, any>;
|
|
57
|
+
};
|
|
58
|
+
export type InputProperty = {
|
|
59
|
+
name?: string;
|
|
60
|
+
description?: string;
|
|
61
|
+
type: string;
|
|
62
|
+
fieldConfigId: string;
|
|
63
|
+
enum?: string[];
|
|
64
|
+
disabled?: boolean;
|
|
65
|
+
of?: InputProperty;
|
|
66
|
+
oneOf?: {
|
|
67
|
+
properties: Record<string, InputProperty>;
|
|
68
|
+
typeField?: string;
|
|
69
|
+
valueField?: string;
|
|
70
|
+
};
|
|
71
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { CollectionConfig, RebasePlugin, User } from "@rebasepro/types";
|
|
2
|
+
export interface DataEnhancementPluginProps {
|
|
3
|
+
apiKey?: string;
|
|
4
|
+
/**
|
|
5
|
+
* Use this function to determine if the data enhancement plugin should be enabled for a given path.
|
|
6
|
+
* If this function is not provided, the plugin will be enabled for all paths.
|
|
7
|
+
* If the function returns false, the plugin will be disabled for the given path.
|
|
8
|
+
* You can also return a configuration object to override the default configuration.
|
|
9
|
+
*
|
|
10
|
+
* @param path
|
|
11
|
+
* @param collection
|
|
12
|
+
*/
|
|
13
|
+
getConfigForPath?: (props: {
|
|
14
|
+
path: string;
|
|
15
|
+
collection: CollectionConfig;
|
|
16
|
+
user: User | null;
|
|
17
|
+
}) => boolean;
|
|
18
|
+
/**
|
|
19
|
+
* Host to use for the data enhancement API.
|
|
20
|
+
* This prop is only use in development mode.
|
|
21
|
+
*/
|
|
22
|
+
host?: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Use this hook to initialise the data enhancement plugin.
|
|
26
|
+
* This is likely the only hook you will need to use.
|
|
27
|
+
* @param props
|
|
28
|
+
*/
|
|
29
|
+
export declare function useDataEnhancementPlugin(props?: DataEnhancementPluginProps): RebasePlugin;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { Properties } from "@rebasepro/types";
|
|
2
|
+
import { InputProperty } from "../types/data_enhancement_controller";
|
|
3
|
+
export declare function getSimplifiedProperties<M extends Record<string, any>>(properties: Properties, values: M, path?: string): Record<string, InputProperty>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function getAppendableSuggestion(suggestion: string | number | undefined, value: unknown): string | undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function flatMapEntityValues<M extends object>(values: M, path?: string): object;
|
package/package.json
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@rebasepro/plugin-ai",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.0.1-canary.4829d6e",
|
|
5
|
+
"main": "./dist/index.umd.js",
|
|
6
|
+
"module": "./dist/index.es.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"source": "src/index.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"development": "./dist/index.es.js",
|
|
13
|
+
"import": "./dist/index.es.js",
|
|
14
|
+
"require": "./dist/index.umd.js"
|
|
15
|
+
},
|
|
16
|
+
"./package.json": "./package.json"
|
|
17
|
+
},
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@rebasepro/admin": "0.0.1-canary.4829d6e",
|
|
20
|
+
"@rebasepro/app": "0.0.1-canary.4829d6e",
|
|
21
|
+
"@rebasepro/types": "0.0.1-canary.4829d6e",
|
|
22
|
+
"@rebasepro/common": "0.0.1-canary.4829d6e",
|
|
23
|
+
"@rebasepro/utils": "0.0.1-canary.4829d6e",
|
|
24
|
+
"@rebasepro/ui": "0.0.1-canary.4829d6e"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"react": ">=19.0.0",
|
|
28
|
+
"react-dom": ">=19.0.0",
|
|
29
|
+
"react-router": ">=6.28.0",
|
|
30
|
+
"react-router-dom": ">=6.28.0"
|
|
31
|
+
},
|
|
32
|
+
"browserslist": {
|
|
33
|
+
"production": [
|
|
34
|
+
">0.2%",
|
|
35
|
+
"not dead",
|
|
36
|
+
"not op_mini all"
|
|
37
|
+
],
|
|
38
|
+
"development": [
|
|
39
|
+
"last 1 chrome version",
|
|
40
|
+
"last 1 firefox version",
|
|
41
|
+
"last 1 safari version"
|
|
42
|
+
]
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@testing-library/jest-dom": "^6.9.1",
|
|
46
|
+
"@types/jest": "^30.0.0",
|
|
47
|
+
"@types/node": "^25.9.3",
|
|
48
|
+
"@types/react": "^19.2.17",
|
|
49
|
+
"@types/react-dom": "^19.2.3",
|
|
50
|
+
"@vitejs/plugin-react": "^6.0.2",
|
|
51
|
+
"babel-jest": "^30.4.1",
|
|
52
|
+
"babel-plugin-react-compiler": "19.0.0-beta-ebf51a3-20250411",
|
|
53
|
+
"jest": "^30.4.2",
|
|
54
|
+
"ts-jest": "^29.4.11",
|
|
55
|
+
"typescript": "^6.0.3",
|
|
56
|
+
"vite": "^8.0.16"
|
|
57
|
+
},
|
|
58
|
+
"jest": {
|
|
59
|
+
"transform": {
|
|
60
|
+
"^.+\\.tsx?$": "ts-jest"
|
|
61
|
+
},
|
|
62
|
+
"testEnvironment": "jsdom",
|
|
63
|
+
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
|
|
64
|
+
"moduleFileExtensions": [
|
|
65
|
+
"ts",
|
|
66
|
+
"tsx",
|
|
67
|
+
"js",
|
|
68
|
+
"jsx",
|
|
69
|
+
"json",
|
|
70
|
+
"node"
|
|
71
|
+
],
|
|
72
|
+
"moduleNameMapper": {
|
|
73
|
+
"^@rebasepro/app$": "<rootDir>/../app/src/index.ts",
|
|
74
|
+
"^@rebasepro/common$": "<rootDir>/../common/src/index.ts",
|
|
75
|
+
"^@rebasepro/types$": "<rootDir>/../types/src/index.ts",
|
|
76
|
+
"^@rebasepro/ui$": "<rootDir>/../ui/src/index.ts",
|
|
77
|
+
"^@rebasepro/admin$": "<rootDir>/../admin/src/index.ts",
|
|
78
|
+
"^@rebasepro/utils$": "<rootDir>/../utils/src/index.ts"
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
"files": [
|
|
82
|
+
"dist",
|
|
83
|
+
"src"
|
|
84
|
+
],
|
|
85
|
+
"publishConfig": {
|
|
86
|
+
"access": "public"
|
|
87
|
+
},
|
|
88
|
+
"gitHead": "d935eefa5aa8d1009a2398cfac2c1e4ee9aeb6b6",
|
|
89
|
+
"repository": {
|
|
90
|
+
"type": "git",
|
|
91
|
+
"url": "https://github.com/rebasepro/rebase.git",
|
|
92
|
+
"directory": "packages/plugin-ai"
|
|
93
|
+
},
|
|
94
|
+
"scripts": {
|
|
95
|
+
"dev": "vite",
|
|
96
|
+
"build": "vite build && tsc --emitDeclarationOnly -p tsconfig.prod.json",
|
|
97
|
+
"test": "jest --passWithNoTests"
|
|
98
|
+
}
|
|
99
|
+
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DataEnhancementRequest,
|
|
3
|
+
EnhancedDataResult,
|
|
4
|
+
InputEntity,
|
|
5
|
+
InputProperty,
|
|
6
|
+
SamplePromptsResult
|
|
7
|
+
} from "./types/data_enhancement_controller";
|
|
8
|
+
import { EntityValues } from "@rebasepro/types";
|
|
9
|
+
import { flatMapEntityValues } from "./utils/values";
|
|
10
|
+
|
|
11
|
+
// const DEFAULT_SERVER = "http://localhost:5001/rebase-dev-2da42/europe-west3/api"; // Local
|
|
12
|
+
|
|
13
|
+
const DEFAULT_SERVER = "https://api.rebase.pro";
|
|
14
|
+
|
|
15
|
+
export async function enhanceDataAPIStream<M extends Record<string, unknown>>(props: {
|
|
16
|
+
apiKey: string,
|
|
17
|
+
entityId?: string | number,
|
|
18
|
+
entityName: string,
|
|
19
|
+
entityDescription?: string,
|
|
20
|
+
propertyKey?: string,
|
|
21
|
+
propertyInstructions?: string;
|
|
22
|
+
values: EntityValues<M>,
|
|
23
|
+
path: string,
|
|
24
|
+
properties: Record<string, InputProperty>,
|
|
25
|
+
|
|
26
|
+
instructions?: string,
|
|
27
|
+
firebaseToken: string,
|
|
28
|
+
onUpdate: (suggestions: Record<string, string | number>) => void;
|
|
29
|
+
onUpdateDelta: (propertyKey: string, partialValue: string) => void;
|
|
30
|
+
onError: (error: Error) => void;
|
|
31
|
+
onEnd: (result: EnhancedDataResult) => void;
|
|
32
|
+
host?: string;
|
|
33
|
+
}) {
|
|
34
|
+
|
|
35
|
+
const flatValues = flatMapEntityValues(props.values);
|
|
36
|
+
|
|
37
|
+
const properties = props.properties;
|
|
38
|
+
|
|
39
|
+
const inputEntity: InputEntity = {
|
|
40
|
+
entityId: props.entityId,
|
|
41
|
+
values: flatValues
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const request: DataEnhancementRequest = {
|
|
45
|
+
inputEntity,
|
|
46
|
+
properties,
|
|
47
|
+
entityName: props.entityName,
|
|
48
|
+
entityDescription: props.entityDescription,
|
|
49
|
+
propertyKey: props.propertyKey,
|
|
50
|
+
propertyInstructions: props.propertyInstructions,
|
|
51
|
+
instructions: props.instructions
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
console.debug("enhanceDataAPIStream", request);
|
|
55
|
+
|
|
56
|
+
return fetch((props.host ?? DEFAULT_SERVER) + "/data/enhance_stream/",
|
|
57
|
+
{
|
|
58
|
+
// mode: "no-cors",
|
|
59
|
+
method: "POST",
|
|
60
|
+
headers: {
|
|
61
|
+
"Content-Type": "application/json",
|
|
62
|
+
Authorization: `Basic ${props.firebaseToken}`,
|
|
63
|
+
"x-de-api-key": `Basic ${props.apiKey}`
|
|
64
|
+
// "x-de-version": version
|
|
65
|
+
},
|
|
66
|
+
body: JSON.stringify(request)
|
|
67
|
+
})
|
|
68
|
+
.then(async (res) => {
|
|
69
|
+
if (!res.ok) {
|
|
70
|
+
console.error("enhanceDataAPIStream error", res)
|
|
71
|
+
throw await res.json();
|
|
72
|
+
}
|
|
73
|
+
const reader = res.body?.getReader();
|
|
74
|
+
if (!reader) {
|
|
75
|
+
throw new Error("No reader");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
for await (const chunk of readChunks(reader)) {
|
|
79
|
+
const str = new TextDecoder().decode(chunk);
|
|
80
|
+
try {
|
|
81
|
+
str.split("&$# ").forEach((s) => {
|
|
82
|
+
if (s && s.length > 0) {
|
|
83
|
+
const data = JSON.parse(s.trim());
|
|
84
|
+
if (data.type === "suggestion_delta")
|
|
85
|
+
props.onUpdateDelta(data.data.propertyKey, data.data.partialValue);
|
|
86
|
+
else if (data.type === "suggestion")
|
|
87
|
+
props.onUpdate(data.data);
|
|
88
|
+
else if (data.type === "result")
|
|
89
|
+
props.onEnd(data.data);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
} catch (e: unknown) {
|
|
93
|
+
console.error("str", str);
|
|
94
|
+
console.error("Error parsing stream", e);
|
|
95
|
+
props.onError(e instanceof Error ? e : new Error(String(e)));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function readChunks(reader: ReadableStreamDefaultReader) {
|
|
104
|
+
return {
|
|
105
|
+
async *[Symbol.asyncIterator]() {
|
|
106
|
+
let readResult = await reader.read();
|
|
107
|
+
while (!readResult.done) {
|
|
108
|
+
yield readResult.value;
|
|
109
|
+
readResult = await reader.read();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function fetchEntityPromptSuggestion<M extends object>(props: {
|
|
116
|
+
input?: string,
|
|
117
|
+
entityName: string,
|
|
118
|
+
firebaseToken: string,
|
|
119
|
+
apiKey: string,
|
|
120
|
+
host?: string
|
|
121
|
+
}): Promise<SamplePromptsResult> {
|
|
122
|
+
|
|
123
|
+
return fetch((props.host ?? DEFAULT_SERVER) + "/data/prompt_autocomplete/",
|
|
124
|
+
{
|
|
125
|
+
// mode: "no-cors",
|
|
126
|
+
method: "POST",
|
|
127
|
+
headers: {
|
|
128
|
+
"Content-Type": "application/json",
|
|
129
|
+
Authorization: `Basic ${props.firebaseToken}`,
|
|
130
|
+
"x-de-api-key": `Basic ${props.apiKey}`
|
|
131
|
+
},
|
|
132
|
+
body: JSON.stringify({
|
|
133
|
+
entityName: props.entityName,
|
|
134
|
+
input: props.input ?? null
|
|
135
|
+
})
|
|
136
|
+
})
|
|
137
|
+
.then(async (res) => {
|
|
138
|
+
const data = await res.json();
|
|
139
|
+
if (!res.ok) {
|
|
140
|
+
console.error("fetchEntityPromptSuggestion", data);
|
|
141
|
+
throw Error(data.message);
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
prompts: data.data.prompts.map((e: string) => ({
|
|
145
|
+
prompt: e,
|
|
146
|
+
type: "sample"
|
|
147
|
+
}))
|
|
148
|
+
};
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function autocompleteStream(props: {
|
|
154
|
+
firebaseToken: string,
|
|
155
|
+
textBefore?: string,
|
|
156
|
+
textAfter: string,
|
|
157
|
+
host?: string;
|
|
158
|
+
onUpdate: (delta: string) => void;
|
|
159
|
+
}) {
|
|
160
|
+
|
|
161
|
+
let result = "";
|
|
162
|
+
return fetch((props.host ?? DEFAULT_SERVER) + "/data/autocomplete/",
|
|
163
|
+
{
|
|
164
|
+
// mode: "no-cors",
|
|
165
|
+
method: "POST",
|
|
166
|
+
headers: {
|
|
167
|
+
"Content-Type": "application/json",
|
|
168
|
+
Authorization: `Basic ${props.firebaseToken}`
|
|
169
|
+
// "x-de-version": version
|
|
170
|
+
},
|
|
171
|
+
body: JSON.stringify({
|
|
172
|
+
textBefore: props.textBefore,
|
|
173
|
+
textAfter: props.textAfter
|
|
174
|
+
})
|
|
175
|
+
})
|
|
176
|
+
.then(async (res) => {
|
|
177
|
+
if (!res.ok) {
|
|
178
|
+
console.error("enhanceDataAPIStream error", res)
|
|
179
|
+
throw await res.json();
|
|
180
|
+
}
|
|
181
|
+
const reader = res.body?.getReader();
|
|
182
|
+
if (!reader) {
|
|
183
|
+
throw new Error("No reader");
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
for await (const chunk of readChunks(reader)) {
|
|
187
|
+
const str = new TextDecoder().decode(chunk);
|
|
188
|
+
result += str;
|
|
189
|
+
console.debug("Autocomplete update:", str);
|
|
190
|
+
props.onUpdate(str);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
}).then(() => {
|
|
194
|
+
console.debug("Autocomplete result:", result);
|
|
195
|
+
return result;
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
}
|