@rebasepro/plugin-ai 0.12.1-canary.g389e9b2 → 0.12.1-canary.g4e7bcbf
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/dist/index.es.js +1 -4
- package/dist/index.es.js.map +1 -1
- package/dist/useDataEnhancementPlugin.d.ts +7 -0
- package/package.json +8 -8
- package/src/tests/diffStrings.test.ts +48 -49
- package/src/tests/suggestions.test.ts +5 -2
- package/src/tests/useDataEnhancementPlugin.test.tsx +19 -9
- package/src/useDataEnhancementPlugin.tsx +7 -1
package/dist/index.es.js
CHANGED
|
@@ -700,16 +700,13 @@ var addRecentPrompt = (storageKey, prompt) => {
|
|
|
700
700
|
var removeRecentPrompt = (storageKey, prompt) => {
|
|
701
701
|
localStorage.setItem(storageKey, JSON.stringify(getRecentPromptsFromStorage(storageKey).map((e) => e.prompt).filter((e) => e !== prompt)));
|
|
702
702
|
};
|
|
703
|
-
//#endregion
|
|
704
|
-
//#region src/useDataEnhancementPlugin.tsx
|
|
705
|
-
var DEFAULT_API_KEY = "fcms-U9jdDii0xXWSDC34asfrf54lbkFJBfKfRWcEDEwdc4V5wDWEDF";
|
|
706
703
|
/**
|
|
707
704
|
* Use this hook to initialise the data enhancement plugin.
|
|
708
705
|
* This is likely the only hook you will need to use.
|
|
709
706
|
* @param props
|
|
710
707
|
*/
|
|
711
708
|
function useDataEnhancementPlugin(props) {
|
|
712
|
-
const apiKey = props?.apiKey ??
|
|
709
|
+
const apiKey = props?.apiKey ?? "fcms-U9jdDii0xXWSDC34asfrf54lbkFJBfKfRWcEDEwdc4V5wDWEDF";
|
|
713
710
|
const getConfigForPath = props?.getConfigForPath;
|
|
714
711
|
return React.useMemo(() => ({
|
|
715
712
|
key: "data_enhancement",
|
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.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.admin?.disabled || property.admin?.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.admin?.disabled || property.admin?.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.admin?.disabled || property.admin?.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.admin?.disabled || property.admin?.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 } from \"@rebasepro/types\";\nimport { PluginFormActionProps } from \"@rebasepro/admin-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} from \"@rebasepro/app\";\nimport { EntityStatus, Properties, Property } from \"@rebasepro/types\";\nimport { PluginFormActionProps } from \"@rebasepro/admin-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\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 // Never full width: this used to stretch to fill the form's\n // `w-80 2xl:w-96` side rail in full screen. That rail is gone, and\n // in the footer a stretched button reads as the primary action.\n trigger={<Button variant={\"filled\"}\n color={\"neutral\"}\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.admin?.markdown || p.admin?.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, User } from \"@rebasepro/types\";\nimport { RebasePlugin } from \"@rebasepro/admin-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":";;;;;;;;AAAA,SAAgB,oBAAsC,QAAW,OAAO,IAAY;CAChF,IAAI,CAAC,QAAQ,OAAO,CAAC;CACrB,OAAO,OAAO,QAAQ,MAAM,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;EACpD,MAAM,cAAc,OAAO,GAAG,KAAK,GAAG,QAAQ;EAC9C,IAAI,OAAO,UAAU,UACjB,OAAO,oBAAoB,OAAO,WAAW;OAE7C,OAAO,GAAG,cAAc,MAAM;CAEtC,CAAC,CAAC,CAAC,QAAQ,KAAK,UAAU;EAAE,GAAG;EACnC,GAAG;CAAK,IAAI,CAAC,CAAC;AACd;;;ACCA,IAAM,iBAAiB;AAEvB,eAAsB,qBAAwD,OAkB3E;CAEC,MAAM,aAAa,oBAAoB,MAAM,MAAM;CAEnD,MAAM,aAAa,MAAM;CAOzB,MAAM,UAAkC;EACpC,aAAA;GALA,UAAU,MAAM;GAChB,QAAQ;EAIR;EACA;EACA,YAAY,MAA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AAmB,OAAO;CAEhC,OAAO,MAAM,eAAe;EACxB,KAAK;EACL,OAAO,CACH;GACI,MAAM;GACN,WAAW;GACX,OAAO;EACX,CACJ;EACA,WAAW,CACP;GACI,OAAO;GACP,WAAW;GACX,OAAO;IACH;IACA;IACA,MAAM,OAAO;GACjB;EACJ,CACJ;CACJ,IAAI;EAAC;EAAQ;EAAkB,OAAO;CAAI,CAAC;AAC/C"}
|
|
1
|
+
{"version":3,"file":"index.es.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.admin?.disabled || property.admin?.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.admin?.disabled || property.admin?.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.admin?.disabled || property.admin?.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.admin?.disabled || property.admin?.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 } from \"@rebasepro/types\";\nimport { PluginFormActionProps } from \"@rebasepro/admin-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} from \"@rebasepro/app\";\nimport { EntityStatus, Properties, Property } from \"@rebasepro/types\";\nimport { PluginFormActionProps } from \"@rebasepro/admin-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\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 // Never full width: this used to stretch to fill the form's\n // `w-80 2xl:w-96` side rail in full screen. That rail is gone, and\n // in the footer a stretched button reads as the primary action.\n trigger={<Button variant={\"filled\"}\n color={\"neutral\"}\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.admin?.markdown || p.admin?.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, User } from \"@rebasepro/types\";\nimport { RebasePlugin } from \"@rebasepro/admin-types\";\nimport { DataEnhancementControllerProvider } from \"./components/DataEnhancementControllerProvider\";\nimport { FormEnhanceAction } from \"./components/FormEnhanceAction\";\n\n/**\n * Key used when the host app supplies none. Exported so a test can assert that\n * this is the value threaded through to the provider without transcribing the\n * literal — a copy in a test pins the key rather than the wiring, and makes\n * rotating it a test failure.\n */\nexport const 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":";;;;;;;;AAAA,SAAgB,oBAAsC,QAAW,OAAO,IAAY;CAChF,IAAI,CAAC,QAAQ,OAAO,CAAC;CACrB,OAAO,OAAO,QAAQ,MAAM,CAAC,CAAC,SAAS,C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D,aAAa,QAAQ,YAAY,KAAK,UAAU,CAAC,QAAQ,GAAG,cACvD,KAAI,MAAK,EAAE,MAAM,CAAC,CAClB,QAAO,MAAK,MAAM,MAAM,CAAC,CACzB,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;AACtB;AAEA,IAAM,sBAAsB,YAAoB,WAAmB;CAC/D,aAAa,QAAQ,YAAY,KAAK,UAAU,4BAA4B,UAAU,CAAC,CAClF,KAAI,MAAK,EAAE,MAAM,CAAC,CAClB,QAAO,MAAK,MAAM,MAAM,CAAC,CAAC;AACnC;;;;;;ACvOA,SAAgB,yBAAyB,OAAkD;CAEvF,MAAM,SAAS,OAAO,UAAA;CACtB,MAAM,mBAAmB,OAAO;CAEhC,OAAO,MAAM,eAAe;EACxB,KAAK;EACL,OAAO,CACH;GACI,MAAM;GACN,WAAW;GACX,OAAO;EACX,CACJ;EACA,WAAW,CACP;GACI,OAAO;GACP,WAAW;GACX,OAAO;IACH;IACA;IACA,MAAM,OAAO;GACjB;EACJ,CACJ;CACJ,IAAI;EAAC;EAAQ;EAAkB,OAAO;CAAI,CAAC;AAC/C"}
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import { CollectionConfig, User } from "@rebasepro/types";
|
|
2
2
|
import { RebasePlugin } from "@rebasepro/admin-types";
|
|
3
|
+
/**
|
|
4
|
+
* Key used when the host app supplies none. Exported so a test can assert that
|
|
5
|
+
* this is the value threaded through to the provider without transcribing the
|
|
6
|
+
* literal — a copy in a test pins the key rather than the wiring, and makes
|
|
7
|
+
* rotating it a test failure.
|
|
8
|
+
*/
|
|
9
|
+
export declare const DEFAULT_API_KEY = "fcms-U9jdDii0xXWSDC34asfrf54lbkFJBfKfRWcEDEwdc4V5wDWEDF";
|
|
3
10
|
export interface DataEnhancementPluginProps {
|
|
4
11
|
apiKey?: string;
|
|
5
12
|
/**
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rebasepro/plugin-ai",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.12.1-canary.
|
|
4
|
+
"version": "0.12.1-canary.g4e7bcbf",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"main": "./dist/index.es.js",
|
|
7
7
|
"module": "./dist/index.es.js",
|
|
@@ -16,13 +16,13 @@
|
|
|
16
16
|
"./package.json": "./package.json"
|
|
17
17
|
},
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"@rebasepro/admin": "0.12.1-canary.
|
|
20
|
-
"@rebasepro/admin-types": "0.12.1-canary.
|
|
21
|
-
"@rebasepro/
|
|
22
|
-
"@rebasepro/
|
|
23
|
-
"@rebasepro/
|
|
24
|
-
"@rebasepro/
|
|
25
|
-
"@rebasepro/
|
|
19
|
+
"@rebasepro/admin": "0.12.1-canary.g4e7bcbf",
|
|
20
|
+
"@rebasepro/admin-types": "0.12.1-canary.g4e7bcbf",
|
|
21
|
+
"@rebasepro/common": "0.12.1-canary.g4e7bcbf",
|
|
22
|
+
"@rebasepro/app": "0.12.1-canary.g4e7bcbf",
|
|
23
|
+
"@rebasepro/types": "0.12.1-canary.g4e7bcbf",
|
|
24
|
+
"@rebasepro/ui": "0.12.1-canary.g4e7bcbf",
|
|
25
|
+
"@rebasepro/utils": "0.12.1-canary.g4e7bcbf"
|
|
26
26
|
},
|
|
27
27
|
"peerDependencies": {
|
|
28
28
|
"react": ">=19.2.7",
|
|
@@ -3,6 +3,28 @@
|
|
|
3
3
|
|
|
4
4
|
import { Change, diffStrings } from "../utils/diffStrings";
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* What a diff has to satisfy no matter how it segments the strings: the kept
|
|
8
|
+
* and deleted parts rebuild the old string, the kept and inserted parts rebuild
|
|
9
|
+
* the new one, no segment is empty, and no two neighbours share a type.
|
|
10
|
+
*
|
|
11
|
+
* Asserted instead of a hard-coded segmentation where the segmentation is an
|
|
12
|
+
* artefact of the LCS strategy rather than a contract — pinning it made any
|
|
13
|
+
* improvement to the algorithm a test failure, so the test was defending the
|
|
14
|
+
* implementation against being made better.
|
|
15
|
+
*/
|
|
16
|
+
function expectValidDiff(changes: Change[], oldStr: string, newStr: string) {
|
|
17
|
+
const rebuilt = (skip: Change["type"]) => changes
|
|
18
|
+
.filter(c => c.type !== skip)
|
|
19
|
+
.map(c => c.value)
|
|
20
|
+
.join("");
|
|
21
|
+
|
|
22
|
+
expect(rebuilt("insert")).toBe(oldStr);
|
|
23
|
+
expect(rebuilt("delete")).toBe(newStr);
|
|
24
|
+
expect(changes.every(c => c.value.length > 0)).toBe(true);
|
|
25
|
+
expect(changes.every((c, i) => i === 0 || c.type !== changes[i - 1].type)).toBe(true);
|
|
26
|
+
}
|
|
27
|
+
|
|
6
28
|
describe("diffStrings", () => {
|
|
7
29
|
test("equal strings", () => {
|
|
8
30
|
const oldStr = "This is a test string";
|
|
@@ -13,7 +35,9 @@ describe("diffStrings", () => {
|
|
|
13
35
|
value: "This is a test string"
|
|
14
36
|
}
|
|
15
37
|
];
|
|
16
|
-
|
|
38
|
+
const changes = diffStrings(oldStr, newStr);
|
|
39
|
+
expectValidDiff(changes, oldStr, newStr);
|
|
40
|
+
expect(changes).toEqual(expected);
|
|
17
41
|
});
|
|
18
42
|
|
|
19
43
|
test("insertions only", () => {
|
|
@@ -33,7 +57,9 @@ describe("diffStrings", () => {
|
|
|
33
57
|
value: " test string"
|
|
34
58
|
}
|
|
35
59
|
];
|
|
36
|
-
|
|
60
|
+
const changes = diffStrings(oldStr, newStr);
|
|
61
|
+
expectValidDiff(changes, oldStr, newStr);
|
|
62
|
+
expect(changes).toEqual(expected);
|
|
37
63
|
});
|
|
38
64
|
|
|
39
65
|
test("deletions only", () => {
|
|
@@ -53,57 +79,28 @@ describe("diffStrings", () => {
|
|
|
53
79
|
value: " test string"
|
|
54
80
|
}
|
|
55
81
|
];
|
|
56
|
-
|
|
82
|
+
const changes = diffStrings(oldStr, newStr);
|
|
83
|
+
expectValidDiff(changes, oldStr, newStr);
|
|
84
|
+
expect(changes).toEqual(expected);
|
|
57
85
|
});
|
|
58
86
|
|
|
59
87
|
test("insertions and deletions", () => {
|
|
60
88
|
const oldStr = "This is an old test string";
|
|
61
89
|
const newStr = "This is a new modified test string";
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
},
|
|
77
|
-
{
|
|
78
|
-
type: "insert",
|
|
79
|
-
value: "ew"
|
|
80
|
-
},
|
|
81
|
-
{
|
|
82
|
-
type: "equal",
|
|
83
|
-
value: " "
|
|
84
|
-
},
|
|
85
|
-
{
|
|
86
|
-
type: "insert",
|
|
87
|
-
value: "m"
|
|
88
|
-
},
|
|
89
|
-
{
|
|
90
|
-
type: "equal",
|
|
91
|
-
value: "o"
|
|
92
|
-
},
|
|
93
|
-
{
|
|
94
|
-
type: "delete",
|
|
95
|
-
value: "l"
|
|
96
|
-
},
|
|
97
|
-
{
|
|
98
|
-
type: "insert",
|
|
99
|
-
value: "difie"
|
|
100
|
-
},
|
|
101
|
-
{
|
|
102
|
-
type: "equal",
|
|
103
|
-
value: "d test string"
|
|
104
|
-
}
|
|
105
|
-
];
|
|
106
|
-
expect(diffStrings(oldStr, newStr)).toEqual(expected);
|
|
90
|
+
|
|
91
|
+
const changes = diffStrings(oldStr, newStr);
|
|
92
|
+
|
|
93
|
+
expectValidDiff(changes, oldStr, newStr);
|
|
94
|
+
// Both edit kinds have to be present — a diff that only inserted would
|
|
95
|
+
// rebuild both strings only if nothing was ever removed.
|
|
96
|
+
expect(changes.some(c => c.type === "insert")).toBe(true);
|
|
97
|
+
expect(changes.some(c => c.type === "delete")).toBe(true);
|
|
98
|
+
// The shared prefix and suffix are long and unambiguous, so they are a
|
|
99
|
+
// contract rather than an artefact.
|
|
100
|
+
expect(changes[0]).toEqual({ type: "equal",
|
|
101
|
+
value: "This is a" });
|
|
102
|
+
expect(changes[changes.length - 1]).toEqual({ type: "equal",
|
|
103
|
+
value: "d test string" });
|
|
107
104
|
});
|
|
108
105
|
|
|
109
106
|
test("completely different strings", () => {
|
|
@@ -123,6 +120,8 @@ describe("diffStrings", () => {
|
|
|
123
120
|
value: " string"
|
|
124
121
|
}
|
|
125
122
|
];
|
|
126
|
-
|
|
123
|
+
const changes = diffStrings(oldStr, newStr);
|
|
124
|
+
expectValidDiff(changes, oldStr, newStr);
|
|
125
|
+
expect(changes).toEqual(expected);
|
|
127
126
|
});
|
|
128
127
|
});
|
|
@@ -36,8 +36,11 @@ describe("getAppendableSuggestion", () => {
|
|
|
36
36
|
expect(result).toBe("Hello World");
|
|
37
37
|
});
|
|
38
38
|
|
|
39
|
-
it("
|
|
40
|
-
|
|
39
|
+
it("ignores whitespace around the value", () => {
|
|
40
|
+
// What the user has typed arrives with the field's own padding, so the
|
|
41
|
+
// comparison and the offset both trim it. Byte-identical to the first
|
|
42
|
+
// test until the value actually carries whitespace.
|
|
43
|
+
const result = getAppendableSuggestion("Hello World", " Hello ");
|
|
41
44
|
expect(result).toBe(" World");
|
|
42
45
|
});
|
|
43
46
|
|
|
@@ -18,7 +18,7 @@ if (typeof window !== "undefined") {
|
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
import { renderHook } from "@testing-library/react";
|
|
21
|
-
import { useDataEnhancementPlugin } from "../useDataEnhancementPlugin";
|
|
21
|
+
import { DEFAULT_API_KEY, useDataEnhancementPlugin } from "../useDataEnhancementPlugin";
|
|
22
22
|
|
|
23
23
|
jest.mock("@rebasepro/admin", () => ({
|
|
24
24
|
useUrlController: () => ({})
|
|
@@ -29,12 +29,21 @@ describe("useDataEnhancementPlugin hook", () => {
|
|
|
29
29
|
const { result } = renderHook(() => useDataEnhancementPlugin());
|
|
30
30
|
const plugin = result.current;
|
|
31
31
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
expect(
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
32
|
+
// Matched as one shape rather than indexed field by field. `slots` and
|
|
33
|
+
// `providers` are optional on `Plugin`, and a preceding
|
|
34
|
+
// `expect(...).toBeDefined()` does not narrow them for TypeScript — so
|
|
35
|
+
// the indexed form only compiled because nothing type-checked this file.
|
|
36
|
+
// `toMatchObject` needs no narrowing and pins the fields together, which
|
|
37
|
+
// is what "correct metadata" actually means.
|
|
38
|
+
//
|
|
39
|
+
// `apiKey` is compared against the exported constant, not a copy of it:
|
|
40
|
+
// a copy pins the key rather than the wiring that hands it to the
|
|
41
|
+
// provider.
|
|
42
|
+
expect(plugin).toMatchObject({
|
|
43
|
+
key: "data_enhancement",
|
|
44
|
+
slots: [{ slot: "form.actions" }],
|
|
45
|
+
providers: [{ scope: "form", props: { apiKey: DEFAULT_API_KEY } }]
|
|
46
|
+
});
|
|
38
47
|
});
|
|
39
48
|
|
|
40
49
|
it("accepts and forwards custom apiKey and host props", () => {
|
|
@@ -45,7 +54,8 @@ describe("useDataEnhancementPlugin hook", () => {
|
|
|
45
54
|
const { result } = renderHook(() => useDataEnhancementPlugin(customProps));
|
|
46
55
|
const plugin = result.current;
|
|
47
56
|
|
|
48
|
-
expect(plugin
|
|
49
|
-
|
|
57
|
+
expect(plugin).toMatchObject({
|
|
58
|
+
providers: [{ props: { apiKey: "custom-key", host: "https://custom-host.com" } }]
|
|
59
|
+
});
|
|
50
60
|
});
|
|
51
61
|
});
|
|
@@ -5,7 +5,13 @@ import { RebasePlugin } from "@rebasepro/admin-types";
|
|
|
5
5
|
import { DataEnhancementControllerProvider } from "./components/DataEnhancementControllerProvider";
|
|
6
6
|
import { FormEnhanceAction } from "./components/FormEnhanceAction";
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Key used when the host app supplies none. Exported so a test can assert that
|
|
10
|
+
* this is the value threaded through to the provider without transcribing the
|
|
11
|
+
* literal — a copy in a test pins the key rather than the wiring, and makes
|
|
12
|
+
* rotating it a test failure.
|
|
13
|
+
*/
|
|
14
|
+
export const DEFAULT_API_KEY = "fcms-U9jdDii0xXWSDC34asfrf54lbkFJBfKfRWcEDEwdc4V5wDWEDF";
|
|
9
15
|
|
|
10
16
|
export interface DataEnhancementPluginProps {
|
|
11
17
|
|