@e-llm-studio/instant-learning 1.3.8 → 1.3.10
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/ComponentRegistry.js +52 -12
- package/dist/ComponentRegistry.js.map +1 -1
- package/dist/cjs/ComponentRegistry.js +52 -12
- package/dist/cjs/ComponentRegistry.js.map +1 -1
- package/dist/cjs/features/IL-OTJ/_components/hooks/useVariantEditSession.js +58 -29
- package/dist/cjs/features/IL-OTJ/_components/hooks/useVariantEditSession.js.map +1 -1
- package/dist/cjs/features/LearningManagement/components/ConfirmationModal.js +5 -3
- package/dist/cjs/features/LearningManagement/components/ConfirmationModal.js.map +1 -1
- package/dist/cjs/features/LearningManagement/components/InstantLearningModal.js +62 -2
- package/dist/cjs/features/LearningManagement/components/InstantLearningModal.js.map +1 -1
- package/dist/cjs/features/LearningManagement/components/InstantLearningModalDynamic.js +55 -7
- package/dist/cjs/features/LearningManagement/components/InstantLearningModalDynamic.js.map +1 -1
- package/dist/cjs/schema-driven/components/GroupEditRow.js +4 -0
- package/dist/cjs/schema-driven/components/GroupEditRow.js.map +1 -1
- package/dist/cjs/schema-driven/components/RepeatableSectionField.js +247 -0
- package/dist/cjs/schema-driven/components/RepeatableSectionField.js.map +1 -0
- package/dist/cjs/schema-driven/components/TableComponent.js +11 -2
- package/dist/cjs/schema-driven/components/TableComponent.js.map +1 -1
- package/dist/cjs/schema-driven/helper.js +14 -4
- package/dist/cjs/schema-driven/helper.js.map +1 -1
- package/dist/cjs/schema-driven/hooks/useSectionEditSession.js +2 -1
- package/dist/cjs/schema-driven/hooks/useSectionEditSession.js.map +1 -1
- package/dist/cjs/schema-driven/types.js.map +1 -1
- package/dist/cjs/schema-driven/utils/PayloadUtils.js +22 -12
- package/dist/cjs/schema-driven/utils/PayloadUtils.js.map +1 -1
- package/dist/features/IL-OTJ/_components/hooks/useVariantEditSession.js +58 -30
- package/dist/features/IL-OTJ/_components/hooks/useVariantEditSession.js.map +1 -1
- package/dist/features/LearningManagement/components/ConfirmationModal.js +5 -3
- package/dist/features/LearningManagement/components/ConfirmationModal.js.map +1 -1
- package/dist/features/LearningManagement/components/InstantLearningModal.js +62 -2
- package/dist/features/LearningManagement/components/InstantLearningModal.js.map +1 -1
- package/dist/features/LearningManagement/components/InstantLearningModalDynamic.js +55 -7
- package/dist/features/LearningManagement/components/InstantLearningModalDynamic.js.map +1 -1
- package/dist/schema-driven/components/GroupEditRow.js +4 -0
- package/dist/schema-driven/components/GroupEditRow.js.map +1 -1
- package/dist/schema-driven/components/RepeatableSectionField.js +243 -0
- package/dist/schema-driven/components/RepeatableSectionField.js.map +1 -0
- package/dist/schema-driven/components/TableComponent.js +11 -2
- package/dist/schema-driven/components/TableComponent.js.map +1 -1
- package/dist/schema-driven/helper.js +14 -4
- package/dist/schema-driven/helper.js.map +1 -1
- package/dist/schema-driven/hooks/useSectionEditSession.js +2 -1
- package/dist/schema-driven/hooks/useSectionEditSession.js.map +1 -1
- package/dist/schema-driven/types.js.map +1 -1
- package/dist/schema-driven/utils/PayloadUtils.js +22 -12
- package/dist/schema-driven/utils/PayloadUtils.js.map +1 -1
- package/dist/types/src/ComponentRegistry.d.ts.map +1 -1
- package/dist/types/src/ILMarketplaceMockTest.d.ts.map +1 -1
- package/dist/types/src/features/IL-OTJ/_components/hooks/useVariantEditSession.d.ts +3 -1
- package/dist/types/src/features/IL-OTJ/_components/hooks/useVariantEditSession.d.ts.map +1 -1
- package/dist/types/src/features/LearningManagement/components/ConfirmationModal.d.ts.map +1 -1
- package/dist/types/src/features/LearningManagement/components/InstantLearningModal.d.ts +30 -1
- package/dist/types/src/features/LearningManagement/components/InstantLearningModal.d.ts.map +1 -1
- package/dist/types/src/features/LearningManagement/components/InstantLearningModalDynamic.d.ts +12 -0
- package/dist/types/src/features/LearningManagement/components/InstantLearningModalDynamic.d.ts.map +1 -1
- package/dist/types/src/schema-driven/components/GroupEditRow.d.ts.map +1 -1
- package/dist/types/src/schema-driven/components/RepeatableSectionField.d.ts +11 -0
- package/dist/types/src/schema-driven/components/RepeatableSectionField.d.ts.map +1 -0
- package/dist/types/src/schema-driven/components/TableComponent.d.ts.map +1 -1
- package/dist/types/src/schema-driven/helper.d.ts +1 -1
- package/dist/types/src/schema-driven/helper.d.ts.map +1 -1
- package/dist/types/src/schema-driven/hooks/useSectionEditSession.d.ts.map +1 -1
- package/dist/types/src/schema-driven/types.d.ts +6 -0
- package/dist/types/src/schema-driven/types.d.ts.map +1 -1
- package/dist/types/src/schema-driven/utils/PayloadUtils.d.ts.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PayloadUtils.js","sources":["../../../../src/schema-driven/utils/PayloadUtils.ts"],"sourcesContent":["// src/schema-driven/utils/PayloadUtils.ts\nimport { useDynamicFormStore } from '../store/useDynamicFormStore';\nimport { isTableValueValid } from '../helper';\nimport { stripAiReasoning } from './aiReasoning';\n/**\n * Two distinct keys per schema leaf, and they are NOT interchangeable:\n * - PROPERTY KEY — the key under `properties` (e.g. `rule_title`, `wta`). This is\n * the ON-THE-WIRE key: what we send to the AI in `ui_state` and what the AI\n * echoes back in its response JSON.\n * - data_key — the internal dynamic-store slot the RHS field reads/writes\n * (e.g. `template_title`, `whenToApply`).\n * So the round-trip is: read store by data_key → emit under property key → AI\n * responds under property key → write store by data_key.\n *\n * Which store bucket a leaf lives in, mirrored by both read (generatePayloadFromSchema)\n * and write (applyResponseToStore) so the round-trip stays symmetric:\n * - `global.`-prefixed data_key, OR a field outside a variant wrapper → global.\n * - otherwise → variant-scoped (tierKey + variantIndex).\n * The data_key is stored WITHOUT the `global.` prefix (`cleanKey`).\n */\nconst resolveScope = (dataKey: string, isVariantLevel: boolean) => ({\n cleanKey: dataKey.replace('global.', ''),\n isGlobal: dataKey.startsWith('global.') || !isVariantLevel,\n});\n/**\n * A section is the repeatable-variant container if it renders as VariantListWrapper\n * OR is explicitly flagged `is_repeatable_variant: true`. Detection MUST match what\n * VariantListField renders per variant, so the store scope (global vs variant) and\n * the UI stay in sync. Its child leaves are variant-scoped; everything else is global.\n */\nconst isVariantWrapper = (node: any): boolean =>\n node?.is_repeatable_variant === true || node?.bpa_ui_component === 'VariantListWrapper';\n\nexport const getVariantPrefilledData = (\n jsonSchema: any,\n prefilledData: Record<string, any>,\n) => {\n const variantData: Record<string, Record<number, Record<string, any>>> = {};\n\n const traverse = (properties: any, isVariantLevel = false) => {\n if (!properties) return;\n Object.values(properties).forEach((node: any) => {\n const dataKey = node?.data_key;\n const cleanKey = dataKey?.replace('global.', '');\n const isVariantField = isVariantLevel && !dataKey?.startsWith('global.');\n\n if (isVariantField && Object.prototype.hasOwnProperty.call(prefilledData, cleanKey)) {\n variantData.tier_1 ??= {};\n variantData.tier_1[0] ??= {};\n variantData.tier_1[0][cleanKey] = prefilledData[cleanKey];\n }\n\n if (node?.properties) traverse(node.properties, isVariantLevel || isVariantWrapper(node));\n });\n };\n\n traverse(jsonSchema?.properties);\n return variantData;\n};\n\n/**\n * A core leaf's value may arrive under a looser name than the property key:\n * - from the AI's `updated_fields` (e.g. `title` for `rule_title`), or\n * - from the rule-fetch API on load, which uses its own fixed field names\n * (`ruleTitle`, `description`, `whenToApply`, `whenNotToApply`).\n * Read those aliases without changing the canonical wire key we emit. Keys here\n * are the conventional property keys; a schema using different keys would extend this.\n * Shared by `applyResponseToStore` (store hydration) and `buildFieldLabelMap`\n * (chat labels) so both resolve the AI's key names the same way.\n */\nexport const CORE_KEY_ALIASES: Record<string, string[]> = {\n rule_title: ['title', 'ruleTitle'],\n rule_description: ['description', 'variant_description'],\n wta: ['whenToApply', 'when_to_apply'],\n wnta: ['whenNotToApply', 'when_not_to_apply'],\n};\n\n/**\n * Build the AI-key → user-facing-label map for the schema-driven flow.\n *\n * The C.A.R.E. response echoes schema PROPERTY KEYS (or their `CORE_KEY_ALIASES`)\n * in `updated_fields` / `identified_fields`. The chat renderer must label those\n * with the same title the RHS form shows, and the JSON owns that title\n * (`rule_title` → \"Template Title\", `rule_description` → \"Template Goal\", …),\n * so it is derived here instead of being hardcoded in the renderer.\n *\n * Every leaf that carries a `title` contributes an entry under its property key\n * plus each of its aliases, so `title`, `rule_title` and `ruleTitle` all resolve\n * to the same label. Only the schema-driven modal passes this map down; the\n * legacy flow keeps the renderer's built-in defaults.\n */\nexport const buildFieldLabelMap = (jsonSchema: any): Record<string, string> => {\n const labels: Record<string, string> = {};\n const traverseSchema = (properties: any) => {\n if (!properties) return;\n Object.entries(properties).forEach(([propKey, node]: [string, any]) => {\n // `ui_only` wrappers (sections/rows) carry no value of their own, but their\n // children do — so recurse through them and only record leaf titles.\n if (node?.data_key && node?.title) {\n labels[propKey] = node.title;\n CORE_KEY_ALIASES[propKey]?.forEach((alias) => {\n labels[alias] = node.title;\n });\n }\n if (node?.properties) traverseSchema(node.properties);\n });\n };\n traverseSchema(jsonSchema?.properties);\n return labels;\n};\n\nexport const generatePayloadFromSchema = (jsonSchema: any, tierKey: string, variantIndex: number) => {\n const { getGlobalField, getVariantField } = useDynamicFormStore.getState();\n \n // `core_field: true` leaves sit at the top level of the payload; everything\n // else is collected under `learning_metadata`.\n const rootPayload: any = {};\n const metadataProperties: any = {};\n const metadataRequired: string[] = [];\n // Property keys whose value came from the per-variant store slot (getVariantField),\n // as opposed to the global slot shared across every variant. Callers that merge this\n // metadata bag with a variant's own API-saved metadata need this to know which keys\n // must always take the live store value (e.g. instruction_prompt) vs. which are fine\n // to let the API snapshot win (e.g. category).\n const variantScopedMetadataKeys: string[] = [];\n const traverseSchema = (properties: any, isVariantLevel: boolean = false) => {\n if (!properties) return;\n Object.entries(properties).forEach(([propKey, node]: [string, any]) => {\n if (node.ui_only) {\n if (isVariantWrapper(node)) return; \n if (node.properties) traverseSchema(node.properties, isVariantLevel);\n return;\n }\n if (node.data_key) {\n const { cleanKey, isGlobal } = resolveScope(node.data_key, isVariantLevel);\n let value = isGlobal \n ? getGlobalField(cleanKey) \n : getVariantField(tierKey, variantIndex, cleanKey);\n // ALWAYS provide a fallback default so the AI sees the empty keys\n // (it needs the previous value to reason about the user's request).\n if (value === undefined) {\n if (node.type === 'array') value = [];\n else if (node.type === 'boolean') value = false;\n else if (node.type === 'object') value = {};\n else value = ''; // default string (incl. \\n-joined wta/wnta)\n }\n // Condition fields keep AI reasoning inline in the store; never echo the\n // <ai_reasoning> tags back to the AI — send only the clean value.\n if (typeof value === 'string' && value.includes('<ai_reasoning>')) {\n value = stripAiReasoning(value).clean;\n }\n // Emit under the PROPERTY KEY (the AI's wire key), not the data_key.\n if (node.core_field) {\n rootPayload[propKey] = value;\n } else {\n metadataProperties[propKey] = value;\n // `required` is derived from each field's `is_required` flag in the JSON.\n if (node.is_required && !metadataRequired.includes(propKey)) {\n metadataRequired.push(propKey);\n }\n if (!isGlobal) variantScopedMetadataKeys.push(propKey);\n }\n }\n // Recursively traverse object properties\n if (node.properties && !isVariantWrapper(node)) {\n traverseSchema(node.properties, isVariantLevel);\n }\n });\n };\n const schemaProperties = jsonSchema?.properties || {};\n // 1. Traverse global properties\n traverseSchema(schemaProperties, false);\n // 2. Traverse variant properties\n const variantWrapper: any = Object.values(schemaProperties).find(isVariantWrapper);\n if (variantWrapper && variantWrapper.properties) {\n traverseSchema(variantWrapper.properties, true);\n }\n const learningMetadata = { properties: metadataProperties, required: metadataRequired };\n return { rootPayload, learningMetadata, variantScopedMetadataKeys };\n};\n/**\n * PROPERTY KEYS that hand ownership of the ruleset id to a form field. In the\n * JSON-driven flow the Sub-Category dropdown carries it (`ruleset_id`), so\n * whichever sub-category the user picks decides which ruleset the template is\n * saved into. `scope_id` is accepted as the same thing under the BE's name.\n */\nconst RULE_SET_ID_PROPERTY_KEYS = ['ruleset_id', 'scope_id'];\n\n/** First leaf (depth-first) whose property key hands over the ruleset id. */\nconst findRuleSetIdNode = (properties: any): any => {\n if (!properties) return null;\n for (const [propKey, node] of Object.entries<any>(properties)) {\n if (RULE_SET_ID_PROPERTY_KEYS.includes(propKey) && node?.data_key) return node;\n const nested = findRuleSetIdNode(node?.properties);\n if (nested) return nested;\n }\n return null;\n};\n\n/**\n * Options for a leaf, resolved exactly like DropdownSectionField renders them:\n * host-injected `dynamicOptions[<dynamic_options_key | data_key + 'Options'>]`\n * wins when non-empty, then inline `options`, then `enum`. Keeping the two in\n * sync matters — the id we return must come from the option the user saw.\n */\nconst resolveNodeOptions = (node: any, dynamicOptions?: Record<string, any>): any[] => {\n const optionsKey = node?.dynamic_options_key || `${node?.data_key}Options`;\n const hostOptions = dynamicOptions?.[optionsKey];\n if (Array.isArray(hostOptions) && hostOptions.length > 0) return hostOptions;\n if (Array.isArray(node?.options)) return node.options;\n if (Array.isArray(node?.enum)) {\n return node.enum.map((opt: any) =>\n opt && typeof opt === 'object' ? opt : { label: String(opt), value: opt },\n );\n }\n return [];\n};\n\n/**\n * The ruleset id the SCHEMA selects, or null when it doesn't select one.\n *\n * The dynamic store holds a dropdown's `value` (e.g. `weekly_digest`), never the\n * backing id — that travels on the option itself (`{ id, label, value }`, from\n * `dynamicOptions` or from inline JSON options that carry an `id`). So: find the\n * `ruleset_id`/`scope_id` leaf, read its store value, and return the id of the\n * option currently selected in it.\n *\n * Null means \"the schema has no opinion\" and the caller keeps whatever ruleset\n * it already used — that's the case for a schema without such a leaf, nothing\n * picked yet, or an option without an id. Only GLOBAL store values are read: a\n * ruleset is a per-template choice, not a per-variant one.\n */\nexport const resolveSchemaRuleSetId = (\n jsonSchema: any,\n dynamicOptions?: Record<string, any>,\n): string | null => {\n const node = findRuleSetIdNode(jsonSchema?.properties);\n if (!node) return null;\n\n // `cleanKey` — the store slot, with any `global.` data_key prefix stripped.\n const { cleanKey } = resolveScope(node.data_key, false);\n const value = useDynamicFormStore.getState().getGlobalField(cleanKey);\n if (!value) return null;\n\n // The API may hydrate a value with different casing from the dropdown option\n // (for example, `nyc` vs. `NYC`). Match strings case-insensitively, while\n // returning the option's UUID — never its display/value token.\n const normalizedValue = typeof value === 'string' ? value.trim().toLowerCase() : value;\n const selected = resolveNodeOptions(node, dynamicOptions).find((opt: any) => {\n const optionValue = typeof opt?.value === 'string' ? opt.value.trim().toLowerCase() : opt?.value;\n return optionValue === normalizedValue;\n });\n return selected?.id ?? null;\n};\n\nconst isFieldFilled = (value: any, node?: any): boolean => {\n if (node?.bpa_ui_component === 'TableComponent') return isTableValueValid(node, value);\n if (value === undefined || value === null) return false;\n if (Array.isArray(value)) return value.length > 0;\n if (typeof value === 'string') return value.trim() !== '';\n return true;\n};\n/**\n * Checks required JSON fields in the dynamic form store.\n * Optional tier/variant scopes limit validation to the data being saved.\n */\nexport const areRequiredFieldsFilled = (\n jsonSchema: any,\n tierVariantMap: Map<string, Map<number, any>>,\n activeTierKeys?: Iterable<string>,\n activeVariantIndexes?: Iterable<number>,\n): boolean => {\n const { getGlobalField, getVariantField } = useDynamicFormStore.getState();\n const schemaProperties = jsonSchema?.properties;\n if (!schemaProperties) return false;\n const activeTierKeySet = activeTierKeys ? new Set(activeTierKeys) : null;\n const activeVariantIndexSet = activeVariantIndexes ? new Set(activeVariantIndexes) : null;\n let allFilled = true;\n const traverseSchema = (properties: any, tierKey?: string, variantIndex?: number) => {\n if (!properties) return;\n Object.entries(properties).forEach(([, node]: [string, any]) => {\n if (node.ui_only && isVariantWrapper(node)) return;\n if (node.data_key && node.is_required) {\n const { cleanKey, isGlobal } = resolveScope(node.data_key, tierKey !== undefined);\n const value = isGlobal\n ? getGlobalField(cleanKey)\n : getVariantField(tierKey as string, variantIndex as number, cleanKey);\n if (!isFieldFilled(value, node)) allFilled = false;\n }\n if (node.properties && !isVariantWrapper(node)) {\n traverseSchema(node.properties, tierKey, variantIndex);\n }\n });\n };\n // Global fields, checked once.\n traverseSchema(schemaProperties);\n // Variant fields, checked once per tier/variantIndex pair actually in use.\n const variantWrapper: any = Object.values(schemaProperties).find(isVariantWrapper);\n if (variantWrapper?.properties) {\n tierVariantMap.forEach((variantMap, tierKey) => {\n if (activeTierKeySet && !activeTierKeySet.has(tierKey)) return;\n variantMap.forEach((_config, variantIndex) => {\n if (activeVariantIndexSet && !activeVariantIndexSet.has(variantIndex)) return;\n traverseSchema(variantWrapper.properties, tierKey, variantIndex);\n });\n });\n }\n return allFilled;\n};\n/**\n * Write an AI/C.A.R.E. response back into the dynamic store.\n *\n * The AI echoes the same PROPERTY KEYS we sent in `ui_state` (e.g. `rule_title`,\n * `wta`). For every schema leaf whose property key is present in `response`, we\n * write the value into the store slot (`data_key`) the field reads from — so the\n * RHS re-renders with the AI's value and the next payload build reflects it.\n * String-typed fields that carry a list (wta/wnta) may arrive as an array; we\n * join those to a single `\\n`-separated string to match the store's string shape.\n *\n * Where each key is read depends on where the writer put it (symmetry with\n * `generatePayloadFromSchema`):\n * - core_field leaves → top level of `response` (e.g. `response.wta`).\n * - non-core (learning_metadata) → under `response.learning_metadata.properties`.\n * For non-core we also tolerate older shapes on load/edit: a flat\n * `learning_metadata[propKey]`, or the legacy `{ type, title, value }` wrapper.\n *\n * Pass `tierKey`/`variantIndex` to hydrate a specific variant; omit them for the\n * global (non-variant) flow. `read_only` and `ui_only` leaves are never written\n * (host-owned values like Category/Sub-Category must survive the round-trip).\n */\nexport const applyResponseToStore = (\n jsonSchema: any,\n response: Record<string, any> | null | undefined,\n tierKey?: string,\n variantIndex?: number,\n // `hydrateAll` writes EVERY leaf (incl. non-AI fields like Category/Sub-Category).\n // Use it for the initial load/edit hydration from the fetched rule; the default\n // (live AI updates) only touches `ai_generated: true` leaves.\n // `variantOnly` skips the global pass entirely and writes only the variant\n // section — used when loading fetched variants so the API never fills global\n // fields (title/category), which are owned by the user + C.A.R.E.\n options?: { hydrateAll?: boolean; variantOnly?: boolean },\n) => {\n if (!response || typeof response !== 'object') return;\n const { setGlobalField, setVariantField, setGlobalReasoning, setVariantReasoning } = useDynamicFormStore.getState();\n const canWriteVariant = !!tierKey && variantIndex !== undefined;\n // Sentinel so we can distinguish \"key absent\" from \"key present but undefined\".\n const NOT_FOUND = Symbol('not-found');\n const metadataBag = response.learning_metadata?.properties ?? response.learning_metadata;\n // Core leaves may arrive under a looser name than the property key — see the\n // shared CORE_KEY_ALIASES table at the top of this file.\n const unwrapLegacyValue = (raw: any) =>\n raw && typeof raw === 'object' && !Array.isArray(raw) && 'value' in raw\n ? raw.value\n : raw;\n // Resolve the incoming value for a leaf, honoring core vs learning_metadata\n // placement and unwrapping the legacy `{ value }` shape when present. Initial\n // edit payloads from integrations may be flat API objects, so metadata leaves\n // also accept their `data_key` from either the metadata bag or that object.\n const readIncoming = (propKey: string, node: any, isCore: boolean): any => {\n if (isCore) {\n if (Object.prototype.hasOwnProperty.call(response, propKey)) return response[propKey];\n const alias = CORE_KEY_ALIASES[propKey]?.find((key) => Object.prototype.hasOwnProperty.call(response, key));\n return alias ? response[alias] : NOT_FOUND;\n }\n const dataKey = node.data_key?.replace('global.', '');\n for (const source of [metadataBag, response]) {\n if (!source || typeof source !== 'object') continue;\n if (propKey in source) return unwrapLegacyValue((source as any)[propKey]);\n if (dataKey && dataKey in source) return unwrapLegacyValue((source as any)[dataKey]);\n }\n return NOT_FOUND;\n };\n const traverseSchema = (properties: any, isVariantLevel: boolean = false) => {\n if (!properties) return;\n Object.entries(properties).forEach(([propKey, node]: [string, any]) => {\n if (node.ui_only) {\n if (isVariantWrapper(node)) return;\n if (node.properties) traverseSchema(node.properties, isVariantLevel);\n return;\n }\n // A leaf is hydrated from the response when the AI/system owns its value —\n // `ai_generated: true` (incl. read_only system fields like `value_id`, a\n // pipeline-resolved id the AI echoes back — we just store + re-send it) — or on\n // `hydrateAll` (initial load/edit seeds every leaf from the fetched rule). Plain\n // user-owned leaves (not ai_generated) are set immediately from input and are\n // never waited on or overwritten by the AI. `readIncoming` returns NOT_FOUND\n // when the response omits the key, so a field the AI doesn't send is untouched.\n if (node.data_key && (node.ai_generated === true || options?.hydrateAll)) {\n const { cleanKey, isGlobal } = resolveScope(node.data_key, isVariantLevel);\n let incoming = readIncoming(propKey, node, !!node.core_field);\n if (incoming !== NOT_FOUND) {\n // Normalize a list-shaped payload back into a \\n-joined string for\n // string leaves (wta/wnta), whose store slot holds a single string.\n if (node.type !== 'array' && Array.isArray(incoming)) {\n incoming = incoming.join('\\n');\n }\n if (incoming !== undefined) {\n // ConditionSection leaves (wta/wnta) can hold MANY conditions, each with\n // its own inline <ai_reasoning>. A single reasoning slot can't hold N of\n // them, so we keep the raw string (tags inline) and let the field parse\n // per-condition reasoning. Single-value leaves (title/goal) instead get\n // their reasoning stripped into the parallel reasoning bucket.\n const isConditionField = node.bpa_ui_component === 'ConditionSection';\n let reasoningRaw: string | null = null;\n if (!isConditionField && typeof incoming === 'string' && incoming.includes('<ai_reasoning>')) {\n const stripped = stripAiReasoning(incoming);\n incoming = stripped.clean;\n reasoningRaw = stripped.raw;\n }\n // Write it into the store under the data_key.\n if (isGlobal) {\n setGlobalField(cleanKey, incoming);\n if (reasoningRaw) setGlobalReasoning(cleanKey, reasoningRaw);\n } else if (canWriteVariant) {\n setVariantField(tierKey as string, variantIndex as number, cleanKey, incoming);\n if (reasoningRaw) setVariantReasoning(tierKey as string, variantIndex as number, cleanKey, reasoningRaw);\n }\n }\n }\n }\n if (node.properties && !isVariantWrapper(node)) {\n traverseSchema(node.properties, isVariantLevel);\n }\n });\n };\n const schemaProperties = jsonSchema?.properties || {};\n // Global pass — skipped for a variant-only hydrate (the API load).\n if (!options?.variantOnly) traverseSchema(schemaProperties, false);\n const variantWrapper: any = Object.values(schemaProperties).find(isVariantWrapper);\n if (variantWrapper && variantWrapper.properties) {\n traverseSchema(variantWrapper.properties, true);\n }\n};\n\n"],"names":["useDynamicFormStore","stripAiReasoning","isTableValueValid","_a","_b"],"mappings":";;;;;;;;AAoBA,MAAM,YAAA,GAAe,CAAC,OAAA,EAAiB,cAA6B,MAAA;AAAA,EAClE,QAAU,EAAA,OAAA,CAAQ,OAAQ,CAAA,SAAA,EAAW,EAAE,CAAA;AAAA,EACvC,QAAU,EAAA,OAAA,CAAQ,UAAW,CAAA,SAAS,KAAK,CAAC,cAAA;AAC9C,CA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A,GAAA,KAAA,CAAA,GAAA,UAAA,CAAA,UAAA,KAAc,EAAC,CAAA;AAEpD,EAAA,IAAI,EAAC,OAAA,IAAA,IAAA,GAAA,KAAA,CAAA,GAAA,OAAA,CAAS,WAAa,CAAA,EAAA,cAAA,CAAe,kBAAkB,KAAK,CAAA,CAAA;AACjE,EAAA,MAAM,iBAAsB,MAAO,CAAA,MAAA,CAAO,gBAAgB,CAAA,CAAE,KAAK,gBAAgB,CAAA,CAAA;AACjF,EAAI,IAAA,cAAA,IAAkB,eAAe,UAAY,EAAA;AAC/C,IAAe,cAAA,CAAA,cAAA,CAAe,YAAY,IAAI,CAAA,CAAA;AAAA,GAChD;AACF;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"PayloadUtils.js","sources":["../../../../src/schema-driven/utils/PayloadUtils.ts"],"sourcesContent":["// src/schema-driven/utils/PayloadUtils.ts\nimport { useDynamicFormStore } from '../store/useDynamicFormStore';\nimport { isTableValueValid } from '../helper';\nimport { stripAiReasoning } from './aiReasoning';\n/**\n * Two distinct keys per schema leaf, and they are NOT interchangeable:\n * - PROPERTY KEY — the key under `properties` (e.g. `rule_title`, `wta`). This is\n * the ON-THE-WIRE key: what we send to the AI in `ui_state` and what the AI\n * echoes back in its response JSON.\n * - data_key — the internal dynamic-store slot the RHS field reads/writes\n * (e.g. `template_title`, `whenToApply`).\n * So the round-trip is: read store by data_key → emit under property key → AI\n * responds under property key → write store by data_key.\n *\n * Which store bucket a leaf lives in, mirrored by both read (generatePayloadFromSchema)\n * and write (applyResponseToStore) so the round-trip stays symmetric:\n * - `global.`-prefixed data_key, OR a field outside a variant wrapper → global.\n * - otherwise → variant-scoped (tierKey + variantIndex).\n * The data_key is stored WITHOUT the `global.` prefix (`cleanKey`).\n */\nconst resolveScope = (dataKey: string, isVariantLevel: boolean) => ({\n cleanKey: dataKey.replace('global.', ''),\n isGlobal: dataKey.startsWith('global.') || !isVariantLevel,\n});\n/**\n * A section is the repeatable-variant container if it renders as VariantListWrapper\n * OR is explicitly flagged `is_repeatable_variant: true`. Detection MUST match what\n * VariantListField renders per variant, so the store scope (global vs variant) and\n * the UI stay in sync. Its child leaves are variant-scoped; everything else is global.\n */\nconst isVariantWrapper = (node: any): boolean =>\n node?.is_repeatable_variant === true || node?.bpa_ui_component === 'VariantListWrapper';\n\n// Unlike a normal object wrapper, a repeatable section owns one array value. Its\n// descendants are an item template, not independent top-level payload fields.\nconst isRepeatableSection = (node: any): boolean =>\n node?.repeatable === true || node?.bpa_ui_component === 'RepeatableSection';\n\nexport const getVariantPrefilledData = (jsonSchema: any, prefilledData: Record<string, any>) => {\n const variantData: Record<string, Record<number, Record<string, any>>> = {};\n\n const traverse = (properties: any, isVariantLevel = false) => {\n if (!properties) return;\n Object.values(properties).forEach((node: any) => {\n const dataKey = node?.data_key;\n const cleanKey = dataKey?.replace('global.', '');\n const isVariantField = isVariantLevel && !dataKey?.startsWith('global.');\n\n if (isVariantField && Object.prototype.hasOwnProperty.call(prefilledData, cleanKey)) {\n variantData.tier_1 ??= {};\n variantData.tier_1[0] ??= {};\n variantData.tier_1[0][cleanKey] = prefilledData[cleanKey];\n }\n\n if (node?.properties) traverse(node.properties, isVariantLevel || isVariantWrapper(node));\n });\n };\n\n traverse(jsonSchema?.properties);\n return variantData;\n};\n\n/**\n * A core leaf's value may arrive under a looser name than the property key:\n * - from the AI's `updated_fields` (e.g. `title` for `rule_title`), or\n * - from the rule-fetch API on load, which uses its own fixed field names\n * (`ruleTitle`, `description`, `whenToApply`, `whenNotToApply`).\n * Read those aliases without changing the canonical wire key we emit. Keys here\n * are the conventional property keys; a schema using different keys would extend this.\n * Shared by `applyResponseToStore` (store hydration) and `buildFieldLabelMap`\n * (chat labels) so both resolve the AI's key names the same way.\n */\nexport const CORE_KEY_ALIASES: Record<string, string[]> = {\n rule_title: ['title', 'ruleTitle'],\n rule_description: ['description', 'variant_description'],\n wta: ['whenToApply', 'when_to_apply'],\n wnta: ['whenNotToApply', 'when_not_to_apply'],\n};\n\n/**\n * Build the AI-key → user-facing-label map for the schema-driven flow.\n *\n * The C.A.R.E. response echoes schema PROPERTY KEYS (or their `CORE_KEY_ALIASES`)\n * in `updated_fields` / `identified_fields`. The chat renderer must label those\n * with the same title the RHS form shows, and the JSON owns that title\n * (`rule_title` → \"Template Title\", `rule_description` → \"Template Goal\", …),\n * so it is derived here instead of being hardcoded in the renderer.\n *\n * Every leaf that carries a `title` contributes an entry under its property key\n * plus each of its aliases, so `title`, `rule_title` and `ruleTitle` all resolve\n * to the same label. Only the schema-driven modal passes this map down; the\n * legacy flow keeps the renderer's built-in defaults.\n */\nexport const buildFieldLabelMap = (jsonSchema: any): Record<string, string> => {\n const labels: Record<string, string> = {};\n const traverseSchema = (properties: any) => {\n if (!properties) return;\n Object.entries(properties).forEach(([propKey, node]: [string, any]) => {\n // `ui_only` wrappers (sections/rows) carry no value of their own, but their\n // children do — so recurse through them and only record leaf titles.\n if (node?.data_key && node?.title) {\n labels[propKey] = node.title;\n CORE_KEY_ALIASES[propKey]?.forEach((alias) => {\n labels[alias] = node.title;\n });\n }\n if (node?.properties) traverseSchema(node.properties);\n });\n };\n traverseSchema(jsonSchema?.properties);\n return labels;\n};\n\nexport const generatePayloadFromSchema = (\n jsonSchema: any,\n tierKey: string,\n variantIndex: number\n) => {\n const { getGlobalField, getVariantField } = useDynamicFormStore.getState();\n\n // `core_field: true` leaves sit at the top level of the payload; everything\n // else is collected under `learning_metadata`.\n const rootPayload: any = {};\n const metadataProperties: any = {};\n const metadataRequired: string[] = [];\n // Property keys whose value came from the per-variant store slot (getVariantField),\n // as opposed to the global slot shared across every variant. Callers that merge this\n // metadata bag with a variant's own API-saved metadata need this to know which keys\n // must always take the live store value (e.g. instruction_prompt) vs. which are fine\n // to let the API snapshot win (e.g. category).\n const variantScopedMetadataKeys: string[] = [];\n const traverseSchema = (properties: any, isVariantLevel: boolean = false) => {\n if (!properties) return;\n Object.entries(properties).forEach(([propKey, node]: [string, any]) => {\n // A repeatable node is a value-bearing array even if older DTs left\n // `ui_only: true` on it. Treat it as the array field, never as a wrapper\n // whose item-template leaves should be emitted as flat metadata.\n if (node.ui_only && !isRepeatableSection(node)) {\n if (isVariantWrapper(node)) return;\n if (node.properties) traverseSchema(node.properties, isVariantLevel);\n return;\n }\n if (node.data_key) {\n const { cleanKey, isGlobal } = resolveScope(node.data_key, isVariantLevel);\n // A repeatable section owns an array under its data_key. Unlike ordinary\n // fields, its config property key may be an implementation-generated id,\n // so use the data_key as its stable wire/payload key.\n const payloadKey = isRepeatableSection(node) ? cleanKey : propKey;\n let value = isGlobal\n ? getGlobalField(cleanKey)\n : getVariantField(tierKey, variantIndex, cleanKey);\n // ALWAYS provide a fallback default so the AI sees the empty keys\n // (it needs the previous value to reason about the user's request).\n if (value === undefined) {\n if (node.type === 'array') value = [];\n else if (node.type === 'boolean') value = false;\n else if (node.type === 'object') value = {};\n else value = ''; // default string (incl. \\n-joined wta/wnta)\n }\n // Condition fields keep AI reasoning inline in the store; never echo the\n // <ai_reasoning> tags back to the AI — send only the clean value.\n if (typeof value === 'string' && value.includes('<ai_reasoning>')) {\n value = stripAiReasoning(value).clean;\n }\n // Emit under the PROPERTY KEY (the AI's wire key), not the data_key.\n if (node.core_field) {\n rootPayload[payloadKey] = value;\n } else {\n metadataProperties[payloadKey] = value;\n // `required` is derived from each field's `is_required` flag in the JSON.\n if (node.is_required && !metadataRequired.includes(payloadKey)) {\n metadataRequired.push(payloadKey);\n }\n if (!isGlobal) variantScopedMetadataKeys.push(payloadKey);\n }\n }\n // Recursively traverse object properties\n if (node.properties && !isVariantWrapper(node) && !isRepeatableSection(node)) {\n traverseSchema(node.properties, isVariantLevel);\n }\n });\n };\n const schemaProperties = jsonSchema?.properties || {};\n // 1. Traverse global properties\n traverseSchema(schemaProperties, false);\n // 2. Traverse variant properties\n const variantWrapper: any = Object.values(schemaProperties).find(isVariantWrapper);\n if (variantWrapper && variantWrapper.properties) {\n traverseSchema(variantWrapper.properties, true);\n }\n const learningMetadata = { properties: metadataProperties, required: metadataRequired };\n return { rootPayload, learningMetadata, variantScopedMetadataKeys };\n};\n/**\n * PROPERTY KEYS that hand ownership of the ruleset id to a form field. In the\n * JSON-driven flow the Sub-Category dropdown carries it (`ruleset_id`), so\n * whichever sub-category the user picks decides which ruleset the template is\n * saved into. `scope_id` is accepted as the same thing under the BE's name.\n */\nconst RULE_SET_ID_PROPERTY_KEYS = ['ruleset_id', 'scope_id'];\n\n/** First leaf (depth-first) whose property key hands over the ruleset id. */\nconst findRuleSetIdNode = (properties: any): any => {\n if (!properties) return null;\n for (const [propKey, node] of Object.entries<any>(properties)) {\n if (RULE_SET_ID_PROPERTY_KEYS.includes(propKey) && node?.data_key) return node;\n const nested = findRuleSetIdNode(node?.properties);\n if (nested) return nested;\n }\n return null;\n};\n\n/**\n * Options for a leaf, resolved exactly like DropdownSectionField renders them:\n * host-injected `dynamicOptions[<dynamic_options_key | data_key + 'Options'>]`\n * wins when non-empty, then inline `options`, then `enum`. Keeping the two in\n * sync matters — the id we return must come from the option the user saw.\n */\nconst resolveNodeOptions = (node: any, dynamicOptions?: Record<string, any>): any[] => {\n const optionsKey = node?.dynamic_options_key || `${node?.data_key}Options`;\n const hostOptions = dynamicOptions?.[optionsKey];\n if (Array.isArray(hostOptions) && hostOptions.length > 0) return hostOptions;\n if (Array.isArray(node?.options)) return node.options;\n if (Array.isArray(node?.enum)) {\n return node.enum.map((opt: any) =>\n opt && typeof opt === 'object' ? opt : { label: String(opt), value: opt }\n );\n }\n return [];\n};\n\n/**\n * The ruleset id the SCHEMA selects, or null when it doesn't select one.\n *\n * The dynamic store holds a dropdown's `value` (e.g. `weekly_digest`), never the\n * backing id — that travels on the option itself (`{ id, label, value }`, from\n * `dynamicOptions` or from inline JSON options that carry an `id`). So: find the\n * `ruleset_id`/`scope_id` leaf, read its store value, and return the id of the\n * option currently selected in it.\n *\n * Null means \"the schema has no opinion\" and the caller keeps whatever ruleset\n * it already used — that's the case for a schema without such a leaf, nothing\n * picked yet, or an option without an id. Only GLOBAL store values are read: a\n * ruleset is a per-template choice, not a per-variant one.\n */\nexport const resolveSchemaRuleSetId = (\n jsonSchema: any,\n dynamicOptions?: Record<string, any>\n): string | null => {\n const node = findRuleSetIdNode(jsonSchema?.properties);\n if (!node) return null;\n\n // `cleanKey` — the store slot, with any `global.` data_key prefix stripped.\n const { cleanKey } = resolveScope(node.data_key, false);\n const value = useDynamicFormStore.getState().getGlobalField(cleanKey);\n if (!value) return null;\n\n // The API may hydrate a value with different casing from the dropdown option\n // (for example, `nyc` vs. `NYC`). Match strings case-insensitively, while\n // returning the option's UUID — never its display/value token.\n const normalizedValue = typeof value === 'string' ? value.trim().toLowerCase() : value;\n const selected = resolveNodeOptions(node, dynamicOptions).find((opt: any) => {\n const optionValue =\n typeof opt?.value === 'string' ? opt.value.trim().toLowerCase() : opt?.value;\n return optionValue === normalizedValue;\n });\n return selected?.id ?? null;\n};\n\nconst isFieldFilled = (value: any, node?: any): boolean => {\n if (node?.bpa_ui_component === 'TableComponent') return isTableValueValid(node, value);\n if (value === undefined || value === null) return false;\n if (Array.isArray(value)) return value.length > 0;\n if (typeof value === 'string') return value.trim() !== '';\n return true;\n};\n/**\n * Checks required JSON fields in the dynamic form store.\n * Optional tier/variant scopes limit validation to the data being saved.\n */\nexport const areRequiredFieldsFilled = (\n jsonSchema: any,\n tierVariantMap: Map<string, Map<number, any>>,\n activeTierKeys?: Iterable<string>,\n activeVariantIndexes?: Iterable<number>\n): boolean => {\n const { getGlobalField, getVariantField } = useDynamicFormStore.getState();\n const schemaProperties = jsonSchema?.properties;\n if (!schemaProperties) return false;\n const activeTierKeySet = activeTierKeys ? new Set(activeTierKeys) : null;\n const activeVariantIndexSet = activeVariantIndexes ? new Set(activeVariantIndexes) : null;\n let allFilled = true;\n const traverseSchema = (properties: any, tierKey?: string, variantIndex?: number) => {\n if (!properties) return;\n Object.entries(properties).forEach(([, node]: [string, any]) => {\n if (node.ui_only && isVariantWrapper(node)) return;\n if (node.data_key && node.is_required) {\n const { cleanKey, isGlobal } = resolveScope(node.data_key, tierKey !== undefined);\n const value = isGlobal\n ? getGlobalField(cleanKey)\n : getVariantField(tierKey as string, variantIndex as number, cleanKey);\n if (!isFieldFilled(value, node)) allFilled = false;\n }\n if (node.properties && !isVariantWrapper(node) && !isRepeatableSection(node)) {\n traverseSchema(node.properties, tierKey, variantIndex);\n }\n });\n };\n // Global fields, checked once.\n traverseSchema(schemaProperties);\n // Variant fields, checked once per tier/variantIndex pair actually in use.\n const variantWrapper: any = Object.values(schemaProperties).find(isVariantWrapper);\n if (variantWrapper?.properties) {\n tierVariantMap.forEach((variantMap, tierKey) => {\n if (activeTierKeySet && !activeTierKeySet.has(tierKey)) return;\n variantMap.forEach((_config, variantIndex) => {\n if (activeVariantIndexSet && !activeVariantIndexSet.has(variantIndex)) return;\n traverseSchema(variantWrapper.properties, tierKey, variantIndex);\n });\n });\n }\n return allFilled;\n};\n/**\n * Write an AI/C.A.R.E. response back into the dynamic store.\n *\n * The AI echoes the same PROPERTY KEYS we sent in `ui_state` (e.g. `rule_title`,\n * `wta`). For every schema leaf whose property key is present in `response`, we\n * write the value into the store slot (`data_key`) the field reads from — so the\n * RHS re-renders with the AI's value and the next payload build reflects it.\n * String-typed fields that carry a list (wta/wnta) may arrive as an array; we\n * join those to a single `\\n`-separated string to match the store's string shape.\n *\n * Where each key is read depends on where the writer put it (symmetry with\n * `generatePayloadFromSchema`):\n * - core_field leaves → top level of `response` (e.g. `response.wta`).\n * - non-core (learning_metadata) → under `response.learning_metadata.properties`.\n * For non-core we also tolerate older shapes on load/edit: a flat\n * `learning_metadata[propKey]`, or the legacy `{ type, title, value }` wrapper.\n *\n * Pass `tierKey`/`variantIndex` to hydrate a specific variant; omit them for the\n * global (non-variant) flow. `read_only` and `ui_only` leaves are never written\n * (host-owned values like Category/Sub-Category must survive the round-trip).\n */\nexport const applyResponseToStore = (\n jsonSchema: any,\n response: Record<string, any> | null | undefined,\n tierKey?: string,\n variantIndex?: number,\n // `hydrateAll` writes EVERY leaf (incl. non-AI fields like Category/Sub-Category).\n // Use it for the initial load/edit hydration from the fetched rule; the default\n // (live AI updates) only touches `ai_generated: true` leaves.\n // `variantOnly` skips the global pass entirely and writes only the variant\n // section — used when loading fetched variants so the API never fills global\n // fields (title/category), which are owned by the user + C.A.R.E.\n options?: { hydrateAll?: boolean; variantOnly?: boolean }\n) => {\n if (!response || typeof response !== 'object') return;\n const { setGlobalField, setVariantField, setGlobalReasoning, setVariantReasoning } =\n useDynamicFormStore.getState();\n const canWriteVariant = !!tierKey && variantIndex !== undefined;\n // Sentinel so we can distinguish \"key absent\" from \"key present but undefined\".\n const NOT_FOUND = Symbol('not-found');\n const metadataBag = response.learning_metadata?.properties ?? response.learning_metadata;\n // Core leaves may arrive under a looser name than the property key — see the\n // shared CORE_KEY_ALIASES table at the top of this file.\n const unwrapLegacyValue = (raw: any) =>\n raw && typeof raw === 'object' && !Array.isArray(raw) && 'value' in raw ? raw.value : raw;\n // Resolve the incoming value for a leaf, honoring core vs learning_metadata\n // placement and unwrapping the legacy `{ value }` shape when present. Initial\n // edit payloads from integrations may be flat API objects, so metadata leaves\n // also accept their `data_key` from either the metadata bag or that object.\n const readIncoming = (propKey: string, node: any, isCore: boolean): any => {\n if (isCore) {\n if (Object.prototype.hasOwnProperty.call(response, propKey)) return response[propKey];\n const alias = CORE_KEY_ALIASES[propKey]?.find((key) =>\n Object.prototype.hasOwnProperty.call(response, key)\n );\n return alias ? response[alias] : NOT_FOUND;\n }\n const dataKey = node.data_key?.replace('global.', '');\n for (const source of [metadataBag, response]) {\n if (!source || typeof source !== 'object') continue;\n if (propKey in source) return unwrapLegacyValue((source as any)[propKey]);\n if (dataKey && dataKey in source) return unwrapLegacyValue((source as any)[dataKey]);\n }\n return NOT_FOUND;\n };\n const traverseSchema = (properties: any, isVariantLevel: boolean = false) => {\n if (!properties) return;\n Object.entries(properties).forEach(([propKey, node]: [string, any]) => {\n // Backward compatibility for DTs that still carry `ui_only: true` on a\n // repeatable array. Its data_key is the persisted array slot.\n if (node.ui_only && !isRepeatableSection(node)) {\n if (isVariantWrapper(node)) return;\n if (node.properties) traverseSchema(node.properties, isVariantLevel);\n return;\n }\n // A leaf is hydrated from the response when the AI/system owns its value —\n // `ai_generated: true` (incl. read_only system fields like `value_id`, a\n // pipeline-resolved id the AI echoes back — we just store + re-send it) — or on\n // `hydrateAll` (initial load/edit seeds every leaf from the fetched rule). Plain\n // user-owned leaves (not ai_generated) are set immediately from input and are\n // never waited on or overwritten by the AI. `readIncoming` returns NOT_FOUND\n // when the response omits the key, so a field the AI doesn't send is untouched.\n if (node.data_key && (node.ai_generated === true || options?.hydrateAll)) {\n const { cleanKey, isGlobal } = resolveScope(node.data_key, isVariantLevel);\n let incoming = readIncoming(propKey, node, !!node.core_field);\n if (incoming !== NOT_FOUND) {\n // Normalize a list-shaped payload back into a \\n-joined string for\n // string leaves (wta/wnta), whose store slot holds a single string.\n if (node.type !== 'array' && Array.isArray(incoming)) {\n incoming = incoming.join('\\n');\n }\n if (incoming !== undefined) {\n // ConditionSection leaves (wta/wnta) can hold MANY conditions, each with\n // its own inline <ai_reasoning>. A single reasoning slot can't hold N of\n // them, so we keep the raw string (tags inline) and let the field parse\n // per-condition reasoning. Single-value leaves (title/goal) instead get\n // their reasoning stripped into the parallel reasoning bucket.\n const isConditionField = node.bpa_ui_component === 'ConditionSection';\n let reasoningRaw: string | null = null;\n if (\n !isConditionField &&\n typeof incoming === 'string' &&\n incoming.includes('<ai_reasoning>')\n ) {\n const stripped = stripAiReasoning(incoming);\n incoming = stripped.clean;\n reasoningRaw = stripped.raw;\n }\n // Write it into the store under the data_key.\n if (isGlobal) {\n setGlobalField(cleanKey, incoming);\n if (reasoningRaw) setGlobalReasoning(cleanKey, reasoningRaw);\n } else if (canWriteVariant) {\n setVariantField(tierKey as string, variantIndex as number, cleanKey, incoming);\n if (reasoningRaw)\n setVariantReasoning(\n tierKey as string,\n variantIndex as number,\n cleanKey,\n reasoningRaw\n );\n }\n }\n }\n }\n if (node.properties && !isVariantWrapper(node) && !isRepeatableSection(node)) {\n traverseSchema(node.properties, isVariantLevel);\n }\n });\n };\n const schemaProperties = jsonSchema?.properties || {};\n // Global pass — skipped for a variant-only hydrate (the API load).\n if (!options?.variantOnly) traverseSchema(schemaProperties, false);\n const variantWrapper: any = Object.values(schemaProperties).find(isVariantWrapper);\n if (variantWrapper && variantWrapper.properties) {\n traverseSchema(variantWrapper.properties, true);\n }\n};\n"],"names":["useDynamicFormStore","stripAiReasoning","isTableValueValid","_a","_b"],"mappings":";;;;;;;;AAoBA,MAAM,YAAA,GAAe,CAAC,OAAA,EAAiB,cAA6B,MAAA;AAAA,EAClE,QAAU,EAAA,OAAA,CAAQ,OAAQ,CAAA,SAAA,EAAW,EAAE,CAAA;AAAA,EACvC,QAAU,EAAA,OAAA,CAAQ,UAAW,CAAA,SAAS,KAAK,CAAC,cAAA;AAC9C,CAAA,CAAA,CAAA;AAOA,MAAM,mBAAmB,CAAC,IAAA,KAAA,CACxB,6BAAM,qBAA0B,MAAA,IAAA,IAAA,CAAQ,6BAAM,gBAAqB,MAAA,oBAAA,CAAA;AAIrE,MAAM,sBAAsB,CAAC,IAAA,KAAA,CAC3B,6BAAM,UAAe,MAAA,IAAA,IAAA,CAAQ,6BAAM,gBAAqB,MAAA,mBAAA,CAAA;AAE7C,MAAA,uBAAA,GAA0B,CAAC,UAAA,EAAiB,aAAuC,KAAA;AAC9F,EAAA,MAAM,cAAmE,EAAC,CAAA;AAE1E,EAAA,MAAM,QAAW,GAAA,CAAC,UAAiB,EAAA,cAAA,GAAiB,KAAU,KAAA;AAC5D,IAAA,IAAI,CAAC,UAAY,EAAA,OAAA;AACjB,IAAA,MAAA,CAAO,MAAO,CAAA,UAAU,CAAE,CAAA,OAAA,CAAQ,CAAC,IAAc,KAAA;AA3CrD,MAAA,IAAA,EAAA,EAAA,EAAA,EAAA,EAAA,CAAA;AA4CM,MAAA,MAAM,UAAU,IAAM,IAAA,I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AO,gBAAgB,CAAA,CAAE,KAAK,gBAAgB,CAAA,CAAA;AACjF,EAAI,IAAA,cAAA,IAAkB,eAAe,UAAY,EAAA;AAC/C,IAAe,cAAA,CAAA,cAAA,CAAe,YAAY,IAAI,CAAA,CAAA;AAAA,GAChD;AACF;;;;;;;;;;"}
|
|
@@ -14,19 +14,48 @@ const diffConditions = (original, draft) => {
|
|
|
14
14
|
});
|
|
15
15
|
return { added, removed, edited };
|
|
16
16
|
};
|
|
17
|
-
const
|
|
17
|
+
const quoteList = (texts) => texts.map((t) => `"${t}"`).join(", ");
|
|
18
|
+
const buildConditionChangeFields = (sectionLabel, original, _draft, diff) => {
|
|
19
|
+
const removedTexts = diff.removed.filter((c) => hasMeaningfulText(c.text)).map((c) => c.text.trim());
|
|
20
|
+
const addedTexts = diff.added.map((c) => c.text.trim());
|
|
21
|
+
const updates = [];
|
|
22
|
+
diff.edited.forEach((c) => {
|
|
23
|
+
const orig = original.find((o) => o.id === c.id);
|
|
24
|
+
if (!orig) return;
|
|
25
|
+
const oldText = orig.text.trim();
|
|
26
|
+
const newText = c.text.trim();
|
|
27
|
+
if (!hasMeaningfulText(newText)) {
|
|
28
|
+
if (hasMeaningfulText(oldText)) removedTexts.push(oldText);
|
|
29
|
+
} else if (!hasMeaningfulText(oldText)) {
|
|
30
|
+
addedTexts.push(newText);
|
|
31
|
+
} else {
|
|
32
|
+
updates.push({
|
|
33
|
+
action: "update",
|
|
34
|
+
label: sectionLabel,
|
|
35
|
+
previous: quoteList([oldText]),
|
|
36
|
+
value: quoteList([newText])
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
const fields = [];
|
|
41
|
+
if (removedTexts.length) fields.push({ action: "remove", label: sectionLabel, value: quoteList(removedTexts) });
|
|
42
|
+
if (addedTexts.length) fields.push({ action: "add", label: sectionLabel, value: quoteList(addedTexts) });
|
|
43
|
+
fields.push(...updates);
|
|
44
|
+
return fields;
|
|
45
|
+
};
|
|
18
46
|
const buildEditMessage = (fields, isPromptChanged) => {
|
|
19
47
|
const promptNote = "I have updated the instruction prompt through RHS";
|
|
20
48
|
if (fields.length === 0) return promptNote;
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
49
|
+
const parts = fields.map((f) => {
|
|
50
|
+
switch (f.action) {
|
|
51
|
+
case "remove":
|
|
52
|
+
return `remove ${f.label}: ${f.value}`;
|
|
53
|
+
case "add":
|
|
54
|
+
return `add ${f.label}: ${f.value}`;
|
|
55
|
+
case "update":
|
|
56
|
+
return f.previous ? `update existing ${f.label}: ${f.previous} with a new ${f.value}` : `update details ${f.label} - ${f.value}`;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
30
59
|
const base = parts.join("; ");
|
|
31
60
|
return isPromptChanged ? `${base}. Also, ${promptNote.toLowerCase()}` : base;
|
|
32
61
|
};
|
|
@@ -104,28 +133,27 @@ function useVariantEditSession(uiState, buildVariantDraft, commitOnSave) {
|
|
|
104
133
|
const wnta = conditionsToText(draft.whenNotToApplyConditions);
|
|
105
134
|
const isWtaChanged = wta !== conditionsToText(original.whenToApplyConditions);
|
|
106
135
|
const isWntaChanged = wnta !== conditionsToText(original.whenNotToApplyConditions);
|
|
107
|
-
const conditionsToRawText = (conditions) => conditions.filter((c) => hasMeaningfulText(c.text)).map((c) => c.text.trim()).join(", ");
|
|
108
136
|
if (isWtaChanged) {
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
committed.whenToApplyText = conditionsToStoreText(
|
|
116
|
-
draft.whenToApplyConditions
|
|
117
|
-
);
|
|
137
|
+
fields.push(...buildConditionChangeFields(
|
|
138
|
+
"When to Apply",
|
|
139
|
+
original.whenToApplyConditions,
|
|
140
|
+
draft.whenToApplyConditions,
|
|
141
|
+
wtaDiff
|
|
142
|
+
));
|
|
143
|
+
committed.whenToApplyText = conditionsToStoreText(draft.whenToApplyConditions);
|
|
118
144
|
}
|
|
119
145
|
if (isWntaChanged) {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
committed.whenNotToApplyText = conditionsToStoreText(
|
|
127
|
-
|
|
128
|
-
|
|
146
|
+
fields.push(...buildConditionChangeFields(
|
|
147
|
+
"When Not to Apply",
|
|
148
|
+
original.whenNotToApplyConditions,
|
|
149
|
+
draft.whenNotToApplyConditions,
|
|
150
|
+
wntaDiff
|
|
151
|
+
));
|
|
152
|
+
committed.whenNotToApplyText = conditionsToStoreText(draft.whenNotToApplyConditions);
|
|
153
|
+
}
|
|
154
|
+
if (fields.length === 0 && !isPromptChanged) {
|
|
155
|
+
handleCancelVariantEdit();
|
|
156
|
+
return;
|
|
129
157
|
}
|
|
130
158
|
if (fields.length === 0 && !isPromptChanged) {
|
|
131
159
|
handleCancelVariantEdit();
|
|
@@ -156,5 +184,5 @@ function useVariantEditSession(uiState, buildVariantDraft, commitOnSave) {
|
|
|
156
184
|
};
|
|
157
185
|
}
|
|
158
186
|
|
|
159
|
-
export { buildEditMessage, conditionsToStoreText, conditionsToText, diffConditions, hasMeaningfulText, useVariantEditSession };
|
|
187
|
+
export { buildConditionChangeFields, buildEditMessage, conditionsToStoreText, conditionsToText, diffConditions, hasMeaningfulText, useVariantEditSession };
|
|
160
188
|
//# sourceMappingURL=useVariantEditSession.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useVariantEditSession.js","sources":["../../../../../src/features/IL-OTJ/_components/hooks/useVariantEditSession.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\n\nexport interface DraftCondition { id: number | string; text: string; reasoning?: string; conflict?: any }\n\nexport interface VariantDraft {\n ruleDescription: string;\n instructionPrompt: string;\n whenToApplyConditions: DraftCondition[];\n whenNotToApplyConditions: DraftCondition[];\n}\n\nexport type ConditionKey = 'whenToApplyConditions' | 'whenNotToApplyConditions';\n\n// A field counts as filled in only when it carries a letter or a digit — spaces and\n// punctuation alone don't qualify.\nexport const hasMeaningfulText = (text?: string | null) => !!text && /[a-z0-9À-]/i.test(text);\n\nexport const conditionsToText = (conditions: DraftCondition[]) =>\n conditions\n .filter((c) => hasMeaningfulText(c.text))\n .map((c, i) => `${i + 1}) ${c.text.trim()}`)\n .join(' ');\n\n// wta/wnta's real store format: one condition per line, no numbering (see\n// splitConditions, which splits on line breaks). The row UI numbers each item\n// itself off its index (ConditionList's `numberIndex`), so baking \"1) \"/\"2) \" into\n// the string here — as conditionsToText does for the chat-summary message — would\n// double it up on screen. Used for the mirage value, which must parse back the\n// same way the real committed string does.\nexport const conditionsToStoreText = (conditions: DraftCondition[]) =>\n conditions\n .filter((c) => hasMeaningfulText(c.text))\n .map((c) => c.text.trim())\n .join('\\n');\n\nexport type ChangeAction = 'update' | 'remove';\n\ninterface ChangedField {\n action: ChangeAction;\n label: string;\n value: string;\n}\n\n/** Per-condition diff (by id) — needed to tell \"row deleted\" apart from \"row edited\". */\nexport interface ConditionDiff {\n added: DraftCondition[];\n removed: DraftCondition[];\n edited: DraftCondition[];\n}\n\nexport const diffConditions = (original: DraftCondition[], draft: DraftCondition[]): ConditionDiff => {\n const draftIds = new Set(draft.map((c) => c.id));\n const originalIds = new Set(original.map((c) => c.id));\n const removed = original.filter((c) => !draftIds.has(c.id));\n const added = draft.filter((c) => !originalIds.has(c.id) && hasMeaningfulText(c.text));\n const edited = draft.filter((c) => {\n const orig = original.find((o) => o.id === c.id);\n return !!orig && orig.text.trim() !== c.text.trim();\n });\n return { added, removed, edited };\n};\n\n// A section (WTA/WNTA) is \"remove\" only if the sole change was a deletion —\n// any edit or addition alongside it makes it an \"update\" instead.\nconst sectionAction = (diff: ConditionDiff): ChangeAction =>\n diff.removed.length > 0 && diff.added.length === 0 && diff.edited.length === 0 ? 'remove' : 'update';\n\n/** Chat copy for a saved edit session. Fields are grouped by action so one \"remove\"\n * or \"update details\" prefix covers all fields sharing that action, instead of\n * repeating the verb per field. */\nexport const buildEditMessage = (fields: ChangedField[], isPromptChanged: boolean) => {\n const promptNote = 'I have updated the instruction prompt through RHS';\n if (fields.length === 0) return promptNote;\n\n const removeFields = fields.filter((f) => f.action === 'remove');\n const updateFields = fields.filter((f) => f.action === 'update');\n\n const parts: string[] = [];\n if (removeFields.length > 0) {\n parts.push(`remove ${removeFields.map((f) => `${f.label} - ${f.value}`).join(', ')}`);\n }\n if (updateFields.length > 0) {\n parts.push(`update details ${updateFields.map((f) => `${f.label} - ${f.value}`).join(', ')}`);\n }\n\n const base = parts.join('; ');\n return isPromptChanged ? `${base}. Also, ${promptNote.toLowerCase()}` : base;\n};\n\nexport interface VariantEditState {\n id: string;\n tierKey: string;\n variantIndex: number;\n label: string;\n original: VariantDraft;\n draft: VariantDraft;\n}\n\n/**\n * One edit session per variant: the whole variant body (description, prompt,\n * when/when-not to apply) is driven off a local draft, and Save sends ONE\n * combined chat message summarizing every changed field. Shared by CreateRule.tsx\n * (TrafficManager) and VariantListField.tsx (schema-driven) so both templates'\n * `backwardCompatibility === false` behavior stays identical.\n */\nexport function useVariantEditSession(\n uiState: any,\n buildVariantDraft: (item: any) => VariantDraft,\n // Called on Save with whichever fields changed. \n // The instruction prompt is user-owned and expected to be committed to the store right away; description/\n // WTA/WNTA are AI-owned and expected to be mirrored for display only until the\n // AI writes the real values back (see VariantListField's commitVariantEdit).\n // Optional so legacy mounts without a store binding keep working.\n commitOnSave?: (\n committed: {\n instructionPrompt?: string;\n ruleDescription?: string;\n whenToApplyText?: string;\n whenNotToApplyText?: string;\n },\n session: VariantEditState,\n ) => void,\n) {\n const [variantEdit, setVariantEdit] = useState<VariantEditState | null>(null);\n const [pendingVariantId, setPendingVariantId] = useState<string | null>(null);\n const prevStreamingVariant = useRef(uiState?.isAiStreaming);\n\n // Clear the variant \"Validating...\" state once the AI has finished responding.\n useEffect(() => {\n const streamingFinished = prevStreamingVariant.current && !uiState?.isAiStreaming;\n if (streamingFinished && pendingVariantId) {\n setPendingVariantId(null);\n }\n prevStreamingVariant.current = uiState?.isAiStreaming;\n }, [uiState?.isAiStreaming, pendingVariantId]);\n\n const handleStartVariantEdit = (item: any, tierKey: string, variantIndex: number, label: string) => {\n const editId = `variant-${tierKey}-${variantIndex}`;\n if (uiState?.activeEditId && uiState.activeEditId !== editId) {\n uiState?.setPendingEditId?.(uiState.activeEditId);\n return;\n }\n const draft = buildVariantDraft(item);\n setVariantEdit({ id: editId, tierKey, variantIndex, label, original: draft, draft: buildVariantDraft(item) });\n uiState?.setActiveEditId?.(editId);\n uiState?.setPendingEditId?.(null);\n };\n\n const handleCancelVariantEdit = () => {\n setVariantEdit(null);\n uiState?.setActiveEditId?.(null);\n uiState?.setPendingEditId?.(null);\n };\n\n const patchVariantDraft = (patch: Partial<VariantDraft>) => {\n setVariantEdit((prev) => (prev ? { ...prev, draft: { ...prev.draft, ...patch } } : prev));\n };\n\n const editDraftCondition = (key: ConditionKey, id: number | string, text: string) => {\n setVariantEdit((prev) => prev ? {\n ...prev,\n draft: { ...prev.draft, [key]: prev.draft[key].map((c) => (c.id === id ? { ...c, text } : c)) },\n } : prev);\n };\n\n const removeDraftCondition = (key: ConditionKey, id: number | string) => {\n setVariantEdit((prev) => prev ? {\n ...prev,\n draft: { ...prev.draft, [key]: prev.draft[key].filter((c) => c.id !== id) },\n } : prev);\n };\n\n const addDraftCondition = (key: ConditionKey) => {\n setVariantEdit((prev) => prev ? {\n ...prev,\n draft: {\n ...prev.draft,\n [key]: [...prev.draft[key], { id: `draft-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, text: '' }],\n },\n } : prev);\n };\n\n const handleSaveVariantEdit = () => {\n if (!variantEdit) return;\n const { draft, original, id } = variantEdit;\n\n const committed: {\n instructionPrompt?: string;\n ruleDescription?: string;\n whenToApplyText?: string;\n whenNotToApplyText?: string;\n } = {};\n const fields: { action: 'update' | 'remove'; label: string; value: string }[] = [];\n\n const isDescriptionChanged = draft.ruleDescription.trim() !== original.ruleDescription.trim();\n if (isDescriptionChanged) {\n fields.push({ action: 'update', label: 'Description', value: draft.ruleDescription.trim() || 'None' });\n committed.ruleDescription = draft.ruleDescription;\n }\n // The instruction prompt is deliberately NOT echoed into the chat message: it can\n // run to thousands of characters. It is also committed to the store here rather\n // than waiting for an AI write-back, so what the user typed is what the form shows\n // the moment they hit Save.\n const isPromptChanged = draft.instructionPrompt.trim() !== original.instructionPrompt.trim();\n if (isPromptChanged) {\n committed.instructionPrompt = draft.instructionPrompt;\n }\n\n const wtaDiff = diffConditions(original.whenToApplyConditions, draft.whenToApplyConditions);\n const wntaDiff = diffConditions(original.whenNotToApplyConditions, draft.whenNotToApplyConditions);\n\n const wta = conditionsToText(draft.whenToApplyConditions);\n const wnta = conditionsToText(draft.whenNotToApplyConditions);\n const isWtaChanged = wta !== conditionsToText(original.whenToApplyConditions);\n const isWntaChanged = wnta !== conditionsToText(original.whenNotToApplyConditions);\n const conditionsToRawText = (conditions: DraftCondition[]) =>\n conditions\n .filter((c) => hasMeaningfulText(c.text))\n .map((c) => c.text.trim())\n .join(', ');\n if (isWtaChanged) {\n const action = sectionAction(wtaDiff);\n\n fields.push({\n action,\n label: 'When to Apply',\n value:\n action === 'remove'\n ? conditionsToRawText(wtaDiff.removed)\n : wta || 'None',\n });\n\n committed.whenToApplyText = conditionsToStoreText(\n draft.whenToApplyConditions\n );\n }\n\n if (isWntaChanged) {\n const action = sectionAction(wntaDiff);\n\n fields.push({\n action,\n label: 'When Not to Apply',\n value:\n action === 'remove'\n ? conditionsToRawText(wntaDiff.removed)\n : wnta || 'None',\n });\n\n committed.whenNotToApplyText = conditionsToStoreText(\n draft.whenNotToApplyConditions\n );\n }\n\n if (fields.length === 0 && !isPromptChanged) {\n handleCancelVariantEdit();\n return;\n }\n\n // Description/WTA/WNTA are AI-owned, same as the prompt is user-owned — the\n // caller decides how each gets kept visible until the AI's turn resolves\n // (VariantListField mirrors them; CreateRule only cares about the prompt).\n if (Object.keys(committed).length > 0) {\n commitOnSave?.(committed, variantEdit);\n }\n\n if (uiState?.setSendMessageInChat) {\n const skId = `sk-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n uiState.setSendMessageInChat(`__SKELETON__:${skId}:${buildEditMessage(fields, isPromptChanged)}`);\n setPendingVariantId(id);\n }\n\n // Drop the draft — the UI shows the saved values until the AI responds.\n setVariantEdit(null);\n uiState?.setActiveEditId?.(null);\n uiState?.setPendingEditId?.(null);\n };\n\n return {\n variantEdit,\n pendingVariantId,\n handleStartVariantEdit,\n handleCancelVariantEdit,\n patchVariantDraft,\n editDraftCondition,\n removeDraftCondition,\n addDraftCondition,\n handleSaveVariantEdit,\n };\n}\n"],"names":[],"mappings":";;AAea,MAAA,iBAAA,GAAoB,CAAC,IAAyB,KAAA,CAAC,CAAC,IAAQ,IAAA,cAAA,CAAe,KAAK,IAAI,EAAA;AAEhF,MAAA,gBAAA,GAAmB,CAAC,UAAA,KAC/B,UACG,CAAA,MAAA,CAAO,CAAC,CAAA,KAAM,iBAAkB,CAAA,CAAA,CAAE,IAAI,CAAC,CACvC,CAAA,GAAA,CAAI,CAAC,CAAA,EAAG,CAAM,KAAA,CAAA,EAAG,CAAI,GAAA,CAAC,CAAK,EAAA,EAAA,CAAA,CAAE,IAAK,CAAA,IAAA,EAAM,CAAA,CAAE,CAC1C,CAAA,IAAA,CAAK,GAAG,EAAA;AAQA,MAAA,qBAAA,GAAwB,CAAC,UACpC,KAAA,UAAA,CACG,OAAO,CAAC,CAAA,KAAM,kBAAkB,CAAE,CAAA,IAAI,CAAC,CACvC,CAAA,GAAA,CAAI,CAAC,CAAM,KAAA,CAAA,CAAE,KAAK,IAAK,EAAC,CACxB,CAAA,IAAA,CAAK,IAAI,EAAA;AAiBD,MAAA,cAAA,GAAiB,CAAC,QAAA,EAA4B,KAA2C,KAAA;AACpG,EAAM,MAAA,QAAA,GAAW,IAAI,GAAI,CAAA,KAAA,CAAM,IAAI,CAA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AA;AAAA,IACA,gBAAA;AAAA,IACA,sBAAA;AAAA,IACA,uBAAA;AAAA,IACA,iBAAA;AAAA,IACA,kBAAA;AAAA,IACA,oBAAA;AAAA,IACA,iBAAA;AAAA,IACA,qBAAA;AAAA,GACF,CAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"useVariantEditSession.js","sources":["../../../../../src/features/IL-OTJ/_components/hooks/useVariantEditSession.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\n\nexport interface DraftCondition { id: number | string; text: string; reasoning?: string; conflict?: any }\n\nexport interface VariantDraft {\n ruleDescription: string;\n instructionPrompt: string;\n whenToApplyConditions: DraftCondition[];\n whenNotToApplyConditions: DraftCondition[];\n}\n\nexport type ConditionKey = 'whenToApplyConditions' | 'whenNotToApplyConditions';\n\n// A field counts as filled in only when it carries a letter or a digit — spaces and\n// punctuation alone don't qualify.\nexport const hasMeaningfulText = (text?: string | null) => !!text && /[a-z0-9À-]/i.test(text);\n\nexport const conditionsToText = (conditions: DraftCondition[]) =>\n conditions\n .filter((c) => hasMeaningfulText(c.text))\n .map((c, i) => `${i + 1}) ${c.text.trim()}`)\n .join(' ');\n\n// wta/wnta's real store format: one condition per line, no numbering (see\n// splitConditions, which splits on line breaks). The row UI numbers each item\n// itself off its index (ConditionList's `numberIndex`), so baking \"1) \"/\"2) \" into\n// the string here — as conditionsToText does for the chat-summary message — would\n// double it up on screen. Used for the mirage value, which must parse back the\n// same way the real committed string does.\nexport const conditionsToStoreText = (conditions: DraftCondition[]) =>\n conditions\n .filter((c) => hasMeaningfulText(c.text))\n .map((c) => c.text.trim())\n .join('\\n');\n\nexport type ChangeAction = \"add\"|\"update\" | \"remove\";\n\ninterface ChangedField {\n action: ChangeAction;\n label: string;\n previous?: string;\n value: string;\n}\n\n/** Per-condition diff (by id) — needed to tell \"row deleted\" apart from \"row edited\". */\nexport interface ConditionDiff {\n added: DraftCondition[];\n removed: DraftCondition[];\n edited: DraftCondition[];\n}\n\nexport const diffConditions = (original: DraftCondition[], draft: DraftCondition[]): ConditionDiff => {\n const draftIds = new Set(draft.map((c) => c.id));\n const originalIds = new Set(original.map((c) => c.id));\n const removed = original.filter((c) => !draftIds.has(c.id));\n const added = draft.filter((c) => !originalIds.has(c.id) && hasMeaningfulText(c.text));\n const edited = draft.filter((c) => {\n const orig = original.find((o) => o.id === c.id);\n return !!orig && orig.text.trim() !== c.text.trim();\n });\n return { added, removed, edited };\n};\nconst quoteList = (texts: string[]) => texts.map((t) => `\"${t}\"`).join(', ');\nexport const buildConditionChangeFields = (\n sectionLabel: string,\n original: DraftCondition[],\n _draft: DraftCondition[],\n diff: ConditionDiff,\n): ChangedField[] => {\n const removedTexts: string[] = diff.removed\n .filter((c) => hasMeaningfulText(c.text))\n .map((c) => c.text.trim());\n const addedTexts: string[] = diff.added.map((c) => c.text.trim());\n const updates: ChangedField[] = [];\n\n diff.edited.forEach((c) => {\n const orig = original.find((o) => o.id === c.id);\n if (!orig) return;\n const oldText = orig.text.trim();\n const newText = c.text.trim();\n\n if (!hasMeaningfulText(newText)) {\n // edited down to blank = removal\n if (hasMeaningfulText(oldText)) removedTexts.push(oldText);\n } else if (!hasMeaningfulText(oldText)) {\n // was blank, now has text = addition\n addedTexts.push(newText);\n } else {\n updates.push({\n action: 'update',\n label: sectionLabel,\n previous: quoteList([oldText]),\n value: quoteList([newText]),\n });\n }\n });\n\n const fields: ChangedField[] = [];\n if (removedTexts.length) fields.push({ action: 'remove', label: sectionLabel, value: quoteList(removedTexts) });\n if (addedTexts.length) fields.push({ action: 'add', label: sectionLabel, value: quoteList(addedTexts) });\n fields.push(...updates);\n return fields;\n};\n\n/** Chat copy for a saved edit session. Fields are grouped by action so one \"remove\"\n * or \"update details\" prefix covers all fields sharing that action, instead of\n * repeating the verb per field. */\nexport const buildEditMessage = (fields: ChangedField[], isPromptChanged: boolean) => {\n const promptNote = 'I have updated the instruction prompt through RHS';\n if (fields.length === 0) return promptNote;\n\n const parts = fields.map((f) => {\n switch (f.action) {\n case 'remove':\n return `remove ${f.label}: ${f.value}`;\n case 'add':\n return `add ${f.label}: ${f.value}`;\n case 'update':\n return f.previous\n ? `update existing ${f.label}: ${f.previous} with a new ${f.value}`\n : `update details ${f.label} - ${f.value}`;\n }\n });\n\n const base = parts.join('; ');\n return isPromptChanged ? `${base}. Also, ${promptNote.toLowerCase()}` : base;\n};\n\nexport interface VariantEditState {\n id: string;\n tierKey: string;\n variantIndex: number;\n label: string;\n original: VariantDraft;\n draft: VariantDraft;\n}\n\n/**\n * One edit session per variant: the whole variant body (description, prompt,\n * when/when-not to apply) is driven off a local draft, and Save sends ONE\n * combined chat message summarizing every changed field. Shared by CreateRule.tsx\n * (TrafficManager) and VariantListField.tsx (schema-driven) so both templates'\n * `backwardCompatibility === false` behavior stays identical.\n */\nexport function useVariantEditSession(\n uiState: any,\n buildVariantDraft: (item: any) => VariantDraft,\n // Called on Save with whichever fields changed. \n // The instruction prompt is user-owned and expected to be committed to the store right away; description/\n // WTA/WNTA are AI-owned and expected to be mirrored for display only until the\n // AI writes the real values back (see VariantListField's commitVariantEdit).\n // Optional so legacy mounts without a store binding keep working.\n commitOnSave?: (\n committed: {\n instructionPrompt?: string;\n ruleDescription?: string;\n whenToApplyText?: string;\n whenNotToApplyText?: string;\n },\n session: VariantEditState,\n ) => void,\n) {\n const [variantEdit, setVariantEdit] = useState<VariantEditState | null>(null);\n const [pendingVariantId, setPendingVariantId] = useState<string | null>(null);\n const prevStreamingVariant = useRef(uiState?.isAiStreaming);\n\n // Clear the variant \"Validating...\" state once the AI has finished responding.\n useEffect(() => {\n const streamingFinished = prevStreamingVariant.current && !uiState?.isAiStreaming;\n if (streamingFinished && pendingVariantId) {\n setPendingVariantId(null);\n }\n prevStreamingVariant.current = uiState?.isAiStreaming;\n }, [uiState?.isAiStreaming, pendingVariantId]);\n\n const handleStartVariantEdit = (item: any, tierKey: string, variantIndex: number, label: string) => {\n const editId = `variant-${tierKey}-${variantIndex}`;\n if (uiState?.activeEditId && uiState.activeEditId !== editId) {\n uiState?.setPendingEditId?.(uiState.activeEditId);\n return;\n }\n const draft = buildVariantDraft(item);\n setVariantEdit({ id: editId, tierKey, variantIndex, label, original: draft, draft: buildVariantDraft(item) });\n uiState?.setActiveEditId?.(editId);\n uiState?.setPendingEditId?.(null);\n };\n\n const handleCancelVariantEdit = () => {\n setVariantEdit(null);\n uiState?.setActiveEditId?.(null);\n uiState?.setPendingEditId?.(null);\n };\n\n const patchVariantDraft = (patch: Partial<VariantDraft>) => {\n setVariantEdit((prev) => (prev ? { ...prev, draft: { ...prev.draft, ...patch } } : prev));\n };\n\n const editDraftCondition = (key: ConditionKey, id: number | string, text: string) => {\n setVariantEdit((prev) => prev ? {\n ...prev,\n draft: { ...prev.draft, [key]: prev.draft[key].map((c) => (c.id === id ? { ...c, text } : c)) },\n } : prev);\n };\n\n const removeDraftCondition = (key: ConditionKey, id: number | string) => {\n setVariantEdit((prev) => prev ? {\n ...prev,\n draft: { ...prev.draft, [key]: prev.draft[key].filter((c) => c.id !== id) },\n } : prev);\n };\n\n const addDraftCondition = (key: ConditionKey) => {\n setVariantEdit((prev) => prev ? {\n ...prev,\n draft: {\n ...prev.draft,\n [key]: [...prev.draft[key], { id: `draft-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, text: '' }],\n },\n } : prev);\n };\n\n const handleSaveVariantEdit = () => {\n if (!variantEdit) return;\n const { draft, original, id } = variantEdit;\n\n const committed: {\n instructionPrompt?: string;\n ruleDescription?: string;\n whenToApplyText?: string;\n whenNotToApplyText?: string;\n } = {};\n const fields: ChangedField[] = [];\n\n const isDescriptionChanged = draft.ruleDescription.trim() !== original.ruleDescription.trim();\n if (isDescriptionChanged) {\n fields.push({ action: 'update', label: 'Description', value: draft.ruleDescription.trim() || 'None' });\n committed.ruleDescription = draft.ruleDescription;\n }\n // The instruction prompt is deliberately NOT echoed into the chat message: it can\n // run to thousands of characters. It is also committed to the store here rather\n // than waiting for an AI write-back, so what the user typed is what the form shows\n // the moment they hit Save.\n const isPromptChanged = draft.instructionPrompt.trim() !== original.instructionPrompt.trim();\n if (isPromptChanged) {\n committed.instructionPrompt = draft.instructionPrompt;\n }\n\n const wtaDiff = diffConditions(original.whenToApplyConditions, draft.whenToApplyConditions);\n const wntaDiff = diffConditions(original.whenNotToApplyConditions, draft.whenNotToApplyConditions);\n\n const wta = conditionsToText(draft.whenToApplyConditions);\n const wnta = conditionsToText(draft.whenNotToApplyConditions);\n const isWtaChanged = wta !== conditionsToText(original.whenToApplyConditions);\n const isWntaChanged = wnta !== conditionsToText(original.whenNotToApplyConditions);\n if (isWtaChanged) {\n fields.push(...buildConditionChangeFields(\n 'When to Apply', original.whenToApplyConditions, draft.whenToApplyConditions, wtaDiff,\n ));\n committed.whenToApplyText = conditionsToStoreText(draft.whenToApplyConditions);\n }\n if (isWntaChanged) {\n fields.push(...buildConditionChangeFields(\n 'When Not to Apply', original.whenNotToApplyConditions, draft.whenNotToApplyConditions, wntaDiff,\n ));\n committed.whenNotToApplyText = conditionsToStoreText(draft.whenNotToApplyConditions);\n }\n\n if (fields.length === 0 && !isPromptChanged) {\n handleCancelVariantEdit();\n return;\n }\n\n if (fields.length === 0 && !isPromptChanged) {\n handleCancelVariantEdit();\n return;\n }\n\n // Description/WTA/WNTA are AI-owned, same as the prompt is user-owned — the\n // caller decides how each gets kept visible until the AI's turn resolves\n // (VariantListField mirrors them; CreateRule only cares about the prompt).\n if (Object.keys(committed).length > 0) {\n commitOnSave?.(committed, variantEdit);\n }\n\n if (uiState?.setSendMessageInChat) {\n const skId = `sk-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n uiState.setSendMessageInChat(`__SKELETON__:${skId}:${buildEditMessage(fields, isPromptChanged)}`);\n setPendingVariantId(id);\n }\n\n // Drop the draft — the UI shows the saved values until the AI responds.\n setVariantEdit(null);\n uiState?.setActiveEditId?.(null);\n uiState?.setPendingEditId?.(null);\n };\n\n return {\n variantEdit,\n pendingVariantId,\n handleStartVariantEdit,\n handle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xs, Fragment } from 'react/jsx-runtime';
|
|
2
|
+
import { createPortal } from 'react-dom';
|
|
2
3
|
import styles from '../styles/ConfirmationModal.module.css.js';
|
|
3
4
|
|
|
4
5
|
function ConfirmationModal({
|
|
@@ -13,14 +14,14 @@ function ConfirmationModal({
|
|
|
13
14
|
onCancel,
|
|
14
15
|
isLoading = false,
|
|
15
16
|
confirmBgColor = "#EF4444",
|
|
16
|
-
position = "
|
|
17
|
+
position = "fixed"
|
|
17
18
|
}) {
|
|
18
19
|
if (!isOpen) return null;
|
|
19
|
-
|
|
20
|
+
const content = /* @__PURE__ */ jsx(
|
|
20
21
|
"div",
|
|
21
22
|
{
|
|
22
23
|
className: styles.overlay,
|
|
23
|
-
style: { position },
|
|
24
|
+
style: { position, inset: 0, zIndex: 2147483e3 },
|
|
24
25
|
children: /* @__PURE__ */ jsxs("div", { className: styles.modal, children: [
|
|
25
26
|
/* @__PURE__ */ jsx(
|
|
26
27
|
"button",
|
|
@@ -64,6 +65,7 @@ function ConfirmationModal({
|
|
|
64
65
|
] })
|
|
65
66
|
}
|
|
66
67
|
);
|
|
68
|
+
return typeof document !== "undefined" ? createPortal(content, document.body) : content;
|
|
67
69
|
}
|
|
68
70
|
|
|
69
71
|
export { ConfirmationModal as default };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ConfirmationModal.js","sources":["../../../../src/features/LearningManagement/components/ConfirmationModal.tsx"],"sourcesContent":["import React from 'react';\nimport styles from '../styles/ConfirmationModal.module.css';\n\ninterface ModalProps {\n isOpen: boolean;\n title: string;\n description: string | React.ReactNode;\n warning?: string;\n confirmText?: string;\n cancelText?: string;\n loadingText?: string;\n onConfirm: () => void;\n onCancel: () => void;\n isLoading?: boolean;\n confirmBgColor?: string;\n position?: 'absolute' | 'fixed' | 'relative' | 'static' | 'sticky';\n}\n\n/**\n * Reusable ConfirmationModal component with full library compatibility.\n * Removes Tailwind dependencies while incorporating state-driven features.\n */\nexport default function ConfirmationModal({\n isOpen,\n title,\n description,\n warning,\n confirmText = 'Confirm',\n cancelText = 'Cancel',\n loadingText = 'Processing...',\n onConfirm,\n onCancel,\n isLoading = false,\n confirmBgColor = '#EF4444',\n position = '
|
|
1
|
+
{"version":3,"file":"ConfirmationModal.js","sources":["../../../../src/features/LearningManagement/components/ConfirmationModal.tsx"],"sourcesContent":["import React from 'react';\nimport { createPortal } from 'react-dom';\nimport styles from '../styles/ConfirmationModal.module.css';\n\ninterface ModalProps {\n isOpen: boolean;\n title: string;\n description: string | React.ReactNode;\n warning?: string;\n confirmText?: string;\n cancelText?: string;\n loadingText?: string;\n onConfirm: () => void;\n onCancel: () => void;\n isLoading?: boolean;\n confirmBgColor?: string;\n position?: 'absolute' | 'fixed' | 'relative' | 'static' | 'sticky';\n}\n\n/**\n * Reusable ConfirmationModal component with full library compatibility.\n * Removes Tailwind dependencies while incorporating state-driven features.\n */\nexport default function ConfirmationModal({\n isOpen,\n title,\n description,\n warning,\n confirmText = 'Confirm',\n cancelText = 'Cancel',\n loadingText = 'Processing...',\n onConfirm,\n onCancel,\n isLoading = false,\n confirmBgColor = '#EF4444',\n position = 'fixed',\n}: ModalProps): any {\n\n\n if (!isOpen) return null;\n\n const content = (\n <div\n className={styles.overlay}\n style={{ position, inset: 0, zIndex: 2147483000 }}\n >\n <div className={styles.modal}>\n {/* Close button */}\n <button\n onClick={onCancel}\n className={styles.closeBtn}\n style={{ position: 'absolute', right: '1rem', top: '1rem' }}\n disabled={isLoading}\n >\n ✕\n </button>\n\n {/* Content */}\n <div>\n <h2 className={styles.title}>{title}</h2>\n <div className={styles.description}>{description}</div>\n\n {warning && <p className={styles.warning}>{warning}</p>}\n\n {/* Actions */}\n <div className={styles.footer}>\n <button\n onClick={onCancel}\n className={styles.cancelBtn}\n disabled={isLoading}\n >\n {cancelText}\n </button>\n <button\n onClick={onConfirm}\n className={styles.confirmBtn}\n style={{ backgroundColor: confirmBgColor }}\n disabled={isLoading}\n >\n {isLoading ? (\n <>\n <div className={styles.spinner}></div>\n {loadingText}\n </>\n ) : (\n confirmText\n )}\n </button>\n </div>\n </div>\n </div>\n </div>\n );\n\n return typeof document !== 'undefined'\n ? createPortal(content, document.body)\n : content;\n}\n"],"names":[],"mappings":";;;;AAuBA,SAAwB,iBAAkB,CAAA;AAAA,EACxC,MAAA;AAAA,EACA,KAAA;AAAA,EACA,WAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAc,GAAA,SAAA;AAAA,EACd,UAAa,GAAA,QAAA;AAAA,EACb,WAAc,GAAA,eAAA;AAAA,EACd,SAAA;AAAA,EACA,QAAA;AAAA,EACA,SAAY,GAAA,KAAA;AAAA,EACZ,cAAiB,GAAA,SAAA;AAAA,EACjB,QAAW,GAAA,OAAA;AACb,CAAoB,EAAA;AAGlB,EAAI,IAAA,CAAC,QAAe,OAAA,IAAA,CAAA;AAEpB,EAAA,MAAM,OACJ,mBAAA,GAAA;AAAA,IAAC,KAAA;AAAA,IAAA;AAAA,MACC,WAAW,MAAO,CAAA,OAAA;AAAA,MAClB,OAAO,EAAE,QAAA,EAAU,KAAO,EAAA,CAAA,EAAG,QAAQ,SAAW,EAAA;AAAA,MAEhD,QAAC,kBAAA,IAAA,CAAA,KAAA,EAAA,EAAI,SAAW,EAAA,MAAA,CAAO,KAErB,EAAA,QAAA,EAAA;AAAA,wBAAA,GAAA;AAAA,UAAC,QAAA;AAAA,UAAA;AAAA,YACC,OAAS,EAAA,QAAA;AAAA,YACT,WAAW,MAAO,CAAA,QAAA;AAAA,YAClB,OAAO,EAAE,QAAA,EAAU,YAAY,KAAO,EAAA,MAAA,EAAQ,KAAK,MAAO,EAAA;AAAA,YAC1D,QAAU,EAAA,SAAA;AAAA,YACX,QAAA,EAAA,QAAA;AAAA,WAAA;AAAA,SAED;AAAA,6BAGC,KACC,EAAA,EAAA,QAAA,EAAA;AAAA,0BAAA,GAAA,CAAC,IAAG,EAAA,EAAA,SAAA,EAAW,MAAO,CAAA,KAAA,EAAQ,QAAM,EAAA,KAAA,EAA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atus(apiConstants.SUCCESS);
|
|
4149
4149
|
setSavedMessage("Your learning draft has been saved successfully.");
|
|
4150
4150
|
setIsSavedSuccessfully(true);
|
|
4151
|
-
await (
|
|
4151
|
+
await invokePostSave("draft");
|
|
4152
4152
|
handleClose();
|
|
4153
4153
|
} catch (error) {
|
|
4154
4154
|
console.error("[DRAFT FLOW] Failed to save draft:", error);
|
|
@@ -4682,6 +4682,46 @@ const InstantLearningModal = ({
|
|
|
4682
4682
|
tiers: useLearningTemplateStore.getState().tiers,
|
|
4683
4683
|
authToken: (user == null ? void 0 : user.accessToken) || ""
|
|
4684
4684
|
};
|
|
4685
|
+
const formStateBuilderRef = useRef();
|
|
4686
|
+
formStateBuilderRef.current = (mode) => {
|
|
4687
|
+
var _a2, _b2, _c2, _d2;
|
|
4688
|
+
const created = (_a2 = useLearningTemplateStore.getState().createdVariantInfo) != null ? _a2 : [];
|
|
4689
|
+
const tierKeys = scopeData.tiers.map(normalizeTierKey);
|
|
4690
|
+
const clean = (items = []) => items.map((c) => sanitizeConditionText(c.text)).filter(Boolean);
|
|
4691
|
+
const variants = [];
|
|
4692
|
+
tierKeys.forEach((tierKey) => {
|
|
4693
|
+
var _a3, _b3, _c3, _d3;
|
|
4694
|
+
const createdForTier = (_b3 = (_a3 = created.find((c) => c.tierName === tierKey)) == null ? void 0 : _a3.variants) != null ? _b3 : [];
|
|
4695
|
+
Array.from((_d3 = (_c3 = configData.get(tierKey)) == null ? void 0 : _c3.keys()) != null ? _d3 : []).forEach((index, i) => {
|
|
4696
|
+
var _a4, _b4, _c4, _d4, _e2, _f2, _g2, _h2, _i2, _j2, _k2, _l2;
|
|
4697
|
+
const item = (structuredAIResponse || [])[index] || {};
|
|
4698
|
+
const id = (_e2 = (_d4 = (_b4 = (_a4 = editingVariants == null ? void 0 : editingVariants[index]) == null ? void 0 : _a4.variantId) != null ? _b4 : item.variant_id) != null ? _d4 : (_c4 = createdForTier[i]) == null ? void 0 : _c4.id) != null ? _e2 : null;
|
|
4699
|
+
const meta = {
|
|
4700
|
+
...careLearningMetadataByVariant[id != null ? id : ""] || {},
|
|
4701
|
+
...item.learning_metadata || {}
|
|
4702
|
+
};
|
|
4703
|
+
variants.push({
|
|
4704
|
+
variantId: id,
|
|
4705
|
+
tier: tierKey,
|
|
4706
|
+
isDefault: !!((_g2 = (_f2 = configData.get(tierKey)) == null ? void 0 : _f2.get(index)) == null ? void 0 : _g2.is_default_enabled),
|
|
4707
|
+
description: filterText(((_h2 = ruleDescription.get(tierKey)) == null ? void 0 : _h2.get(index)) || ""),
|
|
4708
|
+
whenToApply: clean((_i2 = whenToApplyConditions.get(tierKey)) == null ? void 0 : _i2.get(index)),
|
|
4709
|
+
whenNotToApply: clean((_j2 = whenNotToApplyConditions.get(tierKey)) == null ? void 0 : _j2.get(index)),
|
|
4710
|
+
instructionPrompt: (_l2 = instructionPromptOverrides[(_k2 = getVariantStableKey(item)) != null ? _k2 : `idx-${index}`]) != null ? _l2 : getInstructionPromptValue(meta),
|
|
4711
|
+
learningMetadata: meta,
|
|
4712
|
+
schedulingConfig: pruneFlattenedDuplicates(rawAiConfig)
|
|
4713
|
+
});
|
|
4714
|
+
});
|
|
4715
|
+
});
|
|
4716
|
+
return {
|
|
4717
|
+
mode,
|
|
4718
|
+
questionId: (_c2 = (_b2 = lastLoadedQuestionIdRef.current) != null ? _b2 : editingRule == null ? void 0 : editingRule.ruleId) != null ? _c2 : null,
|
|
4719
|
+
ruleTitle,
|
|
4720
|
+
scope: { ruleSetId: (_d2 = ruleSet == null ? void 0 : ruleSet.ruleSetId) != null ? _d2 : "", station: scopeData.station, tiers: tierKeys },
|
|
4721
|
+
variants,
|
|
4722
|
+
createdVariantInfo: created
|
|
4723
|
+
};
|
|
4724
|
+
};
|
|
4685
4725
|
const nextVariantString = getNextVariantType(existingVariants);
|
|
4686
4726
|
const templateState = {
|
|
4687
4727
|
ruleTitle,
|
|
@@ -4961,7 +5001,8 @@ const InstantLearningModal = ({
|
|
|
4961
5001
|
const handleSaveSuccessAndClose = async () => {
|
|
4962
5002
|
if (postSaveCallback) {
|
|
4963
5003
|
try {
|
|
4964
|
-
|
|
5004
|
+
const mode = resolveIsEditMode({ flow, editingRule, editingVariants }) ? "edit" : "create";
|
|
5005
|
+
await invokePostSave(mode);
|
|
4965
5006
|
} catch (err) {
|
|
4966
5007
|
console.error("postSaveCallback threw after successful save \u2014 keeping modal open", err);
|
|
4967
5008
|
setIsError(true);
|
|
@@ -4973,6 +5014,25 @@ const InstantLearningModal = ({
|
|
|
4973
5014
|
}
|
|
4974
5015
|
handleClose();
|
|
4975
5016
|
};
|
|
5017
|
+
const invokePostSave = async (mode) => {
|
|
5018
|
+
var _a2, _b2;
|
|
5019
|
+
if (!postSaveCallback) return;
|
|
5020
|
+
let formState;
|
|
5021
|
+
try {
|
|
5022
|
+
formState = formStateBuilderRef.current(mode);
|
|
5023
|
+
} catch (e) {
|
|
5024
|
+
console.warn("[TeachMe] Failed to build form state for postSaveCallback", e);
|
|
5025
|
+
formState = {
|
|
5026
|
+
mode,
|
|
5027
|
+
questionId: (_a2 = lastLoadedQuestionIdRef.current) != null ? _a2 : null,
|
|
5028
|
+
ruleTitle,
|
|
5029
|
+
scope: { ruleSetId: (_b2 = ruleSet == null ? void 0 : ruleSet.ruleSetId) != null ? _b2 : "", station: scopeData.station, tiers: [] },
|
|
5030
|
+
variants: [],
|
|
5031
|
+
createdVariantInfo: []
|
|
5032
|
+
};
|
|
5033
|
+
}
|
|
5034
|
+
await postSaveCallback(formState);
|
|
5035
|
+
};
|
|
4976
5036
|
const hasConflictingConditions = () => {
|
|
4977
5037
|
const checkMap = (map) => {
|
|
4978
5038
|
return Array.from(map.values()).some(
|