@dawntech/dwntbots-services 0.0.90 → 0.0.92
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/package.json +14 -9
- package/src/lib/blip/BlipBuilder/BlipBuilderTranspilation.js +4 -2
- package/src/lib/blip/BlipBuilder/BlipBuilderTranspilation.js.map +1 -1
- package/src/lib/blip/BlipBuilder/features/Feature.js.map +1 -1
- package/src/lib/blip/BlipBuilder/features/InactivityFeature.js +1 -1
- package/src/lib/blip/BlipBuilder/features/InactivityFeature.js.map +1 -1
- package/src/lib/blip/BlipBuilder/features/PositionFeature.js +2 -2
- package/src/lib/blip/BlipBuilder/features/PositionFeature.js.map +1 -1
- package/src/lib/blip/BlipBuilder/features/SDKFeature.js +12 -9
- package/src/lib/blip/BlipBuilder/features/SDKFeature.js.map +1 -1
- package/src/lib/blip/BlipBuilder/features/actions/entrypoint.js +1 -1
- package/src/lib/blip/BlipBuilder/features/actions/entrypoint.js.map +1 -1
- package/src/lib/blip/BlipBuilder/features/actions/fallback.d.ts +2 -2
- package/src/lib/blip/BlipBuilder/features/actions/fallback.js +12 -25
- package/src/lib/blip/BlipBuilder/features/actions/fallback.js.map +1 -1
- package/src/lib/blip/BlipBuilder/features/actions/global.d.ts +1 -1
- package/src/lib/blip/BlipBuilder/features/actions/global.js +9 -17
- package/src/lib/blip/BlipBuilder/features/actions/global.js.map +1 -1
- package/src/lib/blip/BlipBuilder/features/actions/onboarding.js +1 -1
- package/src/lib/blip/BlipBuilder/features/actions/onboarding.js.map +1 -1
- package/src/lib/blip/BlipBuilder/index.d.ts +3 -3
- package/src/lib/blip/BlipBuilder/index.js +2 -3
- package/src/lib/blip/BlipBuilder/index.js.map +1 -1
- package/src/lib/blip/BlipBuilder/models/_base.js +3 -3
- package/src/lib/blip/BlipBuilder/models/_base.js.map +1 -1
- package/src/lib/blip/BlipBuilder/models/base.js +3 -3
- package/src/lib/blip/BlipBuilder/models/base.js.map +1 -1
- package/src/lib/blip/BlipBuilder/models/navigation.js.map +1 -1
- package/src/lib/blip/BlipBuilder/models/tags.js +1 -1
- package/src/lib/blip/BlipBuilder/models/tags.js.map +1 -1
- package/src/lib/blip/BlipBuilder/utils.d.ts +1 -1
- package/src/lib/blip/BlipBuilder/utils.js.map +1 -1
- package/src/lib/blip/BlipService.d.ts +21 -4
- package/src/lib/blip/BlipService.js +161 -22
- package/src/lib/blip/BlipService.js.map +1 -1
- package/src/lib/blip/BlipTransport.d.ts +1 -0
- package/src/lib/blip/BlipTransport.js +16 -4
- package/src/lib/blip/BlipTransport.js.map +1 -1
- package/src/lib/blip/{BlipBuilder/BlipBotDiff.d.ts → BotDiff/BotDiff.d.ts} +24 -11
- package/src/lib/blip/{BlipBuilder/BlipBotDiff.js → BotDiff/BotDiff.js} +57 -23
- package/src/lib/blip/BotDiff/BotDiff.js.map +1 -0
- package/src/lib/blip/BotDiff/index.d.ts +2 -0
- package/src/lib/blip/BotDiff/index.js +8 -0
- package/src/lib/blip/BotDiff/index.js.map +1 -0
- package/src/lib/blip/{BlipBuilder → BuilderSanitize}/BlipBuilderSanitize.d.ts +1 -0
- package/src/lib/blip/{BlipBuilder → BuilderSanitize}/BlipBuilderSanitize.js +16 -10
- package/src/lib/blip/BuilderSanitize/BlipBuilderSanitize.js.map +1 -0
- package/src/lib/blip/BuilderSanitize/index.d.ts +1 -0
- package/src/lib/blip/BuilderSanitize/index.js +18 -0
- package/src/lib/blip/BuilderSanitize/index.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/BlipBuilder.d.ts +96 -0
- package/src/lib/blip/DwnGridCompiler/BlipBuilder.js +443 -0
- package/src/lib/blip/DwnGridCompiler/BlipBuilder.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/DwnGridCompiler.d.ts +61 -0
- package/src/lib/blip/DwnGridCompiler/DwnGridCompiler.js +255 -0
- package/src/lib/blip/DwnGridCompiler/DwnGridCompiler.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/ExecutionLogger.d.ts +24 -0
- package/src/lib/blip/DwnGridCompiler/ExecutionLogger.js +48 -0
- package/src/lib/blip/DwnGridCompiler/ExecutionLogger.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/CoreFeature.d.ts +65 -0
- package/src/lib/blip/DwnGridCompiler/features/CoreFeature.js +408 -0
- package/src/lib/blip/DwnGridCompiler/features/CoreFeature.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/Feature.d.ts +149 -0
- package/src/lib/blip/DwnGridCompiler/features/Feature.js +160 -0
- package/src/lib/blip/DwnGridCompiler/features/Feature.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/InactivityFeature.d.ts +13 -0
- package/src/lib/blip/DwnGridCompiler/features/InactivityFeature.js +56 -0
- package/src/lib/blip/DwnGridCompiler/features/InactivityFeature.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/LinterFeature.d.ts +38 -0
- package/src/lib/blip/DwnGridCompiler/features/LinterFeature.js +77 -0
- package/src/lib/blip/DwnGridCompiler/features/LinterFeature.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/ScriptsFeature.d.ts +14 -0
- package/src/lib/blip/DwnGridCompiler/features/ScriptsFeature.js +46 -0
- package/src/lib/blip/DwnGridCompiler/features/ScriptsFeature.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/TagsFeature.d.ts +30 -0
- package/src/lib/blip/DwnGridCompiler/features/TagsFeature.js +221 -0
- package/src/lib/blip/DwnGridCompiler/features/TagsFeature.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/TemplatesFeature.d.ts +14 -0
- package/src/lib/blip/DwnGridCompiler/features/TemplatesFeature.js +31 -0
- package/src/lib/blip/DwnGridCompiler/features/TemplatesFeature.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/conditions.d.ts +2 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/conditions.js +45 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/conditions.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/contact.d.ts +5 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/contact.js +112 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/contact.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/content.d.ts +7 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/content.js +183 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/content.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/events.d.ts +21 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/events.js +827 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/events.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/redirect.d.ts +3 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/redirect.js +77 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/redirect.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/scripts.d.ts +14 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/scripts.js +292 -0
- package/src/lib/blip/DwnGridCompiler/features/entities/scripts.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/index.d.ts +8 -0
- package/src/lib/blip/DwnGridCompiler/features/index.js +67 -0
- package/src/lib/blip/DwnGridCompiler/features/index.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/__definitions.d.ts +830 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/__definitions.js +364 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/__definitions.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/__scripts.template.d.ts +14 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/__scripts.template.js +292 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/__scripts.template.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/_bindings.d.ts +24 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/_bindings.js +25 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/_bindings.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/_build.d.ts +2 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/_build.js +8 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/_build.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/_types.d.ts +14 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/_types.js +3 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/_types.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_error_message.d.ts +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_error_message.js +46 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_error_message.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_fallback_create.d.ts +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_fallback_create.js +178 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_fallback_create.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_fallback_process.d.ts +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_fallback_process.js +225 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_fallback_process.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_gactions_config_pt_br.d.ts +19 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_gactions_config_pt_br.js +165 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_gactions_config_pt_br.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_gactions_core.d.ts +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_gactions_core.js +411 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_gactions_core.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_gactions_dwn.d.ts +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_gactions_dwn.js +1195 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_gactions_dwn.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_onboarding_reset.d.ts +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_onboarding_reset.js +109 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/grid_onboarding_reset.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_console.d.ts +29 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_console.js +61 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_console.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_datetime.d.ts +5 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_datetime.js +24 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_datetime.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_enforcesate.d.ts +2 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_enforcesate.js +28 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_enforcesate.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_http.d.ts +139 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_http.js +270 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_http.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_kebabcase.d.ts +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_kebabcase.js +16 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_kebabcase.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_merge.d.ts +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_merge.js +64 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_merge.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_script.d.ts +2 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_script.js +148 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/libs_script.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/template_intent.d.ts +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/template_intent.js +148 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/template_intent.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/template_prepare.d.ts +33 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/template_prepare.js +165 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/template_prepare.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/template_script_basic.d.ts +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/template_script_basic.js +31 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/template_script_basic.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/template_script_complete.d.ts +1 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/template_script_complete.js +31 -0
- package/src/lib/blip/DwnGridCompiler/features/scripts/template_script_complete.js.map +1 -0
- package/src/lib/blip/DwnGridCompiler/index.d.ts +1 -0
- package/src/lib/blip/DwnGridCompiler/index.js +18 -0
- package/src/lib/blip/DwnGridCompiler/index.js.map +1 -0
- package/src/lib/blip/WhatsAppBlipService.js +0 -2
- package/src/lib/blip/WhatsAppBlipService.js.map +1 -1
- package/src/lib/new-relic/NewRelicIngest.d.ts +17 -4
- package/src/lib/new-relic/NewRelicIngest.js +2 -0
- package/src/lib/new-relic/NewRelicIngest.js.map +1 -1
- package/src/lib/storage/Driver.js +1 -1
- package/src/lib/storage/Driver.js.map +1 -1
- package/src/lib/storage/ScopedStorage.js.map +1 -1
- package/src/lib/whatsapp-flow/index.js.map +1 -1
- package/src/lib/blip/BlipBuilder/BlipBotDiff.js.map +0 -1
- package/src/lib/blip/BlipBuilder/BlipBuilderSanitize.js.map +0 -1
- package/src/lib/blip/BlipBuilder/BlipBuilderTranspile.d.ts +0 -49
- package/src/lib/blip/BlipBuilder/BlipBuilderTranspile.js +0 -317
- package/src/lib/blip/BlipBuilder/BlipBuilderTranspile.js.map +0 -1
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.intentScriptTemplate = exports.completeScriptTemplate = exports.basicScriptTemplate = exports.prepareScriptTemplate = exports.errorMessageScript = exports.processErrorScript = exports.createErrorScript = exports.updateStatesScript = exports.updateDwnScript = exports.updateCoreScript = exports.configScript = exports.resetDwnScript = void 0;
|
|
4
|
+
const Feature_1 = require("../Feature");
|
|
5
|
+
const resetDwnScript = ($id) => {
|
|
6
|
+
const source = '\nvar RESET_CONFIG = {\n journey: true,\n errors: true,\n checkpoints: true,\n intents: true,\n services: true,\n visits: true,\n group: true\n};\nvar ONLY_ON_MAIN = true;\nasync function dwnRun(coreStr, configStr, errorStr) {\n coreStr = coreStr || "";\n configStr = configStr || "";\n errorStr = errorStr || "";\n let core = null;\n let config = null;\n let error = DwnError.fromDwnError(errorStr);\n try {\n core = JSON.parse(coreStr || "{}");\n if (error) {\n throw error;\n }\n try {\n config = JSON.parse(configStr || "");\n } catch (err) {\n throw new Error(`config parsing ${String(err)}`);\n }\n const IS_MAIN = config.service.current === config.service.main;\n const allow = ONLY_ON_MAIN ? IS_MAIN : true;\n if (allow && RESET_CONFIG.journey) {\n core.journey = "{{random.guid}}";\n core.sessions = (core.sessions || 0) + 1;\n }\n if (allow && RESET_CONFIG.errors) {\n core.errors = [];\n }\n if (allow && RESET_CONFIG.checkpoints) {\n core.checkpoints = [];\n }\n if (allow && RESET_CONFIG.intents) {\n core.intents = { stack: [], groups: [] };\n }\n if (allow && RESET_CONFIG.services) {\n core.services = [];\n }\n if (allow && RESET_CONFIG.group) {\n const GROUP_SEED_RESOLUTION = 1e7;\n let groups = config.groups || [];\n let sum = groups.reduce((acc, val) => acc + val, 0);\n let seed = Math.floor(Math.random() * GROUP_SEED_RESOLUTION);\n const groupIndex = groups.findIndex((val) => {\n seed -= val * GROUP_SEED_RESOLUTION / sum;\n return seed < 0;\n });\n const group = groupIndex === -1 ? 0 : groupIndex;\n core.group = String.fromCharCode(65 + group);\n }\n if (allow && RESET_CONFIG.visits) {\n core.visits = [];\n }\n if (IS_MAIN) {\n core.warnings = [];\n }\n } catch (err) {\n if (!(err instanceof DwnError)) {\n const description = `[entrypoint-core] Unexpected error ${String(err)}`;\n const stack = err.stack || "";\n err = new DwnError("RUNTIME_ERROR", description, {\n stack,\n goto: null\n });\n }\n error = err;\n } finally {\n if (!core || typeof core !== "object") {\n core = null;\n }\n coreStr = JSON.stringify(core);\n }\n if (error && error.toString() !== errorStr) {\n await context.setVariableAsync("dwnError", error.toString());\n }\n return coreStr;\n}\n/**\n * @imports\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n */\nvar DwnError = class _DwnError extends Error {\n /**\n * Creates a new DwnError instance.\n *\n * @param {string} type The error type identifier (e.g., "VALIDATION_ERROR", "SCRIPT_ERROR")\n * @param {string} description Human-readable description of what went wrong\n * @param {{message?: string, messages?: string[], stack?: string, goto?: State | null, state?: State, at?: string, intent?: string | null, content?: string, recurrence?: ErrorRecurrence, code?: string | null, status?: FINALIZATION_STATUS}} [extras] Optional additional error context and metadata:\n * - `message`: Primary error message for user display\n * - `messages`: Array of error messages for different contexts\n * - `stack`: Stack trace or execution context information\n * - `goto`: Target state to redirect to on error (null means terminate)\n * - `state`: Flow state where the error occurred\n * - `at`: Location or context where the error occurred\n * - `intent`: Associated intent that caused the error\n * - `content`: Additional error content or context\n * - `recurrence`: Information about error recurrence patterns\n * - `code`: Error code for programmatic error handling\n * - `status`: Finalization status indicating how the error was resolved\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid input provided");\n *\n * const contextError = new DwnError("SCRIPT_ERROR", "Script execution failed", {\n * state: { id: "state-123", service: "main" },\n * intent: "user-input",\n * content: "invalid data",\n * messages: ["First attempt failed", "Retry failed"],\n * goto: { id: "error-handler", service: "main" }\n * });\n * ```\n */\n constructor(type, description, extras) {\n super();\n this.name = "DwnError";\n const _extras = _DwnError.enforceExtras(extras);\n this.type = type;\n this.description = description;\n this.at = _extras.at;\n this.content = _extras.content;\n this.state = _extras.state;\n this.recurrence = _extras.recurrence;\n this.goto = _extras.goto;\n this.message = _extras.message || undefined;\n this.messages = _extras.messages || [];\n this.intent = _extras.intent || undefined;\n this.code = _extras.code || undefined;\n this.status = _extras.status || undefined;\n this.stack = _extras.stack || undefined;\n if (!this.stack) {\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, _DwnError);\n }\n }\n }\n /**\n * Creates a DwnError instance from a serialized error string.\n *\n * Parses a DWN error string in the format "TYPE -|- DESCRIPTION -|- EXTRAS_JSON"\n * and reconstructs the original DwnError instance.\n *\n * @param {string} dwnErrorString Serialized error string from toString() method\n * @returns {DwnError | undefined} DwnError instance or undefined if parsing fails\n *\n * @example\n * ```typescript\n * const errorString = "SCRIPT_ERROR -|- Execution failed -|- {...}";\n * const error = DwnError.fromDwnError(errorString);\n * ```\n */\n static fromDwnError(dwnErrorString) {\n if (!dwnErrorString) return undefined;\n const parts = dwnErrorString.split("-|-");\n let type = parts.shift();\n if (!type) {\n return undefined;\n }\n type = type.trim();\n let description = parts.shift() || "";\n if (description) {\n description = description.trim();\n }\n let extras = undefined;\n try {\n extras = JSON.parse(parts.shift() || "{}");\n } catch (e) {\n }\n if (extras) {\n return new _DwnError(type, description, extras);\n }\n return new _DwnError(type, description);\n }\n /**\n * Creates a DwnError instance from a JSON object.\n *\n * Converts a generic Error object or JSON representation into a properly\n * structured DwnError instance with all required properties.\n *\n * @param {Error} data Error object or JSON data to convert\n * @returns {DwnError} New DwnError instance\n *\n * @example\n * ```typescript\n * const jsonData = { type: "API_ERROR", description: "Request failed" };\n * const error = DwnError.fromJson(jsonData);\n * ```\n */\n static fromJson(data) {\n const extras = _DwnError.enforceExtras(data);\n return new _DwnError(data.type, data.description, extras);\n }\n /**\n * Normalizes and validates error extras properties.\n *\n * Ensures all optional properties have default values and validates the structure\n * of the extras object. Used internally to maintain consistency across error instances.\n *\n * @param {DwnError | DwnErrorExtras} [entity] Error entity or extras object to normalize\n * @returns {Required<DwnErrorExtras>} Normalized extras object with all required properties\n *\n * @internal\n */\n static enforceExtras(entity) {\n if (!entity) entity = {};\n const extras = {};\n extras.message = entity.message || "";\n extras.messages = entity.messages || [];\n extras.stack = entity.stack || "";\n extras.goto = entity.goto;\n extras.state = entity.state || { id: "", service: "" };\n extras.at = entity.at || (new Date()).toISOString();\n extras.intent = entity.intent || "";\n extras.content = entity.content || "";\n extras.recurrence = entity.recurrence || { type: 1, state: 1, combined: 1 };\n extras.code = entity.code || undefined;\n extras.status = entity.status || undefined;\n return extras;\n }\n /**\n * Serializes the error to a string format.\n *\n * Converts the DwnError instance into a parseable string format using the pattern\n * "TYPE -|- DESCRIPTION -|- EXTRAS_JSON" for storage or transmission.\n *\n * @returns {string} Serialized error string\n *\n * @example\n * ```typescript\n * const error = new DwnError("API_ERROR", "Request failed");\n * const serialized = error.toString();\n * // "API_ERROR -|- Request failed -|- {...}"\n * ```\n */\n toString() {\n const extras = JSON.stringify(_DwnError.enforceExtras(this));\n return `${this.type} -|- ${this.description} -|- ${extras}`;\n }\n /**\n * Converts the error to a JSON object.\n *\n * Serializes all error properties into a plain JavaScript object suitable\n * for JSON serialization, API responses, or logging.\n *\n * @returns {Error} Plain object representation of the error\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid data");\n * const json = error.toJson();\n * console.log(JSON.stringify(json, null, 2));\n * ```\n */\n toJson() {\n return {\n type: this.type,\n at: this.at,\n description: this.description,\n message: this.message,\n messages: this.messages || [],\n stack: this.stack || "",\n intent: this.intent,\n content: this.content,\n goto: this.goto,\n state: this.state,\n recurrence: this.recurrence\n };\n }\n};\nvar SYSTEM_DWN_ERRORS = [\n "RUNTIME_ERROR",\n "MISCONFIGURATION_ERROR"\n];\n';
|
|
7
|
+
return {
|
|
8
|
+
$id,
|
|
9
|
+
$typeOfContent: "",
|
|
10
|
+
type: "ExecuteScriptV2",
|
|
11
|
+
$title: "DWN [SETTINGS] Reset",
|
|
12
|
+
settings: {
|
|
13
|
+
function: "dwnRun",
|
|
14
|
+
source,
|
|
15
|
+
inputVariables: [
|
|
16
|
+
Feature_1.Feature.VARIABLES.CORE,
|
|
17
|
+
Feature_1.Feature.VARIABLES.CONFIG,
|
|
18
|
+
Feature_1.Feature.VARIABLES.ERROR,
|
|
19
|
+
],
|
|
20
|
+
outputVariable: Feature_1.Feature.VARIABLES.CORE,
|
|
21
|
+
},
|
|
22
|
+
conditions: [],
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
exports.resetDwnScript = resetDwnScript;
|
|
26
|
+
const configScript = ($id, language) => {
|
|
27
|
+
const source = {
|
|
28
|
+
pt_br: '\nvar DEFAULT_LIST = {\n block: false,\n allow: false\n};\nvar DEFAULT_THRESHOLD = {\n minScore: 0.75,\n maxStack: 3\n};\nvar DEFAULT_DISABLE = {\n inactivity: false,\n intents: []\n};\nvar DEFAULT_STACK_SIZES = {\n requests: 3,\n logs: 10,\n intents: 3,\n errors: 5,\n checkpoints: 5\n};\nvar DEFAULT_GLOBAL_INTENTS = [\n {\n id: "CLOSE",\n label: "Sair",\n type: "regex",\n patterns: ["sair", "encerrar"],\n goto: null\n },\n {\n id: "CHECKPOINT_BACK",\n label: "Voltar",\n type: "regex",\n patterns: ["voltar"]\n }\n];\nvar DEFAULT_GREETING = {\n ["MORNING"]: "Bom dia",\n ["AFTERNOON"]: "Boa tarde",\n ["EVENING"]: "Boa noite",\n ["NIGHT"]: "Boa noite"\n};\nvar DEFAULT_ERROR_MESSAGES = {\n ["UNEXPECTED_INPUT"]: [\n "Desculpe, não consegui entender.\\n\\n<b>Escolha uma opção do menu ou tente com outras palavras,</b> por favor.",\n "Não entendi o que você quis dizer.\\n\\n<b>Poderia tentar novamente?</b>"\n ],\n ["UNEXPECTED_OPTION"]: [\n "Não entendi sua mensagem, desculpe...\\n\\n<b>Confira as opções do menu e escolha uma,</b> por favor.",\n "Essa não é uma das opções...\\n\\n<b>Confira as opções do menu e escolha uma,</b> por favor."\n ],\n ["INACTIVITY"]: [\n //"Já faz uns minutinhos desde a sua última mensagem...",\n "Faz um tempo que você não envia mensagens...\\n\\n<b>Vou encerrar a conversa, mas é só enviar um “Oi” para retomar!</b>"\n ],\n ["HTTP_ERROR"]: [\n "Desculpe, meu sistema está indisponível agora...\\n\\n<b>Por favor, tente novamente mais tarde.</b>"\n ],\n ["SCRIPT_ERROR"]: [\n "Desculpe, não consigo te ajudar nesse momento...\\n\\n<b>Por favor, tente novamente mais tarde.</b>"\n ],\n ["RECURRENT_ERROR"]: [\n "Ainda não estou conseguindo te entender...\\n\\n<i>ℹ️ Caso esteja com dificuldades no WhatsApp, busque nossos outros canais de atendimento.</i>\\n\\n<b>Seu atendimento será encerrado, mas você pode reiniciar a qualquer momento mandando um “oi”.</b>"\n ]\n};\nvar DEFAULT_TYPE_MESSAGES = {\n ["AUDIO"]: [\n "Não consigo ouvir áudios agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ouvir áudios agora! 🔈🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["VIDEO"]: [\n "Não consigo ver vídeos agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver vídeos agora... 🎥🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["IMAGE"]: [\n "Não consigo ver imagens agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver imagens agora... 🖼🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["STICKER"]: [\n "Não consigo ver figurinhas...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver figurinhas... 🖼🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["DOCUMENT"]: [\n "Não consigo ver arquivos agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver arquivos agora... 📄🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["LOCATION"]: [\n "Não consigo ver a localização agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver a localização agora... 📍🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ]\n};\nvar DEFAULT_INTENT_MESSAGES = {\n ["CLOSE"]: [\n "Obrigado por nos contatar! 😊 Se precisar de mais ajuda, não hesite em nos procurar novamente."\n ]\n};\nvar DEFAULT_ERROR = {\n type: "UNEXPECTED_INPUT"\n};\nvar DEFAULT_DAYPARTS = {\n ["MORNING"]: [6, 7, 8, 9, 10, 11],\n ["AFTERNOON"]: [12, 13, 14, 15, 16, 17],\n ["EVENING"]: [18, 19, 20, 21],\n ["NIGHT"]: [22, 23, 0, 1, 2, 3, 4, 5]\n};\nvar DEFAULT_LABEL = {\n ["UNEXPECTED"]: "Inesperado",\n ["ABANDONED"]: "Abandonado",\n ["RESOLVED"]: "Finalizado",\n ["ERROR"]: "Erro"\n};\nvar DEFAULT_INACTIVITY = "INACTIVITY";\nvar DEFAULT_PASSWORD = "admin";\nvar DEFAULT_PROPAGATE = null;\nvar DEFAULT_CONTACT_GROUPS = [1];\nvar DEFAULT_DEBUG = false;\nvar config = {\n list: DEFAULT_LIST,\n threshold: DEFAULT_THRESHOLD,\n stackSize: DEFAULT_STACK_SIZES,\n intents: DEFAULT_GLOBAL_INTENTS,\n disabled: DEFAULT_DISABLE,\n messages: {\n error: DEFAULT_ERROR_MESSAGES,\n type: DEFAULT_TYPE_MESSAGES,\n greeting: DEFAULT_GREETING,\n intent: DEFAULT_INTENT_MESSAGES\n },\n daypart: DEFAULT_DAYPARTS,\n error: DEFAULT_ERROR,\n label: DEFAULT_LABEL,\n password: DEFAULT_PASSWORD,\n propagate: DEFAULT_PROPAGATE,\n groups: DEFAULT_CONTACT_GROUPS,\n debug: DEFAULT_DEBUG\n};\nasync function dwnRun(stateId) {\n if (stateId && stateId.startsWith("desk:")) {\n await context.setVariableAsync("dwnBypass", "true");\n } else {\n await context.deleteVariableAsync("dwnBypass");\n }\n return JSON.stringify(config);\n}\n/**\n * @imports\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n */\nvar DwnError = class _DwnError extends Error {\n /**\n * Creates a new DwnError instance.\n *\n * @param {string} type The error type identifier (e.g., "VALIDATION_ERROR", "SCRIPT_ERROR")\n * @param {string} description Human-readable description of what went wrong\n * @param {{message?: string, messages?: string[], stack?: string, goto?: State | null, state?: State, at?: string, intent?: string | null, content?: string, recurrence?: ErrorRecurrence, code?: string | null, status?: FINALIZATION_STATUS}} [extras] Optional additional error context and metadata:\n * - `message`: Primary error message for user display\n * - `messages`: Array of error messages for different contexts\n * - `stack`: Stack trace or execution context information\n * - `goto`: Target state to redirect to on error (null means terminate)\n * - `state`: Flow state where the error occurred\n * - `at`: Location or context where the error occurred\n * - `intent`: Associated intent that caused the error\n * - `content`: Additional error content or context\n * - `recurrence`: Information about error recurrence patterns\n * - `code`: Error code for programmatic error handling\n * - `status`: Finalization status indicating how the error was resolved\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid input provided");\n *\n * const contextError = new DwnError("SCRIPT_ERROR", "Script execution failed", {\n * state: { id: "state-123", service: "main" },\n * intent: "user-input",\n * content: "invalid data",\n * messages: ["First attempt failed", "Retry failed"],\n * goto: { id: "error-handler", service: "main" }\n * });\n * ```\n */\n constructor(type, description, extras) {\n super();\n this.name = "DwnError";\n const _extras = _DwnError.enforceExtras(extras);\n this.type = type;\n this.description = description;\n this.at = _extras.at;\n this.content = _extras.content;\n this.state = _extras.state;\n this.recurrence = _extras.recurrence;\n this.goto = _extras.goto;\n this.message = _extras.message || undefined;\n this.messages = _extras.messages || [];\n this.intent = _extras.intent || undefined;\n this.code = _extras.code || undefined;\n this.status = _extras.status || undefined;\n this.stack = _extras.stack || undefined;\n if (!this.stack) {\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, _DwnError);\n }\n }\n }\n /**\n * Creates a DwnError instance from a serialized error string.\n *\n * Parses a DWN error string in the format "TYPE -|- DESCRIPTION -|- EXTRAS_JSON"\n * and reconstructs the original DwnError instance.\n *\n * @param {string} dwnErrorString Serialized error string from toString() method\n * @returns {DwnError | undefined} DwnError instance or undefined if parsing fails\n *\n * @example\n * ```typescript\n * const errorString = "SCRIPT_ERROR -|- Execution failed -|- {...}";\n * const error = DwnError.fromDwnError(errorString);\n * ```\n */\n static fromDwnError(dwnErrorString) {\n if (!dwnErrorString) return undefined;\n const parts = dwnErrorString.split("-|-");\n let type = parts.shift();\n if (!type) {\n return undefined;\n }\n type = type.trim();\n let description = parts.shift() || "";\n if (description) {\n description = description.trim();\n }\n let extras = undefined;\n try {\n extras = JSON.parse(parts.shift() || "{}");\n } catch (e) {\n }\n if (extras) {\n return new _DwnError(type, description, extras);\n }\n return new _DwnError(type, description);\n }\n /**\n * Creates a DwnError instance from a JSON object.\n *\n * Converts a generic Error object or JSON representation into a properly\n * structured DwnError instance with all required properties.\n *\n * @param {Error} data Error object or JSON data to convert\n * @returns {DwnError} New DwnError instance\n *\n * @example\n * ```typescript\n * const jsonData = { type: "API_ERROR", description: "Request failed" };\n * const error = DwnError.fromJson(jsonData);\n * ```\n */\n static fromJson(data) {\n const extras = _DwnError.enforceExtras(data);\n return new _DwnError(data.type, data.description, extras);\n }\n /**\n * Normalizes and validates error extras properties.\n *\n * Ensures all optional properties have default values and validates the structure\n * of the extras object. Used internally to maintain consistency across error instances.\n *\n * @param {DwnError | DwnErrorExtras} [entity] Error entity or extras object to normalize\n * @returns {Required<DwnErrorExtras>} Normalized extras object with all required properties\n *\n * @internal\n */\n static enforceExtras(entity) {\n if (!entity) entity = {};\n const extras = {};\n extras.message = entity.message || "";\n extras.messages = entity.messages || [];\n extras.stack = entity.stack || "";\n extras.goto = entity.goto;\n extras.state = entity.state || { id: "", service: "" };\n extras.at = entity.at || (new Date()).toISOString();\n extras.intent = entity.intent || "";\n extras.content = entity.content || "";\n extras.recurrence = entity.recurrence || { type: 1, state: 1, combined: 1 };\n extras.code = entity.code || undefined;\n extras.status = entity.status || undefined;\n return extras;\n }\n /**\n * Serializes the error to a string format.\n *\n * Converts the DwnError instance into a parseable string format using the pattern\n * "TYPE -|- DESCRIPTION -|- EXTRAS_JSON" for storage or transmission.\n *\n * @returns {string} Serialized error string\n *\n * @example\n * ```typescript\n * const error = new DwnError("API_ERROR", "Request failed");\n * const serialized = error.toString();\n * // "API_ERROR -|- Request failed -|- {...}"\n * ```\n */\n toString() {\n const extras = JSON.stringify(_DwnError.enforceExtras(this));\n return `${this.type} -|- ${this.description} -|- ${extras}`;\n }\n /**\n * Converts the error to a JSON object.\n *\n * Serializes all error properties into a plain JavaScript object suitable\n * for JSON serialization, API responses, or logging.\n *\n * @returns {Error} Plain object representation of the error\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid data");\n * const json = error.toJson();\n * console.log(JSON.stringify(json, null, 2));\n * ```\n */\n toJson() {\n return {\n type: this.type,\n at: this.at,\n description: this.description,\n message: this.message,\n messages: this.messages || [],\n stack: this.stack || "",\n intent: this.intent,\n content: this.content,\n goto: this.goto,\n state: this.state,\n recurrence: this.recurrence\n };\n }\n};\nvar SYSTEM_DWN_ERRORS = [\n "RUNTIME_ERROR",\n "MISCONFIGURATION_ERROR"\n];\n',
|
|
29
|
+
es: '\nvar DEFAULT_LIST = {\n block: false,\n allow: false\n};\nvar DEFAULT_THRESHOLD = {\n minScore: 0.75,\n maxStack: 3\n};\nvar DEFAULT_DISABLE = {\n inactivity: false,\n intents: []\n};\nvar DEFAULT_STACK_SIZES = {\n requests: 3,\n logs: 10,\n intents: 3,\n errors: 5,\n checkpoints: 5\n};\nvar DEFAULT_GLOBAL_INTENTS = [\n {\n id: "CLOSE",\n label: "Sair",\n type: "regex",\n patterns: ["sair", "encerrar"],\n goto: null\n },\n {\n id: "CHECKPOINT_BACK",\n label: "Voltar",\n type: "regex",\n patterns: ["voltar"]\n }\n];\nvar DEFAULT_GREETING = {\n ["MORNING"]: "Bom dia",\n ["AFTERNOON"]: "Boa tarde",\n ["EVENING"]: "Boa noite",\n ["NIGHT"]: "Boa noite"\n};\nvar DEFAULT_ERROR_MESSAGES = {\n ["UNEXPECTED_INPUT"]: [\n "Desculpe, não consegui entender.\\n\\n<b>Escolha uma opção do menu ou tente com outras palavras,</b> por favor.",\n "Não entendi o que você quis dizer.\\n\\n<b>Poderia tentar novamente?</b>"\n ],\n ["UNEXPECTED_OPTION"]: [\n "Não entendi sua mensagem, desculpe...\\n\\n<b>Confira as opções do menu e escolha uma,</b> por favor.",\n "Essa não é uma das opções...\\n\\n<b>Confira as opções do menu e escolha uma,</b> por favor."\n ],\n ["INACTIVITY"]: [\n //"Já faz uns minutinhos desde a sua última mensagem...",\n "Faz um tempo que você não envia mensagens...\\n\\n<b>Vou encerrar a conversa, mas é só enviar um “Oi” para retomar!</b>"\n ],\n ["HTTP_ERROR"]: [\n "Desculpe, meu sistema está indisponível agora...\\n\\n<b>Por favor, tente novamente mais tarde.</b>"\n ],\n ["SCRIPT_ERROR"]: [\n "Desculpe, não consigo te ajudar nesse momento...\\n\\n<b>Por favor, tente novamente mais tarde.</b>"\n ],\n ["RECURRENT_ERROR"]: [\n "Ainda não estou conseguindo te entender...\\n\\n<i>ℹ️ Caso esteja com dificuldades no WhatsApp, busque nossos outros canais de atendimento.</i>\\n\\n<b>Seu atendimento será encerrado, mas você pode reiniciar a qualquer momento mandando um “oi”.</b>"\n ]\n};\nvar DEFAULT_TYPE_MESSAGES = {\n ["AUDIO"]: [\n "Não consigo ouvir áudios agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ouvir áudios agora! 🔈🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["VIDEO"]: [\n "Não consigo ver vídeos agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver vídeos agora... 🎥🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["IMAGE"]: [\n "Não consigo ver imagens agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver imagens agora... 🖼🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["STICKER"]: [\n "Não consigo ver figurinhas...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver figurinhas... 🖼🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["DOCUMENT"]: [\n "Não consigo ver arquivos agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver arquivos agora... 📄🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["LOCATION"]: [\n "Não consigo ver a localização agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver a localização agora... 📍🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ]\n};\nvar DEFAULT_INTENT_MESSAGES = {\n ["CLOSE"]: [\n "Obrigado por nos contatar! 😊 Se precisar de mais ajuda, não hesite em nos procurar novamente."\n ]\n};\nvar DEFAULT_ERROR = {\n type: "UNEXPECTED_INPUT"\n};\nvar DEFAULT_DAYPARTS = {\n ["MORNING"]: [6, 7, 8, 9, 10, 11],\n ["AFTERNOON"]: [12, 13, 14, 15, 16, 17],\n ["EVENING"]: [18, 19, 20, 21],\n ["NIGHT"]: [22, 23, 0, 1, 2, 3, 4, 5]\n};\nvar DEFAULT_LABEL = {\n ["UNEXPECTED"]: "Inesperado",\n ["ABANDONED"]: "Abandonado",\n ["RESOLVED"]: "Finalizado",\n ["ERROR"]: "Erro"\n};\nvar DEFAULT_INACTIVITY = "INACTIVITY";\nvar DEFAULT_PASSWORD = "admin";\nvar DEFAULT_PROPAGATE = null;\nvar DEFAULT_CONTACT_GROUPS = [1];\nvar DEFAULT_DEBUG = false;\nvar config = {\n list: DEFAULT_LIST,\n threshold: DEFAULT_THRESHOLD,\n stackSize: DEFAULT_STACK_SIZES,\n intents: DEFAULT_GLOBAL_INTENTS,\n disabled: DEFAULT_DISABLE,\n messages: {\n error: DEFAULT_ERROR_MESSAGES,\n type: DEFAULT_TYPE_MESSAGES,\n greeting: DEFAULT_GREETING,\n intent: DEFAULT_INTENT_MESSAGES\n },\n daypart: DEFAULT_DAYPARTS,\n error: DEFAULT_ERROR,\n label: DEFAULT_LABEL,\n password: DEFAULT_PASSWORD,\n propagate: DEFAULT_PROPAGATE,\n groups: DEFAULT_CONTACT_GROUPS,\n debug: DEFAULT_DEBUG\n};\nasync function dwnRun(stateId) {\n if (stateId && stateId.startsWith("desk:")) {\n await context.setVariableAsync("dwnBypass", "true");\n } else {\n await context.deleteVariableAsync("dwnBypass");\n }\n return JSON.stringify(config);\n}\n/**\n * @imports\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n */\nvar DwnError = class _DwnError extends Error {\n /**\n * Creates a new DwnError instance.\n *\n * @param {string} type The error type identifier (e.g., "VALIDATION_ERROR", "SCRIPT_ERROR")\n * @param {string} description Human-readable description of what went wrong\n * @param {{message?: string, messages?: string[], stack?: string, goto?: State | null, state?: State, at?: string, intent?: string | null, content?: string, recurrence?: ErrorRecurrence, code?: string | null, status?: FINALIZATION_STATUS}} [extras] Optional additional error context and metadata:\n * - `message`: Primary error message for user display\n * - `messages`: Array of error messages for different contexts\n * - `stack`: Stack trace or execution context information\n * - `goto`: Target state to redirect to on error (null means terminate)\n * - `state`: Flow state where the error occurred\n * - `at`: Location or context where the error occurred\n * - `intent`: Associated intent that caused the error\n * - `content`: Additional error content or context\n * - `recurrence`: Information about error recurrence patterns\n * - `code`: Error code for programmatic error handling\n * - `status`: Finalization status indicating how the error was resolved\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid input provided");\n *\n * const contextError = new DwnError("SCRIPT_ERROR", "Script execution failed", {\n * state: { id: "state-123", service: "main" },\n * intent: "user-input",\n * content: "invalid data",\n * messages: ["First attempt failed", "Retry failed"],\n * goto: { id: "error-handler", service: "main" }\n * });\n * ```\n */\n constructor(type, description, extras) {\n super();\n this.name = "DwnError";\n const _extras = _DwnError.enforceExtras(extras);\n this.type = type;\n this.description = description;\n this.at = _extras.at;\n this.content = _extras.content;\n this.state = _extras.state;\n this.recurrence = _extras.recurrence;\n this.goto = _extras.goto;\n this.message = _extras.message || undefined;\n this.messages = _extras.messages || [];\n this.intent = _extras.intent || undefined;\n this.code = _extras.code || undefined;\n this.status = _extras.status || undefined;\n this.stack = _extras.stack || undefined;\n if (!this.stack) {\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, _DwnError);\n }\n }\n }\n /**\n * Creates a DwnError instance from a serialized error string.\n *\n * Parses a DWN error string in the format "TYPE -|- DESCRIPTION -|- EXTRAS_JSON"\n * and reconstructs the original DwnError instance.\n *\n * @param {string} dwnErrorString Serialized error string from toString() method\n * @returns {DwnError | undefined} DwnError instance or undefined if parsing fails\n *\n * @example\n * ```typescript\n * const errorString = "SCRIPT_ERROR -|- Execution failed -|- {...}";\n * const error = DwnError.fromDwnError(errorString);\n * ```\n */\n static fromDwnError(dwnErrorString) {\n if (!dwnErrorString) return undefined;\n const parts = dwnErrorString.split("-|-");\n let type = parts.shift();\n if (!type) {\n return undefined;\n }\n type = type.trim();\n let description = parts.shift() || "";\n if (description) {\n description = description.trim();\n }\n let extras = undefined;\n try {\n extras = JSON.parse(parts.shift() || "{}");\n } catch (e) {\n }\n if (extras) {\n return new _DwnError(type, description, extras);\n }\n return new _DwnError(type, description);\n }\n /**\n * Creates a DwnError instance from a JSON object.\n *\n * Converts a generic Error object or JSON representation into a properly\n * structured DwnError instance with all required properties.\n *\n * @param {Error} data Error object or JSON data to convert\n * @returns {DwnError} New DwnError instance\n *\n * @example\n * ```typescript\n * const jsonData = { type: "API_ERROR", description: "Request failed" };\n * const error = DwnError.fromJson(jsonData);\n * ```\n */\n static fromJson(data) {\n const extras = _DwnError.enforceExtras(data);\n return new _DwnError(data.type, data.description, extras);\n }\n /**\n * Normalizes and validates error extras properties.\n *\n * Ensures all optional properties have default values and validates the structure\n * of the extras object. Used internally to maintain consistency across error instances.\n *\n * @param {DwnError | DwnErrorExtras} [entity] Error entity or extras object to normalize\n * @returns {Required<DwnErrorExtras>} Normalized extras object with all required properties\n *\n * @internal\n */\n static enforceExtras(entity) {\n if (!entity) entity = {};\n const extras = {};\n extras.message = entity.message || "";\n extras.messages = entity.messages || [];\n extras.stack = entity.stack || "";\n extras.goto = entity.goto;\n extras.state = entity.state || { id: "", service: "" };\n extras.at = entity.at || (new Date()).toISOString();\n extras.intent = entity.intent || "";\n extras.content = entity.content || "";\n extras.recurrence = entity.recurrence || { type: 1, state: 1, combined: 1 };\n extras.code = entity.code || undefined;\n extras.status = entity.status || undefined;\n return extras;\n }\n /**\n * Serializes the error to a string format.\n *\n * Converts the DwnError instance into a parseable string format using the pattern\n * "TYPE -|- DESCRIPTION -|- EXTRAS_JSON" for storage or transmission.\n *\n * @returns {string} Serialized error string\n *\n * @example\n * ```typescript\n * const error = new DwnError("API_ERROR", "Request failed");\n * const serialized = error.toString();\n * // "API_ERROR -|- Request failed -|- {...}"\n * ```\n */\n toString() {\n const extras = JSON.stringify(_DwnError.enforceExtras(this));\n return `${this.type} -|- ${this.description} -|- ${extras}`;\n }\n /**\n * Converts the error to a JSON object.\n *\n * Serializes all error properties into a plain JavaScript object suitable\n * for JSON serialization, API responses, or logging.\n *\n * @returns {Error} Plain object representation of the error\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid data");\n * const json = error.toJson();\n * console.log(JSON.stringify(json, null, 2));\n * ```\n */\n toJson() {\n return {\n type: this.type,\n at: this.at,\n description: this.description,\n message: this.message,\n messages: this.messages || [],\n stack: this.stack || "",\n intent: this.intent,\n content: this.content,\n goto: this.goto,\n state: this.state,\n recurrence: this.recurrence\n };\n }\n};\nvar SYSTEM_DWN_ERRORS = [\n "RUNTIME_ERROR",\n "MISCONFIGURATION_ERROR"\n];\n',
|
|
30
|
+
en: '\nvar DEFAULT_LIST = {\n block: false,\n allow: false\n};\nvar DEFAULT_THRESHOLD = {\n minScore: 0.75,\n maxStack: 3\n};\nvar DEFAULT_DISABLE = {\n inactivity: false,\n intents: []\n};\nvar DEFAULT_STACK_SIZES = {\n requests: 3,\n logs: 10,\n intents: 3,\n errors: 5,\n checkpoints: 5\n};\nvar DEFAULT_GLOBAL_INTENTS = [\n {\n id: "CLOSE",\n label: "Sair",\n type: "regex",\n patterns: ["sair", "encerrar"],\n goto: null\n },\n {\n id: "CHECKPOINT_BACK",\n label: "Voltar",\n type: "regex",\n patterns: ["voltar"]\n }\n];\nvar DEFAULT_GREETING = {\n ["MORNING"]: "Bom dia",\n ["AFTERNOON"]: "Boa tarde",\n ["EVENING"]: "Boa noite",\n ["NIGHT"]: "Boa noite"\n};\nvar DEFAULT_ERROR_MESSAGES = {\n ["UNEXPECTED_INPUT"]: [\n "Desculpe, não consegui entender.\\n\\n<b>Escolha uma opção do menu ou tente com outras palavras,</b> por favor.",\n "Não entendi o que você quis dizer.\\n\\n<b>Poderia tentar novamente?</b>"\n ],\n ["UNEXPECTED_OPTION"]: [\n "Não entendi sua mensagem, desculpe...\\n\\n<b>Confira as opções do menu e escolha uma,</b> por favor.",\n "Essa não é uma das opções...\\n\\n<b>Confira as opções do menu e escolha uma,</b> por favor."\n ],\n ["INACTIVITY"]: [\n //"Já faz uns minutinhos desde a sua última mensagem...",\n "Faz um tempo que você não envia mensagens...\\n\\n<b>Vou encerrar a conversa, mas é só enviar um “Oi” para retomar!</b>"\n ],\n ["HTTP_ERROR"]: [\n "Desculpe, meu sistema está indisponível agora...\\n\\n<b>Por favor, tente novamente mais tarde.</b>"\n ],\n ["SCRIPT_ERROR"]: [\n "Desculpe, não consigo te ajudar nesse momento...\\n\\n<b>Por favor, tente novamente mais tarde.</b>"\n ],\n ["RECURRENT_ERROR"]: [\n "Ainda não estou conseguindo te entender...\\n\\n<i>ℹ️ Caso esteja com dificuldades no WhatsApp, busque nossos outros canais de atendimento.</i>\\n\\n<b>Seu atendimento será encerrado, mas você pode reiniciar a qualquer momento mandando um “oi”.</b>"\n ]\n};\nvar DEFAULT_TYPE_MESSAGES = {\n ["AUDIO"]: [\n "Não consigo ouvir áudios agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ouvir áudios agora! 🔈🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["VIDEO"]: [\n "Não consigo ver vídeos agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver vídeos agora... 🎥🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["IMAGE"]: [\n "Não consigo ver imagens agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver imagens agora... 🖼🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["STICKER"]: [\n "Não consigo ver figurinhas...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver figurinhas... 🖼🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["DOCUMENT"]: [\n "Não consigo ver arquivos agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver arquivos agora... 📄🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ],\n ["LOCATION"]: [\n "Não consigo ver a localização agora...\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>",\n "Opa, não posso ver a localização agora... 📍🚫\\n\\n<b>Envie apenas texto ou uma das opções do menu, por favor.</b>"\n ]\n};\nvar DEFAULT_INTENT_MESSAGES = {\n ["CLOSE"]: [\n "Obrigado por nos contatar! 😊 Se precisar de mais ajuda, não hesite em nos procurar novamente."\n ]\n};\nvar DEFAULT_ERROR = {\n type: "UNEXPECTED_INPUT"\n};\nvar DEFAULT_DAYPARTS = {\n ["MORNING"]: [6, 7, 8, 9, 10, 11],\n ["AFTERNOON"]: [12, 13, 14, 15, 16, 17],\n ["EVENING"]: [18, 19, 20, 21],\n ["NIGHT"]: [22, 23, 0, 1, 2, 3, 4, 5]\n};\nvar DEFAULT_LABEL = {\n ["UNEXPECTED"]: "Inesperado",\n ["ABANDONED"]: "Abandonado",\n ["RESOLVED"]: "Finalizado",\n ["ERROR"]: "Erro"\n};\nvar DEFAULT_INACTIVITY = "INACTIVITY";\nvar DEFAULT_PASSWORD = "admin";\nvar DEFAULT_PROPAGATE = null;\nvar DEFAULT_CONTACT_GROUPS = [1];\nvar DEFAULT_DEBUG = false;\nvar config = {\n list: DEFAULT_LIST,\n threshold: DEFAULT_THRESHOLD,\n stackSize: DEFAULT_STACK_SIZES,\n intents: DEFAULT_GLOBAL_INTENTS,\n disabled: DEFAULT_DISABLE,\n messages: {\n error: DEFAULT_ERROR_MESSAGES,\n type: DEFAULT_TYPE_MESSAGES,\n greeting: DEFAULT_GREETING,\n intent: DEFAULT_INTENT_MESSAGES\n },\n daypart: DEFAULT_DAYPARTS,\n error: DEFAULT_ERROR,\n label: DEFAULT_LABEL,\n password: DEFAULT_PASSWORD,\n propagate: DEFAULT_PROPAGATE,\n groups: DEFAULT_CONTACT_GROUPS,\n debug: DEFAULT_DEBUG\n};\nasync function dwnRun(stateId) {\n if (stateId && stateId.startsWith("desk:")) {\n await context.setVariableAsync("dwnBypass", "true");\n } else {\n await context.deleteVariableAsync("dwnBypass");\n }\n return JSON.stringify(config);\n}\n/**\n * @imports\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n */\nvar DwnError = class _DwnError extends Error {\n /**\n * Creates a new DwnError instance.\n *\n * @param {string} type The error type identifier (e.g., "VALIDATION_ERROR", "SCRIPT_ERROR")\n * @param {string} description Human-readable description of what went wrong\n * @param {{message?: string, messages?: string[], stack?: string, goto?: State | null, state?: State, at?: string, intent?: string | null, content?: string, recurrence?: ErrorRecurrence, code?: string | null, status?: FINALIZATION_STATUS}} [extras] Optional additional error context and metadata:\n * - `message`: Primary error message for user display\n * - `messages`: Array of error messages for different contexts\n * - `stack`: Stack trace or execution context information\n * - `goto`: Target state to redirect to on error (null means terminate)\n * - `state`: Flow state where the error occurred\n * - `at`: Location or context where the error occurred\n * - `intent`: Associated intent that caused the error\n * - `content`: Additional error content or context\n * - `recurrence`: Information about error recurrence patterns\n * - `code`: Error code for programmatic error handling\n * - `status`: Finalization status indicating how the error was resolved\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid input provided");\n *\n * const contextError = new DwnError("SCRIPT_ERROR", "Script execution failed", {\n * state: { id: "state-123", service: "main" },\n * intent: "user-input",\n * content: "invalid data",\n * messages: ["First attempt failed", "Retry failed"],\n * goto: { id: "error-handler", service: "main" }\n * });\n * ```\n */\n constructor(type, description, extras) {\n super();\n this.name = "DwnError";\n const _extras = _DwnError.enforceExtras(extras);\n this.type = type;\n this.description = description;\n this.at = _extras.at;\n this.content = _extras.content;\n this.state = _extras.state;\n this.recurrence = _extras.recurrence;\n this.goto = _extras.goto;\n this.message = _extras.message || undefined;\n this.messages = _extras.messages || [];\n this.intent = _extras.intent || undefined;\n this.code = _extras.code || undefined;\n this.status = _extras.status || undefined;\n this.stack = _extras.stack || undefined;\n if (!this.stack) {\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, _DwnError);\n }\n }\n }\n /**\n * Creates a DwnError instance from a serialized error string.\n *\n * Parses a DWN error string in the format "TYPE -|- DESCRIPTION -|- EXTRAS_JSON"\n * and reconstructs the original DwnError instance.\n *\n * @param {string} dwnErrorString Serialized error string from toString() method\n * @returns {DwnError | undefined} DwnError instance or undefined if parsing fails\n *\n * @example\n * ```typescript\n * const errorString = "SCRIPT_ERROR -|- Execution failed -|- {...}";\n * const error = DwnError.fromDwnError(errorString);\n * ```\n */\n static fromDwnError(dwnErrorString) {\n if (!dwnErrorString) return undefined;\n const parts = dwnErrorString.split("-|-");\n let type = parts.shift();\n if (!type) {\n return undefined;\n }\n type = type.trim();\n let description = parts.shift() || "";\n if (description) {\n description = description.trim();\n }\n let extras = undefined;\n try {\n extras = JSON.parse(parts.shift() || "{}");\n } catch (e) {\n }\n if (extras) {\n return new _DwnError(type, description, extras);\n }\n return new _DwnError(type, description);\n }\n /**\n * Creates a DwnError instance from a JSON object.\n *\n * Converts a generic Error object or JSON representation into a properly\n * structured DwnError instance with all required properties.\n *\n * @param {Error} data Error object or JSON data to convert\n * @returns {DwnError} New DwnError instance\n *\n * @example\n * ```typescript\n * const jsonData = { type: "API_ERROR", description: "Request failed" };\n * const error = DwnError.fromJson(jsonData);\n * ```\n */\n static fromJson(data) {\n const extras = _DwnError.enforceExtras(data);\n return new _DwnError(data.type, data.description, extras);\n }\n /**\n * Normalizes and validates error extras properties.\n *\n * Ensures all optional properties have default values and validates the structure\n * of the extras object. Used internally to maintain consistency across error instances.\n *\n * @param {DwnError | DwnErrorExtras} [entity] Error entity or extras object to normalize\n * @returns {Required<DwnErrorExtras>} Normalized extras object with all required properties\n *\n * @internal\n */\n static enforceExtras(entity) {\n if (!entity) entity = {};\n const extras = {};\n extras.message = entity.message || "";\n extras.messages = entity.messages || [];\n extras.stack = entity.stack || "";\n extras.goto = entity.goto;\n extras.state = entity.state || { id: "", service: "" };\n extras.at = entity.at || (new Date()).toISOString();\n extras.intent = entity.intent || "";\n extras.content = entity.content || "";\n extras.recurrence = entity.recurrence || { type: 1, state: 1, combined: 1 };\n extras.code = entity.code || undefined;\n extras.status = entity.status || undefined;\n return extras;\n }\n /**\n * Serializes the error to a string format.\n *\n * Converts the DwnError instance into a parseable string format using the pattern\n * "TYPE -|- DESCRIPTION -|- EXTRAS_JSON" for storage or transmission.\n *\n * @returns {string} Serialized error string\n *\n * @example\n * ```typescript\n * const error = new DwnError("API_ERROR", "Request failed");\n * const serialized = error.toString();\n * // "API_ERROR -|- Request failed -|- {...}"\n * ```\n */\n toString() {\n const extras = JSON.stringify(_DwnError.enforceExtras(this));\n return `${this.type} -|- ${this.description} -|- ${extras}`;\n }\n /**\n * Converts the error to a JSON object.\n *\n * Serializes all error properties into a plain JavaScript object suitable\n * for JSON serialization, API responses, or logging.\n *\n * @returns {Error} Plain object representation of the error\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid data");\n * const json = error.toJson();\n * console.log(JSON.stringify(json, null, 2));\n * ```\n */\n toJson() {\n return {\n type: this.type,\n at: this.at,\n description: this.description,\n message: this.message,\n messages: this.messages || [],\n stack: this.stack || "",\n intent: this.intent,\n content: this.content,\n goto: this.goto,\n state: this.state,\n recurrence: this.recurrence\n };\n }\n};\nvar SYSTEM_DWN_ERRORS = [\n "RUNTIME_ERROR",\n "MISCONFIGURATION_ERROR"\n];\n',
|
|
31
|
+
//es: "{{create_config_es}}",
|
|
32
|
+
//en: "{{create_config_en}}",
|
|
33
|
+
}[language];
|
|
34
|
+
return {
|
|
35
|
+
$id,
|
|
36
|
+
$typeOfContent: "",
|
|
37
|
+
type: "ExecuteScriptV2",
|
|
38
|
+
$title: "DWN [SETTINGS] Config",
|
|
39
|
+
settings: {
|
|
40
|
+
function: "dwnRun",
|
|
41
|
+
source,
|
|
42
|
+
inputVariables: ["state.id"],
|
|
43
|
+
outputVariable: Feature_1.Feature.VARIABLES.LOCAL_CONFIG,
|
|
44
|
+
},
|
|
45
|
+
conditions: [],
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
exports.configScript = configScript;
|
|
49
|
+
const updateCoreScript = ($id, version) => {
|
|
50
|
+
let source = '/**\n * @author [Beuren Bechlin] <beuren.bechlin@dawntech.dev>\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n *\n * ---\n *\n * This software is the proprietary property of Dawntech.\n * Possession, use, duplication, or dissemination of this software is strictly\n * prohibited unless you have received prior written permission from\n * Dawntech.\n *\n * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nvar dwnGlobalConfig = "resource.dwnGlobalConfig".replace("resource.", "");\nasync function dwnRun(coreStr, setupStr, localStr, globalStr, statesStr, prepareStr, errorStr, inputContent, inputType, inputMessage, stateId) {\n coreStr = coreStr || "";\n localStr = localStr || "";\n globalStr = globalStr || "";\n statesStr = statesStr || "";\n prepareStr = prepareStr || "";\n errorStr = errorStr || "";\n let core;\n let config = undefined;\n let local;\n let global;\n let states = {};\n let prepare = undefined;\n let error = DwnError.fromDwnError(errorStr);\n let warnings = [];\n let _states = {};\n try {\n core = JSON.parse(coreStr || "{}");\n } catch (err) {\n warnings.push(`[update-core] Unexpected core JSON ${String(err)}`);\n core = {};\n }\n let setup;\n try {\n setup = JSON.parse(setupStr || "{}");\n } catch (err) {\n warnings.push(`[update-core] Unexpected setup JSON ${String(err)}`);\n setup = {};\n }\n try {\n local = JSON.parse(localStr);\n } catch (err) {\n warnings.push(`[update-core] Unexpected localConfig JSON ${String(err)}`);\n local = {};\n }\n try {\n global = JSON.parse(globalStr || "{}");\n } catch (err) {\n warnings.push(`[update-core] Unexpected globalConfig JSON ${String(err)}`);\n global = {};\n }\n try {\n prepare = JSON.parse(prepareStr || "null");\n } catch (err) {\n warnings.push(`[update-core] Unexpected prepare JSON ${String(err)}`);\n prepare = undefined;\n }\n try {\n states = JSON.parse(statesStr || "{}");\n } catch (err) {\n warnings.push(`[update-core] Unexpected states JSON ${String(err)}`);\n states = {};\n }\n try {\n if (error && error.type === "MISCONFIGURATION_ERROR") {\n throw error;\n }\n const service = setup.services ? setup.services.current : null;\n if (!service) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `Setup must have \'services.current\' property.`,\n { goto: null }\n );\n }\n _states = Object.keys(_states).reduce((acc, key) => {\n acc[`${key}@${service}`] = _states[key];\n return acc;\n }, {});\n states = {\n ...states,\n ..._states\n };\n await context.setVariableAsync("dwnStates", JSON.stringify(states));\n local = sanitizeLocalConfig(local, service, states);\n global = sanitizeGlobalConfig(global, service, states);\n prepare = sanitizePrepare(prepare, service, states);\n config = createConfig(global, local, prepare, setup);\n await context.setVariableAsync(dwnGlobalConfig, JSON.stringify(global));\n const state = enforceState(\n stateId || "onboarding",\n service,\n states\n );\n if (prepare.stack > config.threshold.maxStack) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `Stack size (prepare.stack) is greater than the maximum stack size (config.threshold.maxStack).`,\n { goto: null }\n );\n }\n let replyContent = inputContent || "";\n let replyType = inputType || "text/plain";\n let replyMessage = inputMessage || "";\n let replyPayload = undefined;\n let replyIntent = null;\n let replyError = null;\n let replyState = null;\n try {\n const EXPECTED_ERRORS = ["RUNTIME_ERROR"];\n if (error && EXPECTED_ERRORS.includes(error.type)) {\n throw error;\n }\n const content = JSON.parse(inputContent || "");\n if (content.state && content.service) {\n replyState = {\n id: content.state,\n service: content.service\n };\n const payload = content;\n if (payload.payload) {\n replyPayload = payload.payload;\n }\n if (payload.intent) {\n replyIntent = payload.intent;\n }\n if (payload.error) {\n replyError = payload.error;\n }\n }\n } catch (err) {\n }\n try {\n let inputMessageParsed = JSON.parse(inputMessage || "{}");\n const rawReplyContent = inputMessageParsed?.metadata?.["#replyContent"];\n if (rawReplyContent) {\n let replyMenu = JSON.parse(rawReplyContent);\n if (replyMenu && replyMenu.replied) {\n replyContent = replyMenu.replied.value || replyContent;\n replyType = replyMenu.replied.type || replyType;\n replyMenu.inReplyTo = { hidden: true };\n inputMessageParsed.metadata["#replyContent"] = JSON.stringify(replyMenu);\n replyMessage = JSON.stringify(inputMessageParsed);\n }\n }\n } catch (err) {\n }\n const reply = {\n content: replyContent,\n type: replyType,\n message: replyMessage,\n payload: replyPayload\n };\n let intent = null;\n if (replyIntent) {\n intent = {\n id: replyIntent,\n type: "static",\n scope: "redirect",\n label: `Intent redirect ${replyIntent}`,\n event: "dwn-redirect-intents",\n pattern: "",\n score: 0\n };\n }\n if (replyError && replyError !== "PROPAGATE" && replyState) {\n if (replyError === "GOTO") {\n error = new DwnError("GOTO", "Goto error", {\n goto: replyState\n });\n } else {\n error = new DwnError(replyError, "Redirect error", {\n state: replyState\n });\n }\n }\n if (error && error.type === "PROPAGATE" && core.error) {\n error = DwnError.fromJson(core.error);\n }\n const stack = core.intents ? core.intents.stack || [] : [];\n const intents = prepare.intents.length ? [\n {\n id: `prepare-${state.service}-${state.id}`,\n intents: prepare.intents,\n scope: "prepare",\n event: prepare.id\n }\n ] : [];\n let groups = [\n ...intents,\n ...stack,\n {\n id: "config",\n intents: config.intents,\n scope: "config",\n event: "config"\n }\n ];\n const checkpoints = core.checkpoints || [];\n if (checkpoints.length === 0) {\n config.disabled.intents.push("CHECKPOINT_BACK");\n }\n if (config.disabled.intents.length > 0) {\n groups = groups.map((group) => {\n group.intents = group.intents.filter((intent2) => {\n return !config.disabled.intents.includes(intent2.id);\n });\n return group;\n });\n }\n let services = core.services || [];\n const serviceIndex = services.findIndex((_service) => _service === service);\n if (serviceIndex >= 0) {\n services.splice(0, serviceIndex + 1);\n }\n services.unshift(service);\n let propagate = config.propagate ? config.propagate : services[1];\n if (config.service.current === propagate) {\n propagate = undefined;\n }\n core.version = "{{version}}";\n core.errors = core.errors || [];\n core.checkpoint = prepare.checkpoint || false;\n core.checkpoints = core.checkpoints || [];\n core.services = services;\n core.intent = intent;\n core.intents = { stack, groups };\n core.prepare = prepare;\n core.state = state;\n core.reply = reply;\n core.group = core.group || "A";\n core.journey = core.journey || "{{random.guid}}";\n core.sessions = core.sessions || 1;\n core.service = config.service.current;\n core.visits = core.visits || [];\n core.main = config.service.current === config.service.main || undefined;\n core.propagate = propagate;\n core.redirect = undefined;\n await context.setVariableAsync("dwnConfig", JSON.stringify(config));\n } catch (err) {\n if (!(err instanceof DwnError)) {\n const description = `[update-core] Unexpected error ${String(err)}`;\n const stack = err.stack || "";\n err = new DwnError("RUNTIME_ERROR", description, {\n stack,\n goto: null\n });\n }\n error = err;\n } finally {\n if (!core || typeof core !== "object") {\n core = {};\n }\n core.warnings = warnings;\n core.error = error ? error.toJson() : null;\n core.fallback = "fallback";\n coreStr = JSON.stringify(core);\n }\n if (prepare) {\n await context.deleteVariableAsync("dwnPrepare");\n }\n if (config && typeof config === "object") {\n await context.setVariableAsync("dwnConfig", JSON.stringify(config));\n }\n if (error && error.toString() !== errorStr) {\n await context.setVariableAsync("dwnError", error.toString());\n }\n return coreStr;\n}\nfunction sanitizeLocalConfig(config, service, states) {\n const intents = config.intents || [];\n config.intents = intents.map(\n (intent) => sanitizeIntentSpec(intent, service, states)\n );\n return config;\n}\nfunction sanitizeGlobalConfig(config, service, states) {\n const intents = config.intents || [];\n config.intents = intents.map(\n (intent) => sanitizeIntentSpec(intent, service, states, true)\n );\n return config;\n}\nfunction createConfig(global, local, prepare, setup) {\n const config = merge(global, local);\n const minScore = config.threshold.minScore || prepare.score;\n if (!minScore) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n "Threshold score (config.threshold.score) is required in the configuration.",\n { goto: null }\n );\n }\n if (setup.services) {\n config.service = setup.services;\n }\n if (setup.connection) {\n config.connection = setup.connection;\n }\n if (setup.gmt) {\n config.gmt = setup.gmt;\n }\n if (global.service && global.service.main) {\n config.service.main = global.service.main;\n }\n if (global.connection && global.connection.contract && global.connection.key) {\n config.connection.contract = global.connection.contract;\n config.connection.key = global.connection.key;\n }\n config.threshold.minScore = minScore;\n config.error = merge(\n config.error,\n prepare.error\n );\n config.inactivity = prepare.inactivity || config.inactivity;\n config.disabled = merge(config.disabled, prepare.disabled);\n config.disabled.intents = Array.from(new Set(config.disabled.intents));\n if (!config.inactivity) {\n config.inactivity = "INACTIVITY";\n }\n if (!config.service || !config.service.current || !config.service.main || !config.gmt) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `Config must have \'service.current\', \'service.main\', and \'gmt\' properties.`,\n { goto: null }\n );\n }\n if (!config.label["UNEXPECTED"]) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `Label for \'unexpected\' (config.label[\'${"UNEXPECTED"}\']) input is required in the configuration.`,\n { goto: null }\n );\n }\n return config;\n}\nfunction sanitizePrepare(prepare, service, states) {\n if (!prepare) {\n prepare = { id: "prepare-not-set" };\n } else {\n if (!prepare.id) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `Prepare must have \'id\' property.`,\n { goto: null }\n );\n }\n }\n const v0 = prepare;\n const latest = prepare;\n prepare = prepare;\n prepare.id = kebabCase(prepare.id);\n prepare.checkpoint = prepare.checkpoint || false;\n prepare.stack = prepare.stack || 0;\n prepare.score = prepare.score;\n prepare.disabled = prepare.disabled || {};\n prepare.disabled.inactivity = prepare.disabled.inactivity || false;\n prepare.disabled.intents = prepare.disabled.intents || [];\n prepare.label = prepare.label;\n prepare.intents = prepare.intents || [];\n prepare.models = prepare.models || [];\n prepare.types = prepare.types || [];\n let inactivity = latest.inactivity || "INACTIVITY";\n if (v0.error && v0.error.inactivity) {\n inactivity = v0.error.inactivity;\n }\n prepare.inactivity = inactivity;\n const error = {\n type: "UNEXPECTED_INPUT",\n messages: [],\n goto: undefined\n };\n if (latest.error && latest.error.type) {\n error.type = latest.error.type;\n } else if (v0.error && v0.error.default) {\n error.type = v0.error.default;\n }\n if (latest.error && latest.error.goto) {\n error.goto = enforceState(latest.error.goto, service, states);\n }\n if (latest.error && latest.error.messages) {\n error.messages = latest.error.messages;\n } else if (v0.messages) {\n error.messages = v0.messages;\n }\n prepare.error = error;\n prepare.intents = prepare.intents.map(\n (intent) => sanitizeIntentSpec(intent, service, states)\n );\n return prepare;\n}\nfunction sanitizeIntentSpec(intent, service, states, global = false) {\n if (!intent.id || !intent.label) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `Intent ${JSON.stringify(intent)} must have \'id\' and \'label\' properties.`,\n { goto: null }\n );\n }\n intent.type = intent.type || "static";\n intent.patterns = intent.patterns || [];\n intent.payload = intent.payload || null;\n if (global) {\n const incompleteGoto = intent.goto && !intent.goto.service;\n if (incompleteGoto) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `Intent ${JSON.stringify(\n intent\n )} has an incomplete goto. Service is required in the global config.`,\n { goto: null }\n );\n }\n }\n intent.goto = enforceState(intent.goto, service, states);\n return intent;\n}\n/**\n * @imports\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n */\nvar DwnError = class _DwnError extends Error {\n /**\n * Creates a new DwnError instance.\n *\n * @param {string} type The error type identifier (e.g., "VALIDATION_ERROR", "SCRIPT_ERROR")\n * @param {string} description Human-readable description of what went wrong\n * @param {{message?: string, messages?: string[], stack?: string, goto?: State | null, state?: State, at?: string, intent?: string | null, content?: string, recurrence?: ErrorRecurrence, code?: string | null, status?: FINALIZATION_STATUS}} [extras] Optional additional error context and metadata:\n * - `message`: Primary error message for user display\n * - `messages`: Array of error messages for different contexts\n * - `stack`: Stack trace or execution context information\n * - `goto`: Target state to redirect to on error (null means terminate)\n * - `state`: Flow state where the error occurred\n * - `at`: Location or context where the error occurred\n * - `intent`: Associated intent that caused the error\n * - `content`: Additional error content or context\n * - `recurrence`: Information about error recurrence patterns\n * - `code`: Error code for programmatic error handling\n * - `status`: Finalization status indicating how the error was resolved\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid input provided");\n *\n * const contextError = new DwnError("SCRIPT_ERROR", "Script execution failed", {\n * state: { id: "state-123", service: "main" },\n * intent: "user-input",\n * content: "invalid data",\n * messages: ["First attempt failed", "Retry failed"],\n * goto: { id: "error-handler", service: "main" }\n * });\n * ```\n */\n constructor(type, description, extras) {\n super();\n this.name = "DwnError";\n const _extras = _DwnError.enforceExtras(extras);\n this.type = type;\n this.description = description;\n this.at = _extras.at;\n this.content = _extras.content;\n this.state = _extras.state;\n this.recurrence = _extras.recurrence;\n this.goto = _extras.goto;\n this.message = _extras.message || undefined;\n this.messages = _extras.messages || [];\n this.intent = _extras.intent || undefined;\n this.code = _extras.code || undefined;\n this.status = _extras.status || undefined;\n this.stack = _extras.stack || undefined;\n if (!this.stack) {\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, _DwnError);\n }\n }\n }\n /**\n * Creates a DwnError instance from a serialized error string.\n *\n * Parses a DWN error string in the format "TYPE -|- DESCRIPTION -|- EXTRAS_JSON"\n * and reconstructs the original DwnError instance.\n *\n * @param {string} dwnErrorString Serialized error string from toString() method\n * @returns {DwnError | undefined} DwnError instance or undefined if parsing fails\n *\n * @example\n * ```typescript\n * const errorString = "SCRIPT_ERROR -|- Execution failed -|- {...}";\n * const error = DwnError.fromDwnError(errorString);\n * ```\n */\n static fromDwnError(dwnErrorString) {\n if (!dwnErrorString) return undefined;\n const parts = dwnErrorString.split("-|-");\n let type = parts.shift();\n if (!type) {\n return undefined;\n }\n type = type.trim();\n let description = parts.shift() || "";\n if (description) {\n description = description.trim();\n }\n let extras = undefined;\n try {\n extras = JSON.parse(parts.shift() || "{}");\n } catch (e) {\n }\n if (extras) {\n return new _DwnError(type, description, extras);\n }\n return new _DwnError(type, description);\n }\n /**\n * Creates a DwnError instance from a JSON object.\n *\n * Converts a generic Error object or JSON representation into a properly\n * structured DwnError instance with all required properties.\n *\n * @param {Error} data Error object or JSON data to convert\n * @returns {DwnError} New DwnError instance\n *\n * @example\n * ```typescript\n * const jsonData = { type: "API_ERROR", description: "Request failed" };\n * const error = DwnError.fromJson(jsonData);\n * ```\n */\n static fromJson(data) {\n const extras = _DwnError.enforceExtras(data);\n return new _DwnError(data.type, data.description, extras);\n }\n /**\n * Normalizes and validates error extras properties.\n *\n * Ensures all optional properties have default values and validates the structure\n * of the extras object. Used internally to maintain consistency across error instances.\n *\n * @param {DwnError | DwnErrorExtras} [entity] Error entity or extras object to normalize\n * @returns {Required<DwnErrorExtras>} Normalized extras object with all required properties\n *\n * @internal\n */\n static enforceExtras(entity) {\n if (!entity) entity = {};\n const extras = {};\n extras.message = entity.message || "";\n extras.messages = entity.messages || [];\n extras.stack = entity.stack || "";\n extras.goto = entity.goto;\n extras.state = entity.state || { id: "", service: "" };\n extras.at = entity.at || (new Date()).toISOString();\n extras.intent = entity.intent || "";\n extras.content = entity.content || "";\n extras.recurrence = entity.recurrence || { type: 1, state: 1, combined: 1 };\n extras.code = entity.code || undefined;\n extras.status = entity.status || undefined;\n return extras;\n }\n /**\n * Serializes the error to a string format.\n *\n * Converts the DwnError instance into a parseable string format using the pattern\n * "TYPE -|- DESCRIPTION -|- EXTRAS_JSON" for storage or transmission.\n *\n * @returns {string} Serialized error string\n *\n * @example\n * ```typescript\n * const error = new DwnError("API_ERROR", "Request failed");\n * const serialized = error.toString();\n * // "API_ERROR -|- Request failed -|- {...}"\n * ```\n */\n toString() {\n const extras = JSON.stringify(_DwnError.enforceExtras(this));\n return `${this.type} -|- ${this.description} -|- ${extras}`;\n }\n /**\n * Converts the error to a JSON object.\n *\n * Serializes all error properties into a plain JavaScript object suitable\n * for JSON serialization, API responses, or logging.\n *\n * @returns {Error} Plain object representation of the error\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid data");\n * const json = error.toJson();\n * console.log(JSON.stringify(json, null, 2));\n * ```\n */\n toJson() {\n return {\n type: this.type,\n at: this.at,\n description: this.description,\n message: this.message,\n messages: this.messages || [],\n stack: this.stack || "",\n intent: this.intent,\n content: this.content,\n goto: this.goto,\n state: this.state,\n recurrence: this.recurrence\n };\n }\n};\nvar SYSTEM_DWN_ERRORS = [\n "RUNTIME_ERROR",\n "MISCONFIGURATION_ERROR"\n];\n\n\nfunction enforceState(state, currentService, states) {\n if (!state && typeof state !== "string") {\n return state;\n }\n const id = typeof state === "string" ? state : state.id;\n if (!id) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `State ${JSON.stringify(state)} must have \'id\' property.`\n );\n }\n const key = `${id}@${currentService}`;\n let service = typeof state === "string" ? currentService : state.service;\n if (!service) {\n service = currentService;\n }\n let name = typeof state === "string" ? "" : state.name;\n if (!name) {\n name = states[key] || undefined;\n }\n return { id, service, name };\n}\n\n\nfunction kebabCase(str) {\n if (!str) return "";\n const matches = str.match(\n /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g\n );\n if (!matches) return "";\n return matches.map((x) => x.toLowerCase()).join("-");\n}\n\n\nfunction deepClone(source) {\n if (source === null || typeof source !== "object") {\n return source;\n }\n if (source instanceof Date) {\n return new Date(source.getTime());\n }\n if (Array.isArray(source)) {\n const newArray = [];\n for (let i = 0; i < source.length; i++) {\n newArray[i] = deepClone(source[i]);\n }\n return newArray;\n }\n const newObject = {};\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n newObject[key] = deepClone(source[key]);\n }\n }\n return newObject;\n}\nfunction internalMerge(...objects) {\n const validObjects = objects.filter((obj) => obj && typeof obj === "object");\n if (validObjects.length === 0) return {};\n const result = deepClone(validObjects[0] || {});\n for (let i = 1; i < validObjects.length; i++) {\n const source = validObjects[i];\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = source[key];\n const resultValue = result[key];\n const isPlainObject = (v) => v && typeof v === "object" && !Array.isArray(v);\n if (isPlainObject(resultValue) && isPlainObject(sourceValue)) {\n result[key] = internalMerge(resultValue, sourceValue);\n } else if (Array.isArray(resultValue) && Array.isArray(sourceValue)) {\n result[key] = [...sourceValue, ...resultValue];\n } else {\n result[key] = deepClone(sourceValue);\n }\n }\n }\n }\n return result;\n}\nfunction merge(...objects) {\n return internalMerge(...objects);\n}\n';
|
|
51
|
+
source = source.replace("{{version}}", version);
|
|
52
|
+
const script = {
|
|
53
|
+
$id,
|
|
54
|
+
$typeOfContent: "",
|
|
55
|
+
type: "ExecuteScriptV2",
|
|
56
|
+
$title: "DWN Update Core",
|
|
57
|
+
settings: {
|
|
58
|
+
function: "dwnRun",
|
|
59
|
+
source,
|
|
60
|
+
inputVariables: [
|
|
61
|
+
Feature_1.Feature.VARIABLES.CORE,
|
|
62
|
+
Feature_1.Feature.VARIABLES.SETUP,
|
|
63
|
+
Feature_1.Feature.VARIABLES.LOCAL_CONFIG,
|
|
64
|
+
Feature_1.Feature.VARIABLES.GLOBAL_CONFIG,
|
|
65
|
+
Feature_1.Feature.VARIABLES.STATES,
|
|
66
|
+
Feature_1.Feature.VARIABLES.PREPARE,
|
|
67
|
+
Feature_1.Feature.VARIABLES.ERROR,
|
|
68
|
+
"input.content",
|
|
69
|
+
"input.type",
|
|
70
|
+
"input.message",
|
|
71
|
+
"state.id",
|
|
72
|
+
],
|
|
73
|
+
outputVariable: Feature_1.Feature.VARIABLES.CORE,
|
|
74
|
+
},
|
|
75
|
+
conditions: [
|
|
76
|
+
{
|
|
77
|
+
values: [],
|
|
78
|
+
source: "context",
|
|
79
|
+
comparison: "notExists",
|
|
80
|
+
variable: Feature_1.Feature.VARIABLES.BYPASS,
|
|
81
|
+
},
|
|
82
|
+
],
|
|
83
|
+
};
|
|
84
|
+
return script;
|
|
85
|
+
};
|
|
86
|
+
exports.updateCoreScript = updateCoreScript;
|
|
87
|
+
const updateDwnScript = ($id) => {
|
|
88
|
+
const source = '/**\n * @author [Beuren Bechlin] <beuren.bechlin@dawntech.dev>\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n *\n * ---\n *\n * This software is the proprietary property of Dawntech.\n * Possession, use, duplication, or dissemination of this software is strictly\n * prohibited unless you have received prior written permission from\n * Dawntech.\n *\n * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nasync function dwnRun(dwnStr, coreStr, configStr, statesStr, errorStr, listsConfigStr, tunnelOriginator, contactSerialized) {\n dwnStr = dwnStr || "";\n coreStr = coreStr || "";\n configStr = configStr || "";\n statesStr = statesStr || "";\n errorStr = errorStr || "";\n listsConfigStr = listsConfigStr || "";\n let warnings = [];\n let error = DwnError.fromDwnError(errorStr);\n let dwn = null;\n let core = null;\n let config = null;\n let contact;\n let states = {};\n let intent = null;\n let goto = undefined;\n let lists = { allow: [], block: [] };\n try {\n try {\n core = JSON.parse(coreStr);\n } catch (err) {\n warnings.push(`[update-dwn] Unexpected core JSON ${String(err)}`);\n throw new Error(`core parsing ${String(err)}`);\n }\n warnings = core.warnings;\n const EXPECTED_ERRORS = [\n "RUNTIME_ERROR",\n "MISCONFIGURATION_ERROR",\n "PROPAGATE"\n ];\n if (error && EXPECTED_ERRORS.includes(error.type)) {\n throw error;\n }\n try {\n dwn = JSON.parse(dwnStr || "{}");\n } catch (err) {\n warnings.push(`[update-dwn] Unexpected dwn JSON ${String(err)}`);\n dwn = {};\n }\n try {\n states = JSON.parse(statesStr);\n } catch (err) {\n warnings.push(`[update-dwn] Unexpected states JSON ${String(err)}`);\n states = {};\n }\n try {\n config = JSON.parse(configStr);\n } catch (err) {\n warnings.push(`[update-dwn] Unexpected config JSON ${String(err)}`);\n throw new Error(`config parsing ${String(err)}`);\n }\n try {\n contact = JSON.parse(contactSerialized);\n } catch (err) {\n warnings.push(`[update-dwn] Unexpected contact JSON ${String(err)}`);\n throw new Error(`contact parsing ${String(err)}`);\n }\n try {\n lists = JSON.parse(listsConfigStr || "{}");\n } catch (err) {\n warnings.push(`[update-dwn] Unexpected listsConfig JSON ${String(err)}`);\n throw new Error(`listsConfig parsing ${String(err)}`);\n }\n dwn.error = undefined;\n dwn.intent = undefined;\n const prepare = core.prepare;\n let allowList = [];\n try {\n if (!config.list.allow) {\n throw new Error("DISABLED_LIST");\n }\n if (!Array.isArray(lists.allow) || lists.allow.length === 0) {\n throw new Error("allow list is not filled or invalid");\n }\n allowList = lists.allow.map(\n (id) => user__id(id, contact.identity)\n );\n } catch (err) {\n allowList = [];\n const _err = err instanceof Error ? err.message : String(err);\n if (_err !== "DISABLED_LIST") {\n warnings.push(`[update-dwn] Unexpected allowList JSON ${String(err)}`);\n }\n }\n let blockList = [];\n try {\n if (!config.list.block) {\n throw new Error("DISABLED_LIST");\n }\n if (!Array.isArray(lists.block) || lists.block.length === 0) {\n throw new Error("blockList is not filled or invalid");\n }\n blockList = lists.block.map(\n (id) => user__id(id, contact.identity)\n );\n } catch (err) {\n blockList = [];\n const _err = err instanceof Error ? err.message : String(err);\n if (_err !== "DISABLED_LIST") {\n warnings.push(`[update-dwn] Unexpected blockList JSON ${err}`);\n }\n }\n let calendar = datetime__process(new Date(), config.gmt);\n let daypart = daypart__find(calendar.hour, config.daypart);\n let user = user__process(\n contact,\n tunnelOriginator,\n !Boolean(dwn.user),\n config.debug,\n core.group,\n core.sessions,\n allowList,\n blockList\n );\n if (user.blocked) {\n let _error = new DwnError(\n "BLOCKED_CONTACT",\n "Blocked contact",\n {\n recurrence: { type: -1, state: -1, combined: -1 },\n goto: null\n }\n );\n error = error || _error;\n }\n let input = input__process(core.reply, prepare.models);\n if (input.model == "DEBUG" && input.payload["password"] === config.password) {\n user.debug = !user.debug || undefined;\n const _error = new DwnError(\n "DEBUG",\n `Debug mode toggled ${user.debug ? "on" : "off"}`\n );\n error = error || _error;\n }\n if (input.model == "GOTO" && input.payload["password"] === config.password && user.debug) {\n goto = {\n id: input.payload.state,\n service: input.payload.service\n };\n const _error = new DwnError(\n "GOTO",\n `Force state change`,\n { goto }\n );\n error = error || _error;\n }\n if (input.type === "INACTIVITY" && !config.disabled.inactivity) {\n const _error = new DwnError(config.inactivity, "Inactivity detected", {\n goto: null\n });\n error = error || _error;\n }\n if (!intent) {\n const [_intent, _goto] = redirect__intent(\n core.intent,\n core.intents.groups\n );\n if (_intent) {\n intent = _intent;\n goto = _goto;\n }\n }\n if (!intent) {\n const [_intent, _goto, _payload] = user__intent(\n contact,\n core.intents.groups\n );\n if (_intent) {\n intent = _intent;\n goto = _goto;\n input.payload = input.payload || _payload;\n let _error = new DwnError(\n "INTENT",\n `Contact intent ${intent.id} matched.`,\n { goto }\n );\n error = error || _error;\n }\n }\n if (!intent) {\n for (const intentSpec of core.intents.groups) {\n let [_intent, _goto, _payload] = reply__intent(\n core.reply,\n intentSpec,\n config\n );\n if (_intent) {\n intent = _intent;\n goto = _goto;\n input.payload = input.payload || _payload;\n break;\n }\n }\n }\n if (intent && intent.id === "CHECKPOINT_BACK") {\n const _goto = core.checkpoints.shift();\n if (_goto) {\n goto = goto || _goto;\n } else {\n intent = null;\n }\n }\n if (intent && (intent.scope !== "prepare" || goto)) {\n const _error = new DwnError(\n "INTENT",\n `Intent ${intent.id} in scope ${intent.scope} matched.`,\n { goto }\n );\n error = error || _error;\n }\n if (!intent && prepare) {\n const messages = config.error.messages || [];\n const goto2 = config.error.goto || undefined;\n if (prepare.models && prepare.models.length > 0 && !input.model) {\n const _error = new DwnError(\n config.error.type,\n `Unexpected input model. Expected one of: ${prepare.models.join(\n ", "\n )}`,\n { messages, goto: goto2 }\n );\n error = error || _error;\n } else if (prepare.types && prepare.types.length > 0 && input.type && !prepare.types.includes(input.type)) {\n const _error = new DwnError(\n config.error.type,\n `Unexpected input type: ${input.type}. Expected one of: ${prepare.types.join(", ")}`,\n { messages, goto: goto2 }\n );\n error = error || _error;\n } else if (prepare.intents && prepare.intents.length > 0) {\n intent = {\n id: undefined,\n type: "static",\n label: config.label["UNEXPECTED"],\n scope: "prepare",\n event: prepare.id,\n pattern: "",\n score: 0\n };\n }\n }\n if (core.checkpoint) {\n const checkpointIndex = core.checkpoints.findIndex(\n (checkpoint) => checkpoint.id === core.state.id && checkpoint.service === core.service\n );\n if (checkpointIndex >= 0) {\n core.checkpoints.splice(0, checkpointIndex + 1);\n }\n core.checkpoints.unshift(core.state);\n core.checkpoints = core.checkpoints.slice(\n 0,\n config.stackSize.checkpoints\n );\n }\n if (prepare.intents && prepare.stack > 0) {\n const intentsGroup = {\n id: prepare.id,\n intents: prepare.intents,\n scope: "stack",\n event: prepare.id\n };\n const stackLastIndex = core.intents.stack.reduce(\n (lastIndex, intent2, index) => intent2.id === prepare.id ? index : lastIndex,\n -1\n );\n if (stackLastIndex >= 0) {\n core.intents.stack.splice(0, stackLastIndex + 1);\n }\n const groups = new Array(prepare.stack).fill(intentsGroup);\n core.intents.stack.unshift(...groups);\n core.intents.stack = core.intents.stack.slice(\n 0,\n config.stackSize.intents\n );\n }\n dwn.journey = core.journey;\n dwn.daypart = daypart;\n dwn.greeting = config.messages.greeting[daypart];\n dwn.calendar = calendar;\n dwn.input = input;\n dwn.user = user;\n dwn.service = config.service.current;\n dwn.main = core.main || false;\n dwn.error = undefined;\n if (error) {\n error.goto = enforceState(error.goto, config.service.current, states);\n dwn.error = error.toJson();\n }\n dwn.intent = intent || undefined;\n core.intent = intent || null;\n } catch (err) {\n if (!(err instanceof DwnError)) {\n const description = `[update-dwn] Unexpected error ${String(err)}`;\n const stack = err.stack || "";\n err = new DwnError("RUNTIME_ERROR", description, {\n stack,\n goto: null\n });\n }\n error = err;\n } finally {\n if (!core || typeof core !== "object") {\n core = {};\n }\n if (!dwn || typeof dwn !== "object") {\n dwn = {};\n }\n if (error) {\n dwn.error = error.toJson();\n }\n core.warnings = warnings;\n dwn.warnings = core.warnings.join("\\n");\n dwnStr = JSON.stringify(dwn);\n }\n if (core && typeof core === "object") {\n await context.setVariableAsync("dwnCore", JSON.stringify(core));\n }\n if (error && error.toString() !== errorStr) {\n await context.setVariableAsync("dwnError", error.toString());\n }\n return dwnStr;\n}\nfunction user__source(contactIdentity) {\n contactIdentity = String(contactIdentity);\n if (contactIdentity.includes("@0mn.io")) return "BLIP_CHAT";\n if (contactIdentity.includes("@mailgun.gw.msging.net"))\n return "E_MAIL";\n if (contactIdentity.includes("@messenger.gw.msging.net"))\n return "MESSENGER";\n if (contactIdentity.includes("@skype.gw.msging.net"))\n return "SKYPE";\n if (contactIdentity.includes("@take.io")) return "SMS_TAKE";\n if (contactIdentity.includes("@tangram.com.br"))\n return "SMS_TANGRAM";\n if (contactIdentity.includes("@telegram.gw.msging.net"))\n return "TELEGRAM";\n if (contactIdentity.includes("@wa.gw.msging.net"))\n return "WHATSAPP";\n if (contactIdentity.includes("@instagram.gw.msging.net"))\n return "INSTAGRAM";\n if (contactIdentity.includes("@googlercs.gw.msging.net"))\n return "GOOGLE_RCS";\n if (contactIdentity.includes("@abs.gw.msging.net"))\n return "MICROSOFT_TEAMS";\n if (contactIdentity.includes("@businesschat.gw.msging.net"))\n return "APPLE_BUSINESS_CHAT";\n if (contactIdentity.includes("@workplace.gw.msging.net"))\n return "WORKPLACE";\n return "OUTRO";\n}\nfunction user__id(contactPrefix, contactId) {\n if (contactPrefix.includes("@")) return contactPrefix;\n const source = user__source(contactId);\n const domains = {\n ["BLIP_CHAT"]: "@0mn.io",\n ["E_MAIL"]: "@mailgun.gw.msging.net",\n ["MESSENGER"]: "@messenger.gw.msging.net",\n ["SKYPE"]: "@skype.gw.msging.net",\n ["SMS_TAKE"]: "@take.io",\n ["SMS_TANGRAM"]: "@tangram.com.br",\n ["TELEGRAM"]: "@telegram.gw.msging.net",\n ["WHATSAPP"]: "@wa.gw.msging.net",\n ["INSTAGRAM"]: "@instagram.gw.msging.net",\n ["GOOGLE_RCS"]: "@googlercs.gw.msging.net",\n ["MICROSOFT_TEAMS"]: "@abs.gw.msging.net",\n ["APPLE_BUSINESS_CHAT"]: "@businesschat.gw.msging.net",\n ["WORKPLACE"]: "@workplace.gw.msging.net",\n ["OUTRO"]: ""\n };\n return `${contactPrefix}${domains[source] || ""}`;\n}\nfunction redirect__intent(intent, groups) {\n const { id, scope } = intent || {};\n let goto = undefined;\n const group = groups.find((group2) => group2.id === "config");\n intent = null;\n if (id && group && scope === "redirect") {\n const _intent = group.intents.find((_intent2) => _intent2.id === id);\n if (_intent) {\n intent = {\n id: _intent.id,\n type: "static",\n label: `Intent redirect ${_intent.id}`,\n scope: "redirect",\n event: "dwn-redirect-intents",\n pattern: "",\n score: 0\n };\n goto = _intent.goto || undefined;\n }\n }\n return [intent, goto];\n}\nfunction user__intent(contact, groups) {\n let intent = null;\n let goto = undefined;\n let payload = null;\n let id = undefined;\n let event = "dwn-contact-intents";\n const group = groups.find((group2) => group2.id === "config");\n try {\n if (!contact.extras["intent"]) throw new Error("Intent not found");\n let extras = {};\n const [intent2, extrasStr] = contact.extras["intent"].split("-|-");\n id = intent2 || undefined;\n try {\n extras = JSON.parse(extrasStr || "{}");\n } catch (e) {\n }\n if (extras.event) {\n event = extras.event;\n }\n if (extras.payload) {\n payload = extras.payload;\n }\n if (extras.dueDate && extras.expired && extras.expired.intent) {\n const date = new Date(extras.dueDate || 0);\n if ((new Date()).getTime() > date.getTime()) {\n id = extras.expired.intent;\n }\n if (extras.expired.event) {\n event = extras.expired.event;\n }\n }\n } catch (e) {\n }\n if (id && group) {\n const intentSpec = group.intents.find((intent2) => intent2.id === id);\n if (intentSpec) {\n goto = intentSpec.goto;\n intent = {\n id: id ? id.trim() : undefined,\n type: "static",\n label: `Intent contact extra ${id}`,\n scope: "contact",\n event,\n pattern: "",\n score: 0\n };\n }\n }\n return [intent, goto, payload];\n}\nfunction is_phone(text) {\n return Boolean(text && /^\\d+$/.test(text) && text.length <= 15);\n}\nfunction user__phone(contact, source) {\n if (source !== "WHATSAPP") {\n return undefined;\n }\n if (contact.whatsAppWaId && is_phone(contact.whatsAppWaId)) {\n return contact.whatsAppWaId;\n }\n const identityPrefix = contact.identity.split("@")[0];\n if (is_phone(identityPrefix)) {\n return identityPrefix;\n }\n return undefined;\n}\nfunction user__process(contact, tunnelOriginator, newUser, configDebug, group, sessions, allowList, blockList) {\n const id = tunnelOriginator ? tunnelOriginator : contact.identity;\n const source = user__source(contact.identity);\n const debug = Boolean(contact.extras && contact.extras["debug"]) || configDebug || undefined;\n const blocked = blockList.some(\n (id2) => contact.identity === user__id(id2, contact.identity)\n );\n const allowed = allowList.some(\n (id2) => contact.identity === user__id(id2, contact.identity)\n );\n const phone = user__phone(contact, source);\n const cellphone = phone ? phone.substring(2) : undefined;\n const DDD = phone ? phone.substring(2, 4) : undefined;\n return {\n id,\n source,\n new: newUser || undefined,\n blocked,\n allowed,\n group,\n sessions,\n cellphone,\n phone,\n DDD,\n debug\n };\n}\nfunction datetime__to_iso_with_offset(date, tzOffset) {\n const dateTz = new Date(date.getTime() + tzOffset * 36e5);\n const dateFormatted = dateTz.toISOString().split(".")[0];\n const offsetSign = tzOffset >= 0 ? "+" : "-";\n const offsetHours = Math.abs(Math.floor(tzOffset)).toString().padStart(2, "0");\n const offsetMinutes = Math.abs(tzOffset % 1 * 60).toString().padStart(2, "0");\n return `${dateFormatted}${offsetSign}${offsetHours}:${offsetMinutes}`;\n}\nfunction datetime__process(date, tzOffset) {\n const datetime = datetime__to_iso_with_offset(date, tzOffset);\n const calendar = {\n datetime,\n date: datetime.split("T")[0],\n time: datetime.split("T")[1].split(".")[0].substring(0, 8),\n hour: parseInt(datetime.split("T")[1].substring(0, 2)),\n minute: parseInt(datetime.split("T")[1].substring(3, 5)),\n GMT: tzOffset\n };\n return calendar;\n}\nfunction daypart__find(hour, daypart) {\n if (isNaN(hour) || hour < 0 || hour > 23) {\n throw new DwnError(\n "RUNTIME_ERROR",\n `Invalid hour: ${hour}`,\n { goto: null }\n );\n }\n if (!daypart || !daypart.MORNING || !daypart.AFTERNOON || !daypart.EVENING || !daypart.NIGHT) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n "Daypart configuration is incomplete",\n { goto: null }\n );\n }\n if (daypart.MORNING.includes(hour)) return "MORNING";\n if (daypart.AFTERNOON.includes(hour)) return "AFTERNOON";\n if (daypart.EVENING.includes(hour)) return "EVENING";\n if (daypart.NIGHT.includes(hour)) return "NIGHT";\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `Hour ${hour} not found in any daypart`,\n { goto: null }\n );\n}\nfunction type__inactivity(reply) {\n return reply.content === "" ? null : undefined;\n}\nfunction type__flows(reply) {\n try {\n return JSON.parse(\n JSON.parse(reply.message).metadata["#wa.interactive.nfm_reply.json_response"]\n );\n } catch (err) {\n }\n return undefined;\n}\nfunction type__ctwa(reply) {\n try {\n const { metadata } = JSON.parse(reply.message || "{}");\n if (metadata && metadata["#wa.referral.source_id"]) {\n return {\n headline: metadata["#wa.referral.headline"],\n body: metadata["#wa.referral.body"],\n source_type: metadata["#wa.referral.source_type"],\n source_id: metadata["#wa.referral.source_id"],\n source_url: metadata["#wa.referral.source_url"],\n media_id: metadata["#wa.referral.image.id"]\n };\n }\n } catch (err) {\n }\n return undefined;\n}\nfunction type__cart(reply) {\n if (reply.type.includes("x-whatsapp-order+json")) {\n return null;\n }\n return undefined;\n}\nfunction type__text(reply) {\n return reply.type === "text/plain" ? null : undefined;\n}\nfunction type__image(reply) {\n try {\n const _content = JSON.parse(reply.content);\n let _type = _content && _content.type && _content.type.toLowerCase() || "";\n if (_type.includes("image")) {\n return null;\n }\n } catch (err) {\n }\n return undefined;\n}\nfunction type__sticker(reply) {\n try {\n const _content = JSON.parse(reply.content);\n let _type = _content && _content.type && _content.type.toLowerCase() || "";\n if (_type.includes("sticker")) {\n return null;\n }\n } catch (err) {\n }\n return undefined;\n}\nfunction type__video(reply) {\n try {\n const _content = JSON.parse(reply.content);\n let _type = _content && _content.type && _content.type.toLowerCase() || "";\n if (_type.includes("video")) {\n return null;\n }\n } catch (err) {\n }\n return undefined;\n}\nfunction type__audio(reply) {\n try {\n const _content = JSON.parse(reply.content);\n let _type = _content && _content.type && _content.type.toLowerCase() || "";\n if (_type.includes("audio")) {\n return null;\n }\n } catch (err) {\n }\n return undefined;\n}\nfunction type__document(reply) {\n try {\n const _content = JSON.parse(reply.content);\n let _type = _content && _content.type && _content.type.toLowerCase() || "";\n if (_type.includes("application")) {\n return null;\n }\n } catch (err) {\n }\n return undefined;\n}\nfunction type__location(reply) {\n try {\n const _content = JSON.parse(reply.message).content;\n if (typeof _content === "string") {\n return undefined;\n }\n let _type = reply.type;\n if (_type.includes("location")) {\n return {\n latitude: _content.latitude,\n longitude: _content.longitude\n };\n }\n } catch (err) {\n }\n return undefined;\n}\nfunction model__cep(reply) {\n const text = reply.content;\n if (typeof text !== "string") {\n return undefined;\n }\n const cleaned = text.replace(/\\D/g, "");\n if (cleaned.length !== 8) {\n return undefined;\n }\n return {\n value: cleaned,\n pretty: `${cleaned.slice(0, 5)}-${cleaned.slice(5)}`\n };\n}\nfunction model__cpf(reply) {\n const text = reply.content;\n if (typeof text !== "string") {\n return undefined;\n }\n const cpf = text.replace(/\\D/g, "");\n if (cpf.length !== 11 || /^(\\d)\\1{10}$/.test(cpf)) {\n return undefined;\n }\n let sum = 0;\n let remainder;\n for (let i = 1; i <= 9; i++) {\n sum = sum + parseInt(cpf.substring(i - 1, i)) * (11 - i);\n }\n remainder = sum * 10 % 11;\n if (remainder === 10 || remainder === 11) {\n remainder = 0;\n }\n if (remainder !== parseInt(cpf.substring(9, 10))) {\n return undefined;\n }\n sum = 0;\n for (let i = 1; i <= 10; i++) {\n sum = sum + parseInt(cpf.substring(i - 1, i)) * (12 - i);\n }\n remainder = sum * 10 % 11;\n if (remainder === 10 || remainder === 11) {\n remainder = 0;\n }\n if (remainder !== parseInt(cpf.substring(10, 11))) {\n return undefined;\n }\n return {\n value: cpf,\n pretty: cpf.replace(/(\\d{3})(\\d{3})(\\d{3})(\\d{2})/, "$1.$2.$3-$4")\n };\n}\nfunction model__cnpj(reply) {\n const text = reply.content;\n if (typeof text !== "string") {\n return undefined;\n }\n const cnpj = text.replace(/[^a-zA-Z0-9]/g, "").toUpperCase();\n if (cnpj.length !== 14 || /^([A-Z0-9])\\1{13}$/.test(cnpj)) {\n return undefined;\n }\n const getVal = (c) => c.charCodeAt(0) - 48;\n const validateDigit = (base2, weights) => {\n let sum = 0;\n for (let i = 0; i < base2.length; i++) {\n sum += getVal(base2[i]) * weights[i];\n }\n const remainder = sum % 11;\n return remainder < 2 ? 0 : 11 - remainder;\n };\n const w1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];\n const w2 = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];\n const base = cnpj.substring(0, 12);\n const dv1 = validateDigit(base, w1);\n const dv2 = validateDigit(base + dv1, w2);\n if (dv1 !== getVal(cnpj[12]) || dv2 !== getVal(cnpj[13])) {\n return undefined;\n }\n return {\n value: cnpj,\n pretty: cnpj.replace(\n /^([A-Z0-9]{2})([A-Z0-9]{3})([A-Z0-9]{3})([A-Z0-9]{4})([A-Z0-9]{2})$/,\n "$1.$2.$3/$4-$5"\n )\n };\n}\nfunction model__birth_day(reply) {\n const text = reply.content;\n if (typeof text !== "string") {\n return undefined;\n }\n const match = text.trim().match(/^(\\d{1,2})[\\/.-](\\d{1,2})[\\/.-](\\d{4})$/);\n if (!match) return undefined;\n const day = parseInt(match[1], 10);\n const month = parseInt(match[2], 10);\n const year = parseInt(match[3], 10);\n const date = new Date(year, month - 1, day);\n if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {\n return undefined;\n }\n const dayStr = String(day).padStart(2, "0");\n const monthStr = String(month).padStart(2, "0");\n const yearStr = String(year);\n return {\n year: yearStr,\n month: monthStr,\n day: dayStr,\n pretty: `${dayStr}/${monthStr}/${yearStr}`\n };\n}\nfunction model__name(reply) {\n const text = reply.content;\n if (typeof text !== "string") {\n return undefined;\n }\n const cleaned = text.trim();\n const nameRegex = /^[a-zA-Z\\u00C0-\\u017F]+$/;\n if (nameRegex.test(cleaned) && cleaned.split(/\\s+/).length === 1) {\n const lowercase = cleaned.toLowerCase();\n const pretty = lowercase.charAt(0).toUpperCase() + lowercase.slice(1);\n return {\n value: lowercase,\n pretty\n };\n }\n return undefined;\n}\nfunction model__full_name(reply) {\n const text = reply.content;\n if (typeof text !== "string") {\n return undefined;\n }\n const cleaned = text.trim();\n const fullNameRegex = /^[a-zA-Z\\u00C0-\\u017F]+(?:\\s[a-zA-Z\\u00C0-\\u017F]+)+$/;\n if (fullNameRegex.test(cleaned)) {\n const names = cleaned.split(/\\s+/).map((n) => n.toLowerCase());\n if (names.length < 2) return undefined;\n const prettyNames = names.map(\n (name) => name.charAt(0).toUpperCase() + name.slice(1)\n );\n const first = prettyNames[0];\n const last = prettyNames.slice(1).join(" ");\n const pretty = prettyNames.join(" ");\n return {\n first,\n last,\n names,\n lowercase: cleaned.toLowerCase(),\n pretty\n };\n }\n return undefined;\n}\nfunction model__email(reply) {\n const text = reply.content;\n if (typeof text !== "string") {\n return undefined;\n }\n const emailRegex = /^(([^<>()[\\]\\\\.,;:\\s@"]+(\\.[^<>()[\\]\\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n const lowercasedText = text.toLowerCase().trim();\n if (emailRegex.test(lowercasedText)) {\n const parts = lowercasedText.split("@");\n return {\n host: parts[0],\n domain: parts[1],\n pretty: lowercasedText\n };\n }\n return undefined;\n}\nfunction model__phone(reply) {\n const text = reply.content;\n if (typeof text !== "string") {\n return undefined;\n }\n const cleaned = text.replace(/\\D/g, "");\n if (cleaned.length < 10 || cleaned.length > 15) {\n return undefined;\n }\n let country = "55";\n let remainingDigits = cleaned;\n if (cleaned.length >= 12) {\n const possibleCountry = cleaned.substring(0, cleaned.length - 10);\n if (possibleCountry.length >= 1 && possibleCountry.length <= 3) {\n country = possibleCountry;\n remainingDigits = cleaned.substring(possibleCountry.length);\n }\n }\n if (country === "55") {\n if (remainingDigits.length < 10 || remainingDigits.length > 11) {\n return undefined;\n }\n const ddd = remainingDigits.substring(0, 2);\n const phone = remainingDigits.substring(2);\n const dddNum = parseInt(ddd, 10);\n if (dddNum < 11 || dddNum > 99) {\n return undefined;\n }\n if (phone.length !== 8 && phone.length !== 9) {\n return undefined;\n }\n if (phone.length === 9 && phone[0] !== "9") {\n return undefined;\n }\n const phonePart1 = phone.length === 9 ? phone.substring(0, 5) : phone.substring(0, 4);\n const phonePart2 = phone.length === 9 ? phone.substring(5) : phone.substring(4);\n const local = `(${ddd}) ${phonePart1}-${phonePart2}`;\n const global = `+${country} ${local}`;\n return {\n value: country + ddd + phone,\n country,\n ddd,\n phone,\n pretty: { global, local }\n };\n }\n if (remainingDigits.length >= 10) {\n const ddd = remainingDigits.substring(0, 2);\n const phone = remainingDigits.substring(2);\n const phonePart1 = phone.substring(0, Math.ceil(phone.length / 2));\n const phonePart2 = phone.substring(Math.ceil(phone.length / 2));\n const local = `${ddd} ${phonePart1}-${phonePart2}`;\n const global = `+${country} ${local}`;\n return {\n value: country + ddd + phone,\n country,\n ddd,\n phone,\n pretty: { global, local }\n };\n }\n return undefined;\n}\nfunction model__debug(reply) {\n const text = reply.content;\n if (typeof text !== "string") {\n return undefined;\n }\n const match = text.trim().match(/^#debug\\s+(\\S+)$/i);\n if (match) {\n const [_, password] = match;\n return { password };\n }\n return undefined;\n}\nfunction model__goto(reply) {\n const text = reply.content;\n if (typeof text !== "string") {\n return undefined;\n }\n const match = text.trim().match(/^#goto\\s+(\\S+)\\s+(\\S+)(?:\\s+(\\S+))?$/i);\n if (match) {\n const [_, password, state, service] = match;\n return { password, state, service };\n }\n return undefined;\n}\nfunction model__ctwa(reply) {\n const message = reply.message;\n try {\n const { metadata } = JSON.parse(message || "{}");\n if (metadata && metadata["#wa.referral.source_id"]) {\n return {\n headline: metadata["#wa.referral.headline"],\n body: metadata["#wa.referral.body"],\n source_type: metadata["#wa.referral.source_type"],\n source_id: metadata["#wa.referral.source_id"],\n source_url: metadata["#wa.referral.source_url"],\n media_id: metadata["#wa.referral.image.id"]\n };\n }\n } catch (err) {\n }\n return undefined;\n}\nfunction model__flows(reply) {\n const message = reply.message;\n try {\n return JSON.parse(\n JSON.parse(message).metadata["#wa.interactive.nfm_reply.json_response"]\n );\n } catch (err) {\n }\n return undefined;\n}\nfunction model__cart(reply) {\n if (reply.type.includes("x-whatsapp-order+json")) {\n return null;\n }\n return undefined;\n}\nfunction model__car_plate(reply) {\n const text = reply.content;\n const cleaned = text.replace(/-/g, "").trim().toUpperCase();\n const carPlateRegex = /^[A-Z]{3}[\\d][A-Z\\d][\\d]{2}$/;\n if (carPlateRegex.test(cleaned)) {\n const pretty = `${cleaned.substring(0, 3)}-${cleaned.substring(3)}`;\n return {\n value: cleaned,\n pretty\n };\n }\n return undefined;\n}\nfunction input__process(reply, models) {\n let content = reply.content;\n let model = undefined;\n let payload = null;\n let type = "TEXT";\n const _types = [\n "INACTIVITY",\n "FLOWS",\n "CTWA",\n "CART",\n "TEXT",\n "IMAGE",\n "STICKER",\n "VIDEO",\n "AUDIO",\n "DOCUMENT",\n "LOCATION"\n ];\n const typeExec = {\n ["INACTIVITY"]: type__inactivity,\n ["FLOWS"]: type__flows,\n ["CTWA"]: type__ctwa,\n ["CART"]: type__cart,\n ["TEXT"]: type__text,\n ["IMAGE"]: type__image,\n ["STICKER"]: type__sticker,\n ["VIDEO"]: type__video,\n ["AUDIO"]: type__audio,\n ["DOCUMENT"]: type__document,\n ["LOCATION"]: type__location\n };\n const modelExec = {\n ["GOTO"]: model__goto,\n ["DEBUG"]: model__debug,\n ["CEP"]: model__cep,\n ["CPF"]: model__cpf,\n ["CNPJ"]: model__cnpj,\n ["BIRTH_DAY"]: model__birth_day,\n ["NAME"]: model__name,\n ["FULL_NAME"]: model__full_name,\n ["EMAIL"]: model__email,\n ["PHONE"]: model__phone,\n ["CAR_PLATE"]: model__car_plate,\n ["CTWA"]: model__ctwa,\n ["FLOWS"]: model__flows,\n ["CART"]: model__cart,\n ["LOCATION"]: type__location\n };\n type = _types.find((input_type) => typeExec[input_type](reply) !== undefined) || "TEXT";\n payload = typeExec[type](reply);\n const _models = [\n "GOTO",\n "DEBUG",\n ...models || []\n ];\n const MODELS = [\n "GOTO",\n "DEBUG",\n "CEP",\n "CPF",\n "CNPJ",\n "BIRTH_DAY",\n "NAME",\n "FULL_NAME",\n "EMAIL",\n "PHONE",\n "CAR_PLATE",\n "CTWA",\n "FLOWS",\n "CART",\n "LOCATION"\n ];\n const invalids = _models.filter((model2) => !MODELS.includes(model2));\n if (invalids.length > 0) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `Invalid model \'${invalids.join(", ")}\'. Must be one of: ${MODELS.join(\n ", "\n )}`,\n { goto: null }\n );\n }\n model = _models.find(\n (input_model) => modelExec[input_model](reply) !== undefined\n );\n if (model) {\n payload = modelExec[model](reply);\n }\n if (reply.payload) {\n payload = reply.payload;\n }\n return {\n content,\n type,\n payload,\n model\n };\n}\nfunction input__content(text) {\n return String(text).trim().toLowerCase().normalize("NFD").replace(/[\\u0300-\\u036f]/g, "").replace(/[^a-z0-9\\s]/g, "");\n}\nfunction reply__intent(reply, intentGroup, config) {\n const { threshold } = config;\n let minScore = threshold && threshold.minScore ? threshold.minScore : 0.75;\n let intent = null;\n let goto = undefined;\n let payload = null;\n for (const intentSpec of intentGroup.intents) {\n const { type } = intentSpec;\n if (type === "fuzzy") {\n const _intent = intent__fuzzy(reply, intentSpec, intentGroup);\n if (_intent && (!intent || intent.score < _intent.score)) {\n intent = _intent;\n goto = intentSpec.goto;\n payload = intentSpec.payload || null;\n continue;\n }\n }\n if (type === "regex") {\n const _intent = intent__regex(reply, intentSpec, intentGroup);\n if (_intent) {\n intent = _intent;\n goto = intentSpec.goto;\n payload = intentSpec.payload || null;\n break;\n }\n }\n if (type === "static") {\n const _intent = intent__static(reply, intentSpec, intentGroup);\n if (_intent) {\n intent = _intent;\n goto = intentSpec.goto;\n payload = intentSpec.payload || null;\n break;\n }\n }\n }\n if (intent && intent.type === "fuzzy" && intent.score < minScore) {\n intent = null;\n goto = undefined;\n }\n return [intent, goto, payload];\n}\nfunction intent__regex(reply, intentSpec, intentGroup) {\n const { scope, event } = intentGroup;\n const { id, patterns, label } = intentSpec;\n let intent = null;\n const score = 0;\n const type = "regex";\n try {\n const normalized = input__content(reply.content);\n for (const pattern of patterns || []) {\n if (new RegExp(pattern, "i").test(reply.content) || new RegExp(pattern, "i").test(normalized)) {\n intent = {\n id,\n type,\n scope,\n label,\n event,\n pattern,\n score\n };\n }\n }\n } catch (err) {\n throw new DwnError(\n "RUNTIME_ERROR",\n `Error processing regex intent ${intentSpec.id}, error: ${err.message}`,\n { goto: null }\n );\n }\n return intent;\n}\nfunction intent__fuzzy(reply, intentSpec, intentGroup) {\n const { scope, event } = intentGroup;\n const { id, patterns, label } = intentSpec;\n const content = input__content(reply.content);\n const type = "fuzzy";\n let intent = null;\n let highest = 0;\n function similarity_score(a, b) {\n const maxLen = Math.max(a.length, b.length);\n if (maxLen === 0) return 1;\n return 1 - levenshtein_distance(a, b) / maxLen;\n }\n function levenshtein_distance(a, b) {\n const matrix = [];\n for (let i = 0; i <= b.length; i++) matrix[i] = [i];\n for (let j = 0; j <= a.length; j++) matrix[0][j] = j;\n for (let i = 1; i <= b.length; i++) {\n for (let j = 1; j <= a.length; j++) {\n if (b[i - 1] === a[j - 1]) {\n matrix[i][j] = matrix[i - 1][j - 1];\n } else {\n matrix[i][j] = Math.min(\n matrix[i - 1][j - 1] + 1,\n matrix[i][j - 1] + 1,\n matrix[i - 1][j] + 1\n );\n }\n }\n }\n return matrix[b.length][a.length];\n }\n for (const pattern of patterns || []) {\n const example = input__content(pattern);\n const score = similarity_score(content, example);\n if (score > highest) {\n highest = score;\n intent = {\n id,\n type,\n scope,\n label,\n event,\n pattern,\n score\n };\n }\n }\n return intent;\n}\nfunction intent__static(reply, intentSpec, intentGroup) {\n const { scope, event } = intentGroup;\n const { id, patterns, label } = intentSpec;\n let intent = null;\n const score = 0;\n const type = "static";\n try {\n let words = patterns || [];\n if (words.includes(reply.content)) {\n intent = {\n id,\n type,\n scope,\n label,\n event,\n pattern: reply.content,\n score\n };\n }\n } catch (err) {\n throw new DwnError(\n "RUNTIME_ERROR",\n `Error processing regex intent ${intentSpec.id}, error: ${err.message}`,\n { goto: null }\n );\n }\n return intent;\n}\n/**\n * @imports\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n */\nvar DwnError = class _DwnError extends Error {\n /**\n * Creates a new DwnError instance.\n *\n * @param {string} type The error type identifier (e.g., "VALIDATION_ERROR", "SCRIPT_ERROR")\n * @param {string} description Human-readable description of what went wrong\n * @param {{message?: string, messages?: string[], stack?: string, goto?: State | null, state?: State, at?: string, intent?: string | null, content?: string, recurrence?: ErrorRecurrence, code?: string | null, status?: FINALIZATION_STATUS}} [extras] Optional additional error context and metadata:\n * - `message`: Primary error message for user display\n * - `messages`: Array of error messages for different contexts\n * - `stack`: Stack trace or execution context information\n * - `goto`: Target state to redirect to on error (null means terminate)\n * - `state`: Flow state where the error occurred\n * - `at`: Location or context where the error occurred\n * - `intent`: Associated intent that caused the error\n * - `content`: Additional error content or context\n * - `recurrence`: Information about error recurrence patterns\n * - `code`: Error code for programmatic error handling\n * - `status`: Finalization status indicating how the error was resolved\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid input provided");\n *\n * const contextError = new DwnError("SCRIPT_ERROR", "Script execution failed", {\n * state: { id: "state-123", service: "main" },\n * intent: "user-input",\n * content: "invalid data",\n * messages: ["First attempt failed", "Retry failed"],\n * goto: { id: "error-handler", service: "main" }\n * });\n * ```\n */\n constructor(type, description, extras) {\n super();\n this.name = "DwnError";\n const _extras = _DwnError.enforceExtras(extras);\n this.type = type;\n this.description = description;\n this.at = _extras.at;\n this.content = _extras.content;\n this.state = _extras.state;\n this.recurrence = _extras.recurrence;\n this.goto = _extras.goto;\n this.message = _extras.message || undefined;\n this.messages = _extras.messages || [];\n this.intent = _extras.intent || undefined;\n this.code = _extras.code || undefined;\n this.status = _extras.status || undefined;\n this.stack = _extras.stack || undefined;\n if (!this.stack) {\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, _DwnError);\n }\n }\n }\n /**\n * Creates a DwnError instance from a serialized error string.\n *\n * Parses a DWN error string in the format "TYPE -|- DESCRIPTION -|- EXTRAS_JSON"\n * and reconstructs the original DwnError instance.\n *\n * @param {string} dwnErrorString Serialized error string from toString() method\n * @returns {DwnError | undefined} DwnError instance or undefined if parsing fails\n *\n * @example\n * ```typescript\n * const errorString = "SCRIPT_ERROR -|- Execution failed -|- {...}";\n * const error = DwnError.fromDwnError(errorString);\n * ```\n */\n static fromDwnError(dwnErrorString) {\n if (!dwnErrorString) return undefined;\n const parts = dwnErrorString.split("-|-");\n let type = parts.shift();\n if (!type) {\n return undefined;\n }\n type = type.trim();\n let description = parts.shift() || "";\n if (description) {\n description = description.trim();\n }\n let extras = undefined;\n try {\n extras = JSON.parse(parts.shift() || "{}");\n } catch (e) {\n }\n if (extras) {\n return new _DwnError(type, description, extras);\n }\n return new _DwnError(type, description);\n }\n /**\n * Creates a DwnError instance from a JSON object.\n *\n * Converts a generic Error object or JSON representation into a properly\n * structured DwnError instance with all required properties.\n *\n * @param {Error} data Error object or JSON data to convert\n * @returns {DwnError} New DwnError instance\n *\n * @example\n * ```typescript\n * const jsonData = { type: "API_ERROR", description: "Request failed" };\n * const error = DwnError.fromJson(jsonData);\n * ```\n */\n static fromJson(data) {\n const extras = _DwnError.enforceExtras(data);\n return new _DwnError(data.type, data.description, extras);\n }\n /**\n * Normalizes and validates error extras properties.\n *\n * Ensures all optional properties have default values and validates the structure\n * of the extras object. Used internally to maintain consistency across error instances.\n *\n * @param {DwnError | DwnErrorExtras} [entity] Error entity or extras object to normalize\n * @returns {Required<DwnErrorExtras>} Normalized extras object with all required properties\n *\n * @internal\n */\n static enforceExtras(entity) {\n if (!entity) entity = {};\n const extras = {};\n extras.message = entity.message || "";\n extras.messages = entity.messages || [];\n extras.stack = entity.stack || "";\n extras.goto = entity.goto;\n extras.state = entity.state || { id: "", service: "" };\n extras.at = entity.at || (new Date()).toISOString();\n extras.intent = entity.intent || "";\n extras.content = entity.content || "";\n extras.recurrence = entity.recurrence || { type: 1, state: 1, combined: 1 };\n extras.code = entity.code || undefined;\n extras.status = entity.status || undefined;\n return extras;\n }\n /**\n * Serializes the error to a string format.\n *\n * Converts the DwnError instance into a parseable string format using the pattern\n * "TYPE -|- DESCRIPTION -|- EXTRAS_JSON" for storage or transmission.\n *\n * @returns {string} Serialized error string\n *\n * @example\n * ```typescript\n * const error = new DwnError("API_ERROR", "Request failed");\n * const serialized = error.toString();\n * // "API_ERROR -|- Request failed -|- {...}"\n * ```\n */\n toString() {\n const extras = JSON.stringify(_DwnError.enforceExtras(this));\n return `${this.type} -|- ${this.description} -|- ${extras}`;\n }\n /**\n * Converts the error to a JSON object.\n *\n * Serializes all error properties into a plain JavaScript object suitable\n * for JSON serialization, API responses, or logging.\n *\n * @returns {Error} Plain object representation of the error\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid data");\n * const json = error.toJson();\n * console.log(JSON.stringify(json, null, 2));\n * ```\n */\n toJson() {\n return {\n type: this.type,\n at: this.at,\n description: this.description,\n message: this.message,\n messages: this.messages || [],\n stack: this.stack || "",\n intent: this.intent,\n content: this.content,\n goto: this.goto,\n state: this.state,\n recurrence: this.recurrence\n };\n }\n};\nvar SYSTEM_DWN_ERRORS = [\n "RUNTIME_ERROR",\n "MISCONFIGURATION_ERROR"\n];\n\n\nfunction enforceState(state, currentService, states) {\n if (!state && typeof state !== "string") {\n return state;\n }\n const id = typeof state === "string" ? state : state.id;\n if (!id) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `State ${JSON.stringify(state)} must have \'id\' property.`\n );\n }\n const key = `${id}@${currentService}`;\n let service = typeof state === "string" ? currentService : state.service;\n if (!service) {\n service = currentService;\n }\n let name = typeof state === "string" ? "" : state.name;\n if (!name) {\n name = states[key] || undefined;\n }\n return { id, service, name };\n}\n';
|
|
89
|
+
return {
|
|
90
|
+
$id,
|
|
91
|
+
$typeOfContent: "",
|
|
92
|
+
type: "ExecuteScriptV2",
|
|
93
|
+
$title: "DWN Update DWN",
|
|
94
|
+
settings: {
|
|
95
|
+
function: "dwnRun",
|
|
96
|
+
source,
|
|
97
|
+
inputVariables: [
|
|
98
|
+
Feature_1.Feature.VARIABLES.DWN,
|
|
99
|
+
Feature_1.Feature.VARIABLES.CORE,
|
|
100
|
+
Feature_1.Feature.VARIABLES.CONFIG,
|
|
101
|
+
Feature_1.Feature.VARIABLES.STATES,
|
|
102
|
+
Feature_1.Feature.VARIABLES.ERROR,
|
|
103
|
+
Feature_1.Feature.VARIABLES.LIST_CONFIG,
|
|
104
|
+
"tunnel.originator",
|
|
105
|
+
"contact.serialized",
|
|
106
|
+
],
|
|
107
|
+
outputVariable: Feature_1.Feature.VARIABLES.DWN,
|
|
108
|
+
},
|
|
109
|
+
conditions: [
|
|
110
|
+
{
|
|
111
|
+
values: [],
|
|
112
|
+
source: "context",
|
|
113
|
+
comparison: "notExists",
|
|
114
|
+
variable: Feature_1.Feature.VARIABLES.BYPASS,
|
|
115
|
+
},
|
|
116
|
+
],
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
exports.updateDwnScript = updateDwnScript;
|
|
120
|
+
const updateStatesScript = (script, states) => {
|
|
121
|
+
const _statesEntries = Object.entries(states)
|
|
122
|
+
.map(([id, name]) => `"${id}": ${JSON.stringify(name)}`)
|
|
123
|
+
.join(",\n\t\t");
|
|
124
|
+
const _statesPattern = /let _states = \{[\s\S]*?\};/;
|
|
125
|
+
const _statesReplacement = `let _states = {\n\t\t${_statesEntries}\n\t};`;
|
|
126
|
+
script.settings.source = script.settings.source.replace(_statesPattern, _statesReplacement);
|
|
127
|
+
return script;
|
|
128
|
+
};
|
|
129
|
+
exports.updateStatesScript = updateStatesScript;
|
|
130
|
+
const createErrorScript = ($id) => {
|
|
131
|
+
const source = '/**\n * @author [Beuren Bechlin] <beuren.bechlin@dawntech.dev>\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n *\n * ---\n *\n * This software is the proprietary property of Dawntech.\n * Possession, use, duplication, or dissemination of this software is strictly\n * prohibited unless you have received prior written permission from\n * Dawntech.\n *\n * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nasync function dwnRun(dwnStr, coreStr, configStr, statesStr, errorStr) {\n dwnStr = dwnStr || "";\n coreStr = coreStr || "";\n configStr = configStr || "";\n statesStr = statesStr || "";\n errorStr = errorStr || "";\n let warnings = [];\n let error = DwnError.fromDwnError(errorStr);\n let core = null;\n let dwn = null;\n let states = {};\n let config = null;\n try {\n if (error && SYSTEM_DWN_ERRORS.includes(error.type)) {\n throw error;\n }\n try {\n core = JSON.parse(coreStr);\n } catch (err) {\n warnings.push(`[create-error] Unexpected core JSON ${String(err)}`);\n throw new Error(`core parsing ${String(err)}`);\n }\n warnings = core.warnings;\n try {\n dwn = JSON.parse(dwnStr);\n } catch (err) {\n warnings.push(`[create-error] Unexpected dwn JSON ${String(err)}`);\n throw new Error(`dwn parsing ${String(err)}`);\n }\n try {\n states = JSON.parse(statesStr);\n } catch (err) {\n warnings.push(`[create-error] Unexpected states JSON ${String(err)}`);\n throw new Error(`states parsing ${String(err)}`);\n }\n try {\n config = JSON.parse(configStr);\n } catch (err) {\n warnings.push(`[create-error] Unexpected config JSON ${String(err)}`);\n throw new Error(`config parsing ${String(err)}`);\n }\n let type = config.error.type;\n let intent = dwn.intent ? dwn.intent.id : null;\n let description = undefined;\n let messages = config.error.messages || [];\n let state = enforceState(\n "{{state.previous.id}}",\n core.service,\n states\n );\n let goto = null;\n if (error) {\n type = error.type;\n description = error.description;\n messages = error.messages || [];\n if (error.message) {\n messages = [error.message];\n }\n if (error.goto === undefined) {\n goto = state;\n } else {\n goto = error.goto;\n }\n } else {\n error = new DwnError(type, "Default error");\n description = "Default error";\n goto = config.error.goto === undefined ? state : config.error.goto;\n }\n if (intent === "CHECKPOINT_BACK") {\n const checkpointIndex = core.checkpoints.findIndex(\n (checkpoint) => checkpoint.id === core.state.id && checkpoint.service === core.service\n );\n if (checkpointIndex >= 0) {\n core.checkpoints.splice(0, checkpointIndex + 1);\n }\n } else if (core.checkpoint) {\n if (!(dwn.intent && dwn.intent.id && dwn.intent.scope === "prepare")) {\n core.checkpoints.splice(0, 1);\n }\n }\n if (dwn.intent && dwn.intent.scope === "stack") {\n const stackIndex = core.intents.stack.findIndex(\n (intentsGroup) => intentsGroup.id === dwn.intent.event\n );\n if (stackIndex >= 0) {\n core.intents.stack.splice(0, stackIndex + 1);\n }\n }\n if (type === "PROPAGATE") {\n throw DwnError.fromJson(dwn.error);\n }\n if (type === "RUNTIME_ERROR") {\n throw error;\n }\n const recurrence = error.recurrence;\n const lastError = core.errors[0];\n if (lastError && recurrence.combined > 0) {\n if (lastError.state.id == state.id) {\n recurrence.state = lastError.recurrence.state + 1;\n }\n if (lastError.type == type) {\n recurrence.type = lastError.recurrence.type + 1;\n }\n recurrence.combined = Math.min(recurrence.state, recurrence.type);\n }\n error.type = type;\n error.at = dwn.calendar.datetime;\n error.content = dwn.input.content;\n error.state = state;\n error.recurrence = recurrence;\n error.goto = enforceState(goto, core.service, states);\n error.intent = intent;\n error.description = description;\n error.message = error.message || undefined;\n if (messages.length === 0 && error.intent && error.intent in config.messages.intent) {\n messages = config.messages.intent[error.intent];\n }\n if (messages.length === 0 && dwn.input.type in config.messages.type) {\n messages = config.messages.type[dwn.input.type];\n }\n if (messages.length === 0 && error.type in config.messages.error) {\n messages = config.messages.error[error.type];\n }\n error.messages = messages;\n } catch (err) {\n if (!(err instanceof DwnError)) {\n const description = `[create-error] Unexpected error ${String(err)}`;\n const stack = err.stack || "";\n err = new DwnError("RUNTIME_ERROR", description, {\n stack,\n goto: null\n });\n }\n error = err;\n } finally {\n if (!core || typeof core !== "object") {\n core = {};\n }\n if (error) {\n core.error = error.toJson();\n }\n core.warnings = warnings;\n coreStr = JSON.stringify(core);\n }\n if (error) {\n await context.deleteVariableAsync("dwnError");\n }\n return coreStr;\n}\n/**\n * @imports\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n */\nvar DwnError = class _DwnError extends Error {\n /**\n * Creates a new DwnError instance.\n *\n * @param {string} type The error type identifier (e.g., "VALIDATION_ERROR", "SCRIPT_ERROR")\n * @param {string} description Human-readable description of what went wrong\n * @param {{message?: string, messages?: string[], stack?: string, goto?: State | null, state?: State, at?: string, intent?: string | null, content?: string, recurrence?: ErrorRecurrence, code?: string | null, status?: FINALIZATION_STATUS}} [extras] Optional additional error context and metadata:\n * - `message`: Primary error message for user display\n * - `messages`: Array of error messages for different contexts\n * - `stack`: Stack trace or execution context information\n * - `goto`: Target state to redirect to on error (null means terminate)\n * - `state`: Flow state where the error occurred\n * - `at`: Location or context where the error occurred\n * - `intent`: Associated intent that caused the error\n * - `content`: Additional error content or context\n * - `recurrence`: Information about error recurrence patterns\n * - `code`: Error code for programmatic error handling\n * - `status`: Finalization status indicating how the error was resolved\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid input provided");\n *\n * const contextError = new DwnError("SCRIPT_ERROR", "Script execution failed", {\n * state: { id: "state-123", service: "main" },\n * intent: "user-input",\n * content: "invalid data",\n * messages: ["First attempt failed", "Retry failed"],\n * goto: { id: "error-handler", service: "main" }\n * });\n * ```\n */\n constructor(type, description, extras) {\n super();\n this.name = "DwnError";\n const _extras = _DwnError.enforceExtras(extras);\n this.type = type;\n this.description = description;\n this.at = _extras.at;\n this.content = _extras.content;\n this.state = _extras.state;\n this.recurrence = _extras.recurrence;\n this.goto = _extras.goto;\n this.message = _extras.message || undefined;\n this.messages = _extras.messages || [];\n this.intent = _extras.intent || undefined;\n this.code = _extras.code || undefined;\n this.status = _extras.status || undefined;\n this.stack = _extras.stack || undefined;\n if (!this.stack) {\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, _DwnError);\n }\n }\n }\n /**\n * Creates a DwnError instance from a serialized error string.\n *\n * Parses a DWN error string in the format "TYPE -|- DESCRIPTION -|- EXTRAS_JSON"\n * and reconstructs the original DwnError instance.\n *\n * @param {string} dwnErrorString Serialized error string from toString() method\n * @returns {DwnError | undefined} DwnError instance or undefined if parsing fails\n *\n * @example\n * ```typescript\n * const errorString = "SCRIPT_ERROR -|- Execution failed -|- {...}";\n * const error = DwnError.fromDwnError(errorString);\n * ```\n */\n static fromDwnError(dwnErrorString) {\n if (!dwnErrorString) return undefined;\n const parts = dwnErrorString.split("-|-");\n let type = parts.shift();\n if (!type) {\n return undefined;\n }\n type = type.trim();\n let description = parts.shift() || "";\n if (description) {\n description = description.trim();\n }\n let extras = undefined;\n try {\n extras = JSON.parse(parts.shift() || "{}");\n } catch (e) {\n }\n if (extras) {\n return new _DwnError(type, description, extras);\n }\n return new _DwnError(type, description);\n }\n /**\n * Creates a DwnError instance from a JSON object.\n *\n * Converts a generic Error object or JSON representation into a properly\n * structured DwnError instance with all required properties.\n *\n * @param {Error} data Error object or JSON data to convert\n * @returns {DwnError} New DwnError instance\n *\n * @example\n * ```typescript\n * const jsonData = { type: "API_ERROR", description: "Request failed" };\n * const error = DwnError.fromJson(jsonData);\n * ```\n */\n static fromJson(data) {\n const extras = _DwnError.enforceExtras(data);\n return new _DwnError(data.type, data.description, extras);\n }\n /**\n * Normalizes and validates error extras properties.\n *\n * Ensures all optional properties have default values and validates the structure\n * of the extras object. Used internally to maintain consistency across error instances.\n *\n * @param {DwnError | DwnErrorExtras} [entity] Error entity or extras object to normalize\n * @returns {Required<DwnErrorExtras>} Normalized extras object with all required properties\n *\n * @internal\n */\n static enforceExtras(entity) {\n if (!entity) entity = {};\n const extras = {};\n extras.message = entity.message || "";\n extras.messages = entity.messages || [];\n extras.stack = entity.stack || "";\n extras.goto = entity.goto;\n extras.state = entity.state || { id: "", service: "" };\n extras.at = entity.at || (new Date()).toISOString();\n extras.intent = entity.intent || "";\n extras.content = entity.content || "";\n extras.recurrence = entity.recurrence || { type: 1, state: 1, combined: 1 };\n extras.code = entity.code || undefined;\n extras.status = entity.status || undefined;\n return extras;\n }\n /**\n * Serializes the error to a string format.\n *\n * Converts the DwnError instance into a parseable string format using the pattern\n * "TYPE -|- DESCRIPTION -|- EXTRAS_JSON" for storage or transmission.\n *\n * @returns {string} Serialized error string\n *\n * @example\n * ```typescript\n * const error = new DwnError("API_ERROR", "Request failed");\n * const serialized = error.toString();\n * // "API_ERROR -|- Request failed -|- {...}"\n * ```\n */\n toString() {\n const extras = JSON.stringify(_DwnError.enforceExtras(this));\n return `${this.type} -|- ${this.description} -|- ${extras}`;\n }\n /**\n * Converts the error to a JSON object.\n *\n * Serializes all error properties into a plain JavaScript object suitable\n * for JSON serialization, API responses, or logging.\n *\n * @returns {Error} Plain object representation of the error\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid data");\n * const json = error.toJson();\n * console.log(JSON.stringify(json, null, 2));\n * ```\n */\n toJson() {\n return {\n type: this.type,\n at: this.at,\n description: this.description,\n message: this.message,\n messages: this.messages || [],\n stack: this.stack || "",\n intent: this.intent,\n content: this.content,\n goto: this.goto,\n state: this.state,\n recurrence: this.recurrence\n };\n }\n};\nvar SYSTEM_DWN_ERRORS = [\n "RUNTIME_ERROR",\n "MISCONFIGURATION_ERROR"\n];\n\n\nfunction enforceState(state, currentService, states) {\n if (!state && typeof state !== "string") {\n return state;\n }\n const id = typeof state === "string" ? state : state.id;\n if (!id) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `State ${JSON.stringify(state)} must have \'id\' property.`\n );\n }\n const key = `${id}@${currentService}`;\n let service = typeof state === "string" ? currentService : state.service;\n if (!service) {\n service = currentService;\n }\n let name = typeof state === "string" ? "" : state.name;\n if (!name) {\n name = states[key] || undefined;\n }\n return { id, service, name };\n}\n';
|
|
132
|
+
return {
|
|
133
|
+
$id,
|
|
134
|
+
$typeOfContent: "",
|
|
135
|
+
type: "ExecuteScriptV2",
|
|
136
|
+
$title: "DWN Create Error",
|
|
137
|
+
settings: {
|
|
138
|
+
function: "dwnRun",
|
|
139
|
+
source,
|
|
140
|
+
inputVariables: [
|
|
141
|
+
Feature_1.Feature.VARIABLES.DWN,
|
|
142
|
+
Feature_1.Feature.VARIABLES.CORE,
|
|
143
|
+
Feature_1.Feature.VARIABLES.CONFIG,
|
|
144
|
+
Feature_1.Feature.VARIABLES.STATES,
|
|
145
|
+
Feature_1.Feature.VARIABLES.ERROR,
|
|
146
|
+
],
|
|
147
|
+
outputVariable: Feature_1.Feature.VARIABLES.CORE,
|
|
148
|
+
},
|
|
149
|
+
conditions: [],
|
|
150
|
+
};
|
|
151
|
+
};
|
|
152
|
+
exports.createErrorScript = createErrorScript;
|
|
153
|
+
const SYSTEM_ERROR_MESSAGES = {
|
|
154
|
+
pt_br: {
|
|
155
|
+
[Feature_1.Feature.PREDEFINED_ERRORS.RUNTIME_ERROR]: "Desculpe, houve um erro inesperado. Por favor, tente novamente mais tarde.",
|
|
156
|
+
[Feature_1.Feature.PREDEFINED_ERRORS.MISCONFIGURATION_ERROR]: "Desculpe, houve uma falha inesperada. Por favor, tente novamente mais tarde.",
|
|
157
|
+
},
|
|
158
|
+
es: {
|
|
159
|
+
[Feature_1.Feature.PREDEFINED_ERRORS.RUNTIME_ERROR]: "Lo sentimos, ocurrió un error inesperado. Por favor, inténtalo de nuevo más tarde.",
|
|
160
|
+
[Feature_1.Feature.PREDEFINED_ERRORS.MISCONFIGURATION_ERROR]: "Lo sentimos, ocurrió un fallo inesperado. Por favor, inténtalo de nuevo más tarde.",
|
|
161
|
+
},
|
|
162
|
+
en: {
|
|
163
|
+
[Feature_1.Feature.PREDEFINED_ERRORS.RUNTIME_ERROR]: "Sorry, an unexpected error occurred. Please try again later.",
|
|
164
|
+
[Feature_1.Feature.PREDEFINED_ERRORS.MISCONFIGURATION_ERROR]: "Sorry, an unexpected failure occurred. Please try again later.",
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
const processErrorScript = ($id, language, currentService, mainService) => {
|
|
168
|
+
let source = '/**\n * @author [Beuren Bechlin] <beuren.bechlin@dawntech.dev>\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n *\n * ---\n *\n * This software is the proprietary property of Dawntech.\n * Possession, use, duplication, or dissemination of this software is strictly\n * prohibited unless you have received prior written permission from\n * Dawntech.\n *\n * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nasync function processError(error, errors, dwn, core, config) {\n if (error.type === "INACTIVITY" && config.messages.error["INACTIVITY"] && config.messages.error["INACTIVITY"].length > 1) {\n const isFinal = error.recurrence.combined === config.messages.error["INACTIVITY"].length;\n if (!isFinal) {\n error.description = "Intermidiate inactivity message, waiting for user.";\n error.goto = error.state;\n } else {\n error.description = "Final inactivity message, closing conversation.";\n error.goto = null;\n }\n error.message = rotateMessages(\n config.messages.error["INACTIVITY"],\n errors\n );\n return error;\n }\n if (error.type !== "INTENT" && error.recurrence.combined >= 3) {\n const messages = config.messages.error["RECURRENT_ERROR"] || [];\n error.type = "RECURRENT_ERROR";\n error.message = rotateMessages(messages, errors);\n error.description = "Recurrence detected";\n error.goto = null;\n return error;\n }\n switch (error.type) {\n // Exemplo de tratamento de erro específico\n case "BLOCKED_CONTACT":\n error.message = rotateMessages(\n [\n "Desculpe, você não pode interagir com este serviço. Entre em contato com o suporte para mais informações.",\n "Desculpe, você foi bloqueado de interagir com este serviço. Entre em contato com o suporte para mais informações."\n ],\n errors\n );\n error.goto = null;\n break;\n }\n return error;\n}\nfunction rotateMessages(messages, errors) {\n if (!messages || !Array.isArray(messages) || messages.length === 0) {\n return undefined;\n }\n if (!errors || !Array.isArray(errors) || errors.length === 0) {\n return messages[0] || undefined;\n }\n const lastErrorMessage = errors[0] ? errors[0].message : "";\n const lastMessageIndex = messages.findIndex((m) => m === lastErrorMessage);\n return messages[(lastMessageIndex + 1) % messages.length] || undefined;\n}\nasync function dwnRun(dwnStr, coreStr, configStr, statesStr, errorStr) {\n dwnStr = dwnStr || "";\n coreStr = coreStr || "";\n configStr = configStr || "";\n statesStr = statesStr || "";\n errorStr = errorStr || "";\n let service = {\n current: "{{current_service}}",\n main: "{{main_service}}"\n };\n let propagate = service.current !== service.main ? service.main : undefined;\n let warnings = [];\n let error = new DwnError(\n "RUNTIME_ERROR",\n "Default error",\n { goto: null }\n );\n let core = null;\n let dwn = null;\n let states = {};\n let config = null;\n try {\n try {\n core = JSON.parse(coreStr);\n } catch (err) {\n warnings.push(`[process-error] Unexpected core JSON ${String(err)}`);\n throw new Error(`core parsing ${String(err)}`);\n }\n warnings = core.warnings;\n try {\n dwn = JSON.parse(dwnStr);\n } catch (err) {\n warnings.push(`[process-error] Unexpected dwn JSON ${String(err)}`);\n throw new Error(`dwn parsing ${String(err)}`);\n }\n try {\n states = JSON.parse(statesStr);\n } catch (err) {\n warnings.push(`[process-error] Unexpected states JSON ${String(err)}`);\n throw new Error(`states parsing ${String(err)}`);\n }\n if (!core.error) {\n warnings.push(`[process-error] core error is not defined`);\n throw new Error("core error is not defined");\n }\n try {\n const error2 = DwnError.fromJson(core.error);\n if (!error2) throw new Error("core error is not defined");\n if (error2 && SYSTEM_DWN_ERRORS.includes(error2.type)) {\n throw error2;\n }\n config = JSON.parse(configStr);\n } catch (error2) {\n warnings.push(`[process-error] Unexpected error ${String(error2)}`);\n throw error2;\n }\n service = config.service;\n propagate = core.propagate;\n let _error = core.error;\n _error.message = rotateMessages(_error.messages, core.errors);\n _error = await processError(_error, core.errors, dwn, core, config);\n _error.goto = enforceState(_error.goto, service.current, states);\n core.errors = core.errors.slice(0, config.stackSize.errors);\n core.errors.unshift(_error);\n error = DwnError.fromJson(_error);\n } catch (err) {\n if (!(err instanceof DwnError)) {\n const description = `[process-error] Unexpected error ${String(err)}`;\n const stack = err.stack || "";\n err = new DwnError("RUNTIME_ERROR", description, {\n stack,\n goto: null\n });\n }\n error = err;\n } finally {\n if (!dwn || typeof dwn !== "object") {\n dwn = {};\n }\n if (!core || typeof core !== "object") {\n core = {};\n }\n core.propagate = propagate;\n if (SYSTEM_DWN_ERRORS.includes(error.type)) {\n error = systemErrorRecovery(error, service);\n }\n if (error.code && error.message) {\n error.message = error.message.replace("{{code}}", error.code);\n }\n if (error.goto) {\n if (!error.goto.service) {\n error.goto.service = service.current;\n }\n if (!error.goto.id) {\n error.goto.id = "onboarding";\n }\n if (error.goto.service !== service.current) {\n core.redirect = true;\n }\n errorStr = "";\n } else {\n if (core.propagate) {\n core.redirect = true;\n errorStr = "PROPAGATE";\n }\n error.goto = undefined;\n }\n core.error = error.toJson();\n dwn.error = error.toJson();\n core.warnings = warnings;\n if (core.warnings.length > 0) {\n dwn.warnings = core.warnings.join("\\n");\n }\n dwnStr = JSON.stringify(dwn);\n }\n if (errorStr === "PROPAGATE") {\n await context.setVariableAsync("dwnError", errorStr);\n }\n if (core && typeof core === "object") {\n await context.setVariableAsync("dwnCore", JSON.stringify(core));\n }\n return dwnStr;\n}\nfunction systemErrorRecovery(error, services) {\n const messages = {\n ["RUNTIME_ERROR"]: "{{runtime_message}}",\n ["MISCONFIGURATION_ERROR"]: "{{misconfiguration_message}}"\n };\n if (messages[error.type]) {\n error.message = messages[error.type];\n } else {\n error.message = messages["RUNTIME_ERROR"];\n }\n if (services.current === services.main) {\n error.goto = undefined;\n } else {\n error.goto = {\n id: "onboarding",\n service: services.main\n };\n }\n return error;\n}\n/**\n * @imports\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n */\nvar DwnError = class _DwnError extends Error {\n /**\n * Creates a new DwnError instance.\n *\n * @param {string} type The error type identifier (e.g., "VALIDATION_ERROR", "SCRIPT_ERROR")\n * @param {string} description Human-readable description of what went wrong\n * @param {{message?: string, messages?: string[], stack?: string, goto?: State | null, state?: State, at?: string, intent?: string | null, content?: string, recurrence?: ErrorRecurrence, code?: string | null, status?: FINALIZATION_STATUS}} [extras] Optional additional error context and metadata:\n * - `message`: Primary error message for user display\n * - `messages`: Array of error messages for different contexts\n * - `stack`: Stack trace or execution context information\n * - `goto`: Target state to redirect to on error (null means terminate)\n * - `state`: Flow state where the error occurred\n * - `at`: Location or context where the error occurred\n * - `intent`: Associated intent that caused the error\n * - `content`: Additional error content or context\n * - `recurrence`: Information about error recurrence patterns\n * - `code`: Error code for programmatic error handling\n * - `status`: Finalization status indicating how the error was resolved\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid input provided");\n *\n * const contextError = new DwnError("SCRIPT_ERROR", "Script execution failed", {\n * state: { id: "state-123", service: "main" },\n * intent: "user-input",\n * content: "invalid data",\n * messages: ["First attempt failed", "Retry failed"],\n * goto: { id: "error-handler", service: "main" }\n * });\n * ```\n */\n constructor(type, description, extras) {\n super();\n this.name = "DwnError";\n const _extras = _DwnError.enforceExtras(extras);\n this.type = type;\n this.description = description;\n this.at = _extras.at;\n this.content = _extras.content;\n this.state = _extras.state;\n this.recurrence = _extras.recurrence;\n this.goto = _extras.goto;\n this.message = _extras.message || undefined;\n this.messages = _extras.messages || [];\n this.intent = _extras.intent || undefined;\n this.code = _extras.code || undefined;\n this.status = _extras.status || undefined;\n this.stack = _extras.stack || undefined;\n if (!this.stack) {\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, _DwnError);\n }\n }\n }\n /**\n * Creates a DwnError instance from a serialized error string.\n *\n * Parses a DWN error string in the format "TYPE -|- DESCRIPTION -|- EXTRAS_JSON"\n * and reconstructs the original DwnError instance.\n *\n * @param {string} dwnErrorString Serialized error string from toString() method\n * @returns {DwnError | undefined} DwnError instance or undefined if parsing fails\n *\n * @example\n * ```typescript\n * const errorString = "SCRIPT_ERROR -|- Execution failed -|- {...}";\n * const error = DwnError.fromDwnError(errorString);\n * ```\n */\n static fromDwnError(dwnErrorString) {\n if (!dwnErrorString) return undefined;\n const parts = dwnErrorString.split("-|-");\n let type = parts.shift();\n if (!type) {\n return undefined;\n }\n type = type.trim();\n let description = parts.shift() || "";\n if (description) {\n description = description.trim();\n }\n let extras = undefined;\n try {\n extras = JSON.parse(parts.shift() || "{}");\n } catch (e) {\n }\n if (extras) {\n return new _DwnError(type, description, extras);\n }\n return new _DwnError(type, description);\n }\n /**\n * Creates a DwnError instance from a JSON object.\n *\n * Converts a generic Error object or JSON representation into a properly\n * structured DwnError instance with all required properties.\n *\n * @param {Error} data Error object or JSON data to convert\n * @returns {DwnError} New DwnError instance\n *\n * @example\n * ```typescript\n * const jsonData = { type: "API_ERROR", description: "Request failed" };\n * const error = DwnError.fromJson(jsonData);\n * ```\n */\n static fromJson(data) {\n const extras = _DwnError.enforceExtras(data);\n return new _DwnError(data.type, data.description, extras);\n }\n /**\n * Normalizes and validates error extras properties.\n *\n * Ensures all optional properties have default values and validates the structure\n * of the extras object. Used internally to maintain consistency across error instances.\n *\n * @param {DwnError | DwnErrorExtras} [entity] Error entity or extras object to normalize\n * @returns {Required<DwnErrorExtras>} Normalized extras object with all required properties\n *\n * @internal\n */\n static enforceExtras(entity) {\n if (!entity) entity = {};\n const extras = {};\n extras.message = entity.message || "";\n extras.messages = entity.messages || [];\n extras.stack = entity.stack || "";\n extras.goto = entity.goto;\n extras.state = entity.state || { id: "", service: "" };\n extras.at = entity.at || (new Date()).toISOString();\n extras.intent = entity.intent || "";\n extras.content = entity.content || "";\n extras.recurrence = entity.recurrence || { type: 1, state: 1, combined: 1 };\n extras.code = entity.code || undefined;\n extras.status = entity.status || undefined;\n return extras;\n }\n /**\n * Serializes the error to a string format.\n *\n * Converts the DwnError instance into a parseable string format using the pattern\n * "TYPE -|- DESCRIPTION -|- EXTRAS_JSON" for storage or transmission.\n *\n * @returns {string} Serialized error string\n *\n * @example\n * ```typescript\n * const error = new DwnError("API_ERROR", "Request failed");\n * const serialized = error.toString();\n * // "API_ERROR -|- Request failed -|- {...}"\n * ```\n */\n toString() {\n const extras = JSON.stringify(_DwnError.enforceExtras(this));\n return `${this.type} -|- ${this.description} -|- ${extras}`;\n }\n /**\n * Converts the error to a JSON object.\n *\n * Serializes all error properties into a plain JavaScript object suitable\n * for JSON serialization, API responses, or logging.\n *\n * @returns {Error} Plain object representation of the error\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid data");\n * const json = error.toJson();\n * console.log(JSON.stringify(json, null, 2));\n * ```\n */\n toJson() {\n return {\n type: this.type,\n at: this.at,\n description: this.description,\n message: this.message,\n messages: this.messages || [],\n stack: this.stack || "",\n intent: this.intent,\n content: this.content,\n goto: this.goto,\n state: this.state,\n recurrence: this.recurrence\n };\n }\n};\nvar SYSTEM_DWN_ERRORS = [\n "RUNTIME_ERROR",\n "MISCONFIGURATION_ERROR"\n];\n\n\nfunction enforceState(state, currentService, states) {\n if (!state && typeof state !== "string") {\n return state;\n }\n const id = typeof state === "string" ? state : state.id;\n if (!id) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `State ${JSON.stringify(state)} must have \'id\' property.`\n );\n }\n const key = `${id}@${currentService}`;\n let service = typeof state === "string" ? currentService : state.service;\n if (!service) {\n service = currentService;\n }\n let name = typeof state === "string" ? "" : state.name;\n if (!name) {\n name = states[key] || undefined;\n }\n return { id, service, name };\n}\n';
|
|
169
|
+
source = source.replace("{{current_service}}", currentService);
|
|
170
|
+
source = source.replace("{{main_service}}", mainService);
|
|
171
|
+
const messages = SYSTEM_ERROR_MESSAGES[language];
|
|
172
|
+
source = source.replace("{{runtime_message}}", messages[Feature_1.Feature.PREDEFINED_ERRORS.RUNTIME_ERROR]);
|
|
173
|
+
source = source.replace("{{misconfiguration_message}}", messages[Feature_1.Feature.PREDEFINED_ERRORS.MISCONFIGURATION_ERROR]);
|
|
174
|
+
return {
|
|
175
|
+
$id,
|
|
176
|
+
$typeOfContent: "",
|
|
177
|
+
type: "ExecuteScriptV2",
|
|
178
|
+
$title: "DWN [SETTINGS] Process Error",
|
|
179
|
+
settings: {
|
|
180
|
+
function: "dwnRun",
|
|
181
|
+
source,
|
|
182
|
+
inputVariables: [
|
|
183
|
+
Feature_1.Feature.VARIABLES.DWN,
|
|
184
|
+
Feature_1.Feature.VARIABLES.CORE,
|
|
185
|
+
Feature_1.Feature.VARIABLES.CONFIG,
|
|
186
|
+
Feature_1.Feature.VARIABLES.STATES,
|
|
187
|
+
Feature_1.Feature.VARIABLES.ERROR,
|
|
188
|
+
],
|
|
189
|
+
outputVariable: Feature_1.Feature.VARIABLES.DWN,
|
|
190
|
+
},
|
|
191
|
+
conditions: [],
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
exports.processErrorScript = processErrorScript;
|
|
195
|
+
const errorMessageScript = ($id) => {
|
|
196
|
+
const source = '/**\n * @author [Beuren Bechlin] <beuren.bechlin@dawntech.dev>\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n *\n * ---\n *\n * This software is the proprietary property of Dawntech.\n * Possession, use, duplication, or dissemination of this software is strictly\n * prohibited unless you have received prior written permission from\n * Dawntech.\n *\n * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nasync function dwnRun(coreStr, errorStr) {\n coreStr = coreStr || "";\n errorStr = errorStr || "";\n let message = null;\n let core = null;\n let error = null;\n try {\n core = JSON.parse(coreStr);\n if (errorStr) {\n error = DwnError.fromDwnError(errorStr) || null;\n }\n if (!error && core.error) {\n error = DwnError.fromJson(core.error);\n }\n if (error && error.type !== "PROPAGATE") {\n message = error.message || null;\n }\n if (message) {\n message = message.trim();\n }\n } catch (err) {\n }\n return message;\n}\n/**\n * @imports\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n */\nvar DwnError = class _DwnError extends Error {\n /**\n * Creates a new DwnError instance.\n *\n * @param {string} type The error type identifier (e.g., "VALIDATION_ERROR", "SCRIPT_ERROR")\n * @param {string} description Human-readable description of what went wrong\n * @param {{message?: string, messages?: string[], stack?: string, goto?: State | null, state?: State, at?: string, intent?: string | null, content?: string, recurrence?: ErrorRecurrence, code?: string | null, status?: FINALIZATION_STATUS}} [extras] Optional additional error context and metadata:\n * - `message`: Primary error message for user display\n * - `messages`: Array of error messages for different contexts\n * - `stack`: Stack trace or execution context information\n * - `goto`: Target state to redirect to on error (null means terminate)\n * - `state`: Flow state where the error occurred\n * - `at`: Location or context where the error occurred\n * - `intent`: Associated intent that caused the error\n * - `content`: Additional error content or context\n * - `recurrence`: Information about error recurrence patterns\n * - `code`: Error code for programmatic error handling\n * - `status`: Finalization status indicating how the error was resolved\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid input provided");\n *\n * const contextError = new DwnError("SCRIPT_ERROR", "Script execution failed", {\n * state: { id: "state-123", service: "main" },\n * intent: "user-input",\n * content: "invalid data",\n * messages: ["First attempt failed", "Retry failed"],\n * goto: { id: "error-handler", service: "main" }\n * });\n * ```\n */\n constructor(type, description, extras) {\n super();\n this.name = "DwnError";\n const _extras = _DwnError.enforceExtras(extras);\n this.type = type;\n this.description = description;\n this.at = _extras.at;\n this.content = _extras.content;\n this.state = _extras.state;\n this.recurrence = _extras.recurrence;\n this.goto = _extras.goto;\n this.message = _extras.message || undefined;\n this.messages = _extras.messages || [];\n this.intent = _extras.intent || undefined;\n this.code = _extras.code || undefined;\n this.status = _extras.status || undefined;\n this.stack = _extras.stack || undefined;\n if (!this.stack) {\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, _DwnError);\n }\n }\n }\n /**\n * Creates a DwnError instance from a serialized error string.\n *\n * Parses a DWN error string in the format "TYPE -|- DESCRIPTION -|- EXTRAS_JSON"\n * and reconstructs the original DwnError instance.\n *\n * @param {string} dwnErrorString Serialized error string from toString() method\n * @returns {DwnError | undefined} DwnError instance or undefined if parsing fails\n *\n * @example\n * ```typescript\n * const errorString = "SCRIPT_ERROR -|- Execution failed -|- {...}";\n * const error = DwnError.fromDwnError(errorString);\n * ```\n */\n static fromDwnError(dwnErrorString) {\n if (!dwnErrorString) return undefined;\n const parts = dwnErrorString.split("-|-");\n let type = parts.shift();\n if (!type) {\n return undefined;\n }\n type = type.trim();\n let description = parts.shift() || "";\n if (description) {\n description = description.trim();\n }\n let extras = undefined;\n try {\n extras = JSON.parse(parts.shift() || "{}");\n } catch (e) {\n }\n if (extras) {\n return new _DwnError(type, description, extras);\n }\n return new _DwnError(type, description);\n }\n /**\n * Creates a DwnError instance from a JSON object.\n *\n * Converts a generic Error object or JSON representation into a properly\n * structured DwnError instance with all required properties.\n *\n * @param {Error} data Error object or JSON data to convert\n * @returns {DwnError} New DwnError instance\n *\n * @example\n * ```typescript\n * const jsonData = { type: "API_ERROR", description: "Request failed" };\n * const error = DwnError.fromJson(jsonData);\n * ```\n */\n static fromJson(data) {\n const extras = _DwnError.enforceExtras(data);\n return new _DwnError(data.type, data.description, extras);\n }\n /**\n * Normalizes and validates error extras properties.\n *\n * Ensures all optional properties have default values and validates the structure\n * of the extras object. Used internally to maintain consistency across error instances.\n *\n * @param {DwnError | DwnErrorExtras} [entity] Error entity or extras object to normalize\n * @returns {Required<DwnErrorExtras>} Normalized extras object with all required properties\n *\n * @internal\n */\n static enforceExtras(entity) {\n if (!entity) entity = {};\n const extras = {};\n extras.message = entity.message || "";\n extras.messages = entity.messages || [];\n extras.stack = entity.stack || "";\n extras.goto = entity.goto;\n extras.state = entity.state || { id: "", service: "" };\n extras.at = entity.at || (new Date()).toISOString();\n extras.intent = entity.intent || "";\n extras.content = entity.content || "";\n extras.recurrence = entity.recurrence || { type: 1, state: 1, combined: 1 };\n extras.code = entity.code || undefined;\n extras.status = entity.status || undefined;\n return extras;\n }\n /**\n * Serializes the error to a string format.\n *\n * Converts the DwnError instance into a parseable string format using the pattern\n * "TYPE -|- DESCRIPTION -|- EXTRAS_JSON" for storage or transmission.\n *\n * @returns {string} Serialized error string\n *\n * @example\n * ```typescript\n * const error = new DwnError("API_ERROR", "Request failed");\n * const serialized = error.toString();\n * // "API_ERROR -|- Request failed -|- {...}"\n * ```\n */\n toString() {\n const extras = JSON.stringify(_DwnError.enforceExtras(this));\n return `${this.type} -|- ${this.description} -|- ${extras}`;\n }\n /**\n * Converts the error to a JSON object.\n *\n * Serializes all error properties into a plain JavaScript object suitable\n * for JSON serialization, API responses, or logging.\n *\n * @returns {Error} Plain object representation of the error\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid data");\n * const json = error.toJson();\n * console.log(JSON.stringify(json, null, 2));\n * ```\n */\n toJson() {\n return {\n type: this.type,\n at: this.at,\n description: this.description,\n message: this.message,\n messages: this.messages || [],\n stack: this.stack || "",\n intent: this.intent,\n content: this.content,\n goto: this.goto,\n state: this.state,\n recurrence: this.recurrence\n };\n }\n};\nvar SYSTEM_DWN_ERRORS = [\n "RUNTIME_ERROR",\n "MISCONFIGURATION_ERROR"\n];\n';
|
|
197
|
+
return {
|
|
198
|
+
$id,
|
|
199
|
+
$typeOfContent: "",
|
|
200
|
+
type: "ExecuteScriptV2",
|
|
201
|
+
$title: "DWN Create Message",
|
|
202
|
+
settings: {
|
|
203
|
+
function: "dwnRun",
|
|
204
|
+
source,
|
|
205
|
+
inputVariables: [Feature_1.Feature.VARIABLES.CORE, Feature_1.Feature.VARIABLES.ERROR],
|
|
206
|
+
outputVariable: Feature_1.Feature.VARIABLES.MESSAGE,
|
|
207
|
+
},
|
|
208
|
+
conditions: [],
|
|
209
|
+
};
|
|
210
|
+
};
|
|
211
|
+
exports.errorMessageScript = errorMessageScript;
|
|
212
|
+
const prepareScriptTemplate = ($id) => {
|
|
213
|
+
const id = $id.substring(0, 8);
|
|
214
|
+
let source = '/*\nenum INTENT_TYPE { REGEX = "regex", FUZZY = "fuzzy", STATIC = "static" }\nenum INPUT_TYPE { \n\tFLOWS = "FLOWS", TEXT = "TEXT", CART = "CART", IMAGE = "IMAGE", STICKER = "STICKER", VIDEO = "VIDEO",\n\tAUDIO = "AUDIO", DOCUMENT = "DOCUMENT", LOCATION = "LOCATION", CTWA = "CTWA", INACTIVITY = "INACTIVITY"\n}\nenum INPUT_MODEL {\n\tGOTO = "GOTO", DEBUG = "DEBUG", CEP = "CEP", CPF = "CPF", CNPJ = "CNPJ",\n\tBIRTH_DAY = "BIRTH_DAY", NAME = "NAME", FULL_NAME = "FULL_NAME", EMAIL = "EMAIL",\n\tCTWA = "CTWA", FLOWS = "FLOWS", CART = "CART", CAR_PLATE = "CAR_PLATE", LOCATION = "LOCATION"\n}\ninterface IntentSpec {\n\t// Unique identifier for the intent (e.g., "dwn@intent.id")\n\tid: string;\n\t// Human-readable label describing the intent\'s purpose\n\tlabel: string;\n\t// Type of intent matching. Defaults to static\n\ttype?: INTENT_TYPE;\n\t// Array of patterns to match against user input (regex patterns or words)\n\tpatterns?: string[];\n\t// Custom payload data to associate with this intent (maps to dwn@input.payload)\n\tpayload?: any | null;\n\t// Target state to transition to when this intent is matched\n\tgoto?: State | null;\n}\ninterface State {\n\t// Unique identifier for the state\n\tid: string;\n\t// Service context for this state\n\tservice?: string;\n\t// Human-readable name for the state\n\tname?: string;\n}\ninterface Prepare {\n\t// Unique identifier for the preparation configuration\n\tid: string;\n\t// Whether to add a checkpoint to the flow for potential rollback. Default: false\n\tcheckpoint?: boolean;\n\t// Number of times to push the intent to the execution stack. Default: 0\n\tstack?: number;\n\t// Confidence score threshold for intent matching. Default: 0.75\n\tscore?: number;\n\t// Configuration for disabling specific flow features\n\tdisabled?: {\n\t\t// Whether to disable inactivity timeout handling. Default: false\n\t\tinactivity?: boolean;\n\t\t// Array of intent IDs to disable during execution\n\t\tintents?: string[];\n\t};\n\t// Default error configurations when reaching the fallback state\n\terror?: {\n\t\t// Default error type\n\t\ttype?: string;\n\t\t// Custom error messages to override default configuration messages. Set to null to disable messages\n\t\tmessages?: string[];\n\t\t// Custom state to transition to after the error\n\t\tgoto?: State | null;\n\t};\n\t// Custom inactivity error message. Default: \'INACTIVITY\'\n\tinactivity?: string;\n\t// Custom labels for flow states\n\tlabel?: {\n\t\t// Custom label for unexpected input handling\n\t\tunexpected?: string;\n\t};\n\t// Array of intent specifications for the flow\n\tintents?: IntentSpec[];\n\t// Input types to be processed in the flow\n\ttypes?: INPUT_TYPE[];\n\t// AI models to be used for intent processing in the flow\n\tmodels?: INPUT_MODEL[];\n}\n*/\n\n\nvar PREPARE_EXAMPLE_1 = {\n id: "unique-identifier-1",\n intents: [\n {\n id: "YES",\n label: "Operação X confirmada",\n type: "regex",\n patterns: ["si.*", "yes.*"]\n },\n {\n id: "NO",\n label: "Operação X rejeitada",\n type: "regex",\n patterns: ["n.*"]\n }\n ]\n};\nvar PREPARE_EXAMPLE_2 = {\n id: "unique-identifier-2",\n models: ["NAME"],\n error: {\n messages: [\n `Isso não é um nome válido, seu nome não pode ter caracteres especiais ou números. Tente novamente.`,\n `Ainda é inválido, tente outra vez.`,\n `Não estou conseguindo entender o seu nome.`\n ]\n }\n};\nvar PREPARE_EXAMPLE_3 = {\n id: "unique-identifier-3",\n checkpoint: true,\n // \'voltar\' go back matching\n error: {\n type: "UNEXPECTED_OPTION"\n // usage of unexpected option default messages instead of unexpected input\n },\n intents: [\n {\n id: "OPT_1",\n label: "Models",\n type: "regex",\n patterns: ["<regex-1>", "<regex-2>"],\n goto: {\n id: "<state-id-opt-1>"\n }\n },\n {\n id: "OPT_2",\n label: "Inactivity",\n type: "fuzzy",\n patterns: ["<similar-word-1>", "<similar-word-2>"],\n goto: {\n id: "a8caf748-4f78-4747-b9bb-4edc7a7c3ebc"\n }\n }\n ]\n};\nasync function dwnRun() {\n const dwnPrepare = {\n id: "{{script-id}}"\n };\n return dwnPrepare;\n}\nasync function run(...args) {\n const id = "{{script-id}}";\n const type = "basic";\n let result = await dwnProcess(id, type, dwnRun, ...args);\n return result;\n}\n/**\n * @imports\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n */\nvar DwnError = class _DwnError extends Error {\n /**\n * Creates a new DwnError instance.\n *\n * @param {string} type The error type identifier (e.g., "VALIDATION_ERROR", "SCRIPT_ERROR")\n * @param {string} description Human-readable description of what went wrong\n * @param {{message?: string, messages?: string[], stack?: string, goto?: State | null, state?: State, at?: string, intent?: string | null, content?: string, recurrence?: ErrorRecurrence, code?: string | null, status?: FINALIZATION_STATUS}} [extras] Optional additional error context and metadata:\n * - `message`: Primary error message for user display\n * - `messages`: Array of error messages for different contexts\n * - `stack`: Stack trace or execution context information\n * - `goto`: Target state to redirect to on error (null means terminate)\n * - `state`: Flow state where the error occurred\n * - `at`: Location or context where the error occurred\n * - `intent`: Associated intent that caused the error\n * - `content`: Additional error content or context\n * - `recurrence`: Information about error recurrence patterns\n * - `code`: Error code for programmatic error handling\n * - `status`: Finalization status indicating how the error was resolved\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid input provided");\n *\n * const contextError = new DwnError("SCRIPT_ERROR", "Script execution failed", {\n * state: { id: "state-123", service: "main" },\n * intent: "user-input",\n * content: "invalid data",\n * messages: ["First attempt failed", "Retry failed"],\n * goto: { id: "error-handler", service: "main" }\n * });\n * ```\n */\n constructor(type, description, extras) {\n super();\n this.name = "DwnError";\n const _extras = _DwnError.enforceExtras(extras);\n this.type = type;\n this.description = description;\n this.at = _extras.at;\n this.content = _extras.content;\n this.state = _extras.state;\n this.recurrence = _extras.recurrence;\n this.goto = _extras.goto;\n this.message = _extras.message || undefined;\n this.messages = _extras.messages || [];\n this.intent = _extras.intent || undefined;\n this.code = _extras.code || undefined;\n this.status = _extras.status || undefined;\n this.stack = _extras.stack || undefined;\n if (!this.stack) {\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, _DwnError);\n }\n }\n }\n /**\n * Creates a DwnError instance from a serialized error string.\n *\n * Parses a DWN error string in the format "TYPE -|- DESCRIPTION -|- EXTRAS_JSON"\n * and reconstructs the original DwnError instance.\n *\n * @param {string} dwnErrorString Serialized error string from toString() method\n * @returns {DwnError | undefined} DwnError instance or undefined if parsing fails\n *\n * @example\n * ```typescript\n * const errorString = "SCRIPT_ERROR -|- Execution failed -|- {...}";\n * const error = DwnError.fromDwnError(errorString);\n * ```\n */\n static fromDwnError(dwnErrorString) {\n if (!dwnErrorString) return undefined;\n const parts = dwnErrorString.split("-|-");\n let type = parts.shift();\n if (!type) {\n return undefined;\n }\n type = type.trim();\n let description = parts.shift() || "";\n if (description) {\n description = description.trim();\n }\n let extras = undefined;\n try {\n extras = JSON.parse(parts.shift() || "{}");\n } catch (e) {\n }\n if (extras) {\n return new _DwnError(type, description, extras);\n }\n return new _DwnError(type, description);\n }\n /**\n * Creates a DwnError instance from a JSON object.\n *\n * Converts a generic Error object or JSON representation into a properly\n * structured DwnError instance with all required properties.\n *\n * @param {Error} data Error object or JSON data to convert\n * @returns {DwnError} New DwnError instance\n *\n * @example\n * ```typescript\n * const jsonData = { type: "API_ERROR", description: "Request failed" };\n * const error = DwnError.fromJson(jsonData);\n * ```\n */\n static fromJson(data) {\n const extras = _DwnError.enforceExtras(data);\n return new _DwnError(data.type, data.description, extras);\n }\n /**\n * Normalizes and validates error extras properties.\n *\n * Ensures all optional properties have default values and validates the structure\n * of the extras object. Used internally to maintain consistency across error instances.\n *\n * @param {DwnError | DwnErrorExtras} [entity] Error entity or extras object to normalize\n * @returns {Required<DwnErrorExtras>} Normalized extras object with all required properties\n *\n * @internal\n */\n static enforceExtras(entity) {\n if (!entity) entity = {};\n const extras = {};\n extras.message = entity.message || "";\n extras.messages = entity.messages || [];\n extras.stack = entity.stack || "";\n extras.goto = entity.goto;\n extras.state = entity.state || { id: "", service: "" };\n extras.at = entity.at || (new Date()).toISOString();\n extras.intent = entity.intent || "";\n extras.content = entity.content || "";\n extras.recurrence = entity.recurrence || { type: 1, state: 1, combined: 1 };\n extras.code = entity.code || undefined;\n extras.status = entity.status || undefined;\n return extras;\n }\n /**\n * Serializes the error to a string format.\n *\n * Converts the DwnError instance into a parseable string format using the pattern\n * "TYPE -|- DESCRIPTION -|- EXTRAS_JSON" for storage or transmission.\n *\n * @returns {string} Serialized error string\n *\n * @example\n * ```typescript\n * const error = new DwnError("API_ERROR", "Request failed");\n * const serialized = error.toString();\n * // "API_ERROR -|- Request failed -|- {...}"\n * ```\n */\n toString() {\n const extras = JSON.stringify(_DwnError.enforceExtras(this));\n return `${this.type} -|- ${this.description} -|- ${extras}`;\n }\n /**\n * Converts the error to a JSON object.\n *\n * Serializes all error properties into a plain JavaScript object suitable\n * for JSON serialization, API responses, or logging.\n *\n * @returns {Error} Plain object representation of the error\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid data");\n * const json = error.toJson();\n * console.log(JSON.stringify(json, null, 2));\n * ```\n */\n toJson() {\n return {\n type: this.type,\n at: this.at,\n description: this.description,\n message: this.message,\n messages: this.messages || [],\n stack: this.stack || "",\n intent: this.intent,\n content: this.content,\n goto: this.goto,\n state: this.state,\n recurrence: this.recurrence\n };\n }\n};\nvar SYSTEM_DWN_ERRORS = [\n "RUNTIME_ERROR",\n "MISCONFIGURATION_ERROR"\n];\n\n\nvar Logger = class {\n constructor() {\n this._logs = [];\n }\n /**\n * Logs an informational message.\n *\n * @param {...any} args Arguments to log (objects are automatically JSON stringified)\n */\n log(...args) {\n this._log("info", ...args);\n }\n /**\n * Logs a warning message.\n *\n * @param {...any} args Arguments to log (objects are automatically JSON stringified)\n */\n warn(...args) {\n this._log("warn", ...args);\n }\n /**\n * Logs an error message.\n *\n * @param {...any} args Arguments to log (objects are automatically JSON stringified)\n */\n error(...args) {\n this._log("error", ...args);\n }\n _log(level, ...args) {\n const message = args.map((arg) => {\n let parsed = "";\n try {\n if (typeof arg !== "object") throw new Error("Not an object");\n parsed = JSON.stringify(arg);\n } catch (err) {\n try {\n parsed = String(arg);\n } catch (err2) {\n parsed = "(unserializable)";\n }\n }\n return parsed;\n }).join(" ");\n const log = { date: new Date(), message, level };\n this._logs.unshift(log);\n }\n};\nvar console = new Logger();\n\n\nvar HttpError = class extends Error {\n constructor(message, status, response) {\n super(message);\n this.name = "HttpError";\n this.status = status;\n this.response = response;\n }\n};\nvar HttpClient = class {\n constructor() {\n this._logs = [];\n }\n /**\n * Performs an HTTP request with comprehensive logging and error handling.\n *\n * Makes HTTP requests with automatic JSON handling, response validation, and detailed logging.\n * All requests and responses are logged for debugging and monitoring purposes.\n *\n * @param {{url: string, method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH", params?: {[key: string]: string}, headers?: {[key: string]: string}, body?: Record<string, any> | Array<any> | string, valid?: ((status: number) => boolean) | number[] | number, reduce?: (response: FetchResponse) => string}} config HTTP request configuration:\n * - `url`: The target URL for the HTTP request (required)\n * - `method`: HTTP method to use (defaults to "GET")\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `body`: Request body (objects/arrays are automatically JSON stringified)\n * - `valid`: Custom validation for HTTP status codes (function, array, or single number)\n * - `reduce`: Custom function to process the response before logging\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response:\n * - `status`: HTTP status code\n * - `data`: Parsed response body (JSON parsed if possible, otherwise raw string)\n * - `headers`: Response headers as key-value object\n *\n * @throws {DwnError} Throws MISCONFIGURATION_ERROR if URL is missing or method is invalid\n * @throws {HttpError} Throws HttpError if the request fails or returns invalid status code\n */\n async request(config) {\n if (!config || !config.url) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n "HTTP request must have a URL."\n );\n }\n if (config.method && !["GET", "POST", "PUT", "DELETE", "PATCH"].includes(config.method)) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `Invalid HTTP method: ${config.method}`\n );\n }\n const req = this.prepareRequest(config);\n const response = await request.fetchAsync(req.url, req.options);\n const resp = this.prepareResponse(config, response);\n const log = {\n request: req.log,\n response: resp.log,\n duration: resp.log.at.getTime() - req.log.at.getTime()\n };\n this._logs.unshift(log);\n if (!resp.success) {\n throw new HttpError(\n `HTTP request failed with status ${resp.response.status}.`,\n resp.response.status,\n resp.response\n );\n }\n return resp.response;\n }\n /**\n * Performs a GET HTTP request.\n *\n * @param {string} url The target URL for the GET request\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async get(url, config) {\n return this.request({ ...config, url, method: "GET" });\n }\n /**\n * Performs a POST HTTP request.\n *\n * @param {string} url The target URL for the POST request\n * @param {Record<string, any> | Array<any> | string} [body] Request body (objects/arrays are automatically JSON stringified)\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async post(url, body, config) {\n return this.request({ ...config, url, method: "POST", body });\n }\n /**\n * Performs a PUT HTTP request.\n *\n * @param {string} url The target URL for the PUT request\n * @param {Record<string, any> | Array<any> | string} [body] Request body (objects/arrays are automatically JSON stringified)\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async put(url, body, config) {\n return this.request({ ...config, url, method: "PUT", body });\n }\n /**\n * Performs a DELETE HTTP request.\n *\n * @param {string} url The target URL for the DELETE request\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async delete(url, config) {\n return this.request({ ...config, url, method: "DELETE" });\n }\n /**\n * Performs a PATCH HTTP request.\n *\n * @param {string} url The target URL for the PATCH request\n * @param {Record<string, any> | Array<any> | string} [body] Request body (objects/arrays are automatically JSON stringified)\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async patch(url, body, config) {\n return this.request({ ...config, url, method: "PATCH", body });\n }\n prepareRequest(config) {\n const createQueryString = (params2 = {}) => {\n const pairs = [];\n for (const [key, value] of Object.entries(params2)) {\n if (value !== undefined && value !== null) {\n const encodedKey = encodeURIComponent(key);\n const encodedValue = encodeURIComponent(String(value));\n pairs.push(`${encodedKey}=${encodedValue}`);\n }\n }\n return pairs.join("&");\n };\n const params = createQueryString(config.params || {});\n const method = config.method || "GET";\n const headers = config.headers || {};\n let length = 0;\n let body = config.body || null;\n if (body && typeof body === "object") {\n body = JSON.stringify(body);\n headers["Content-Type"] = "application/json";\n }\n if (body && typeof body === "string") {\n length = body.length;\n }\n let url = config.url;\n if (params !== "") url += `?${params}`;\n let options = {\n method,\n headers,\n body\n };\n const log = {\n at: new Date(),\n url,\n method: method || "GET",\n headers: headers || {},\n length\n };\n return { url, options, log };\n }\n prepareResponse(config, resp) {\n const { status } = resp;\n let headers = {};\n for (const header of resp.headers) {\n const key = header.key;\n const values = header.value;\n if (values.length > 0) {\n headers[key] = values[0];\n }\n }\n const length = headers["content-length"] ? parseInt(headers["content-length"], 10) : resp.body ? resp.body.length : 0;\n let data = null;\n try {\n data = JSON.parse(resp.body);\n } catch (err) {\n data = resp.body;\n }\n let valid = (status2) => status2 >= 200 && status2 < 300;\n if (config.valid) {\n if (Array.isArray(config.valid)) {\n const expectedSet = new Set(config.valid);\n valid = (status2) => expectedSet.has(status2);\n } else if (typeof config.valid === "number") {\n const expectedNumber = config.valid;\n valid = (status2) => status2 === expectedNumber;\n } else if (typeof config.valid === "function") {\n valid = config.valid;\n }\n }\n const success = valid(status);\n let reduce = (raw) => {\n let body = "";\n try {\n if (typeof raw !== "object") {\n throw new Error("Not an object");\n }\n body = JSON.stringify(raw);\n } catch (err) {\n body = String(raw);\n }\n let reduced = false;\n if (body.length > 1e3) {\n body = body.substring(0, 1e3) + "...(truncated)";\n reduced = true;\n }\n return { body, reduced };\n };\n const log = {\n at: new Date(),\n status,\n length,\n success,\n ...reduce(resp.body)\n };\n const response = {\n status,\n data,\n headers\n };\n return { response, log, success };\n }\n};\nvar http = new HttpClient();\n\n\nfunction formatDate(date, config) {\n let tzOffset = config ? config.gmt || -3 : -3;\n const dateTz = new Date(date.getTime() + tzOffset * 36e5);\n const datetimeFormatted = dateTz.toISOString().split(".")[0];\n const offsetSign = tzOffset >= 0 ? "+" : "-";\n const offsetHours = Math.abs(Math.floor(tzOffset)).toString().padStart(2, "0");\n const offsetMinutes = Math.abs(tzOffset % 1 * 60).toString().padStart(2, "0");\n return {\n datetime: `${datetimeFormatted}${offsetSign}${offsetHours}:${offsetMinutes}`,\n time: dateTz.toISOString().split("T")[1].split("Z")[0]\n };\n}\n\n\nasync function dwnProcess(id, type, fn, ...args) {\n let result = undefined;\n let error = null;\n try {\n result = await fn(...args);\n if (!id && (console._logs.length > 0 || http._logs.length > 0)) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n "Script must have an ID to capture logs."\n );\n }\n } catch (err) {\n if (err instanceof HttpError) {\n const description = `[${id}] HTTP request failed with status ${err.status}.`;\n const stack = err && err.stack ? String(err.stack) : "";\n err = new DwnError("HTTP_ERROR", description, {\n code: `S-${err.status}`,\n stack,\n goto: null\n });\n } else if (!(err instanceof DwnError)) {\n const description = `[${id}] Unexpected error ${String(err)}`;\n const stack = err && err.stack ? String(err.stack) : "";\n err = new DwnError("SCRIPT_ERROR", description, {\n stack,\n goto: null\n });\n }\n error = err;\n } finally {\n await dwnFlush(id, type, error);\n }\n if (error) {\n await context.setVariableAsync("dwnError", error.toString());\n }\n return result;\n}\nasync function dwnFlush(id, type, error = null) {\n let config = {};\n try {\n const configStr = await context.getVariableAsync("dwnConfig");\n config = JSON.parse(configStr || "");\n } catch (err) {\n }\n await dwnFlushGlobalLogs(config);\n if (type === "complete") {\n await dwnFlushLocalLogs(config, id);\n }\n if (error) {\n await dwnFlushError(config, error);\n }\n}\nasync function dwnFlushLocalLogs(config, id) {\n const { datetime } = formatDate(new Date(), config);\n const _logs = console._logs.map((log) => {\n const { level, message, date } = log;\n const { time } = formatDate(date, config);\n return `[${time}](${level}) ${message}`;\n });\n const _http = http._logs.map((log) => log);\n const data = { datetime, logs: _logs, http: _http };\n const name = `${"dwnScript"}-${id}`;\n await context.setVariableAsync(name, JSON.stringify(data));\n}\nasync function dwnFlushGlobalLogs(config) {\n const size = config.stackSize ? config.stackSize.logs || 10 : 10;\n if (console._logs.length === 0) return;\n let logs = [];\n try {\n const logsStr = await context.getVariableAsync("dwnLogger");\n logs = JSON.parse(logsStr || "[]");\n if (!logs || !Array.isArray(logs)) {\n throw new Error("Invalid logs format");\n }\n } catch (err) {\n logs = [];\n }\n const _logs = console._logs.map((log) => {\n const { level, message, date } = log;\n const { datetime } = formatDate(date, config);\n return `[${datetime}](${level}) ${message}`;\n });\n logs = [..._logs, ...logs].slice(0, size);\n await context.setVariableAsync("dwnLogger", JSON.stringify(logs));\n}\nasync function dwnFlushError(config, error) {\n const contract = config.connection ? config.connection.contract || "" : "";\n const key = config.connection ? config.connection.key || "" : "";\n if (!contract || !key) return;\n let category = "dwn-track-error";\n let items = [error.type, error.code || "", error.description || ""];\n let action = items.join("-|-").trim();\n const url = `https://${contract}.http.msging.net/commands`;\n const headers = {\n "Content-Type": "application/json",\n Authorization: key\n };\n const body = {\n id: Math.random().toString(36).substring(2, 15),\n to: "postmaster@analytics.msging.net",\n method: "set",\n type: "application/vnd.iris.eventTrack+json",\n uri: "/event-track",\n resource: {\n category,\n action\n }\n };\n request.fetchAsync(url, { method: "POST", headers, body });\n}\n';
|
|
215
|
+
source = source.replace(/{{script-id}}/g, id);
|
|
216
|
+
return {
|
|
217
|
+
$id,
|
|
218
|
+
$typeOfContent: "",
|
|
219
|
+
type: "ExecuteScriptV2",
|
|
220
|
+
$title: `DWN Prepare ${id}`,
|
|
221
|
+
settings: {
|
|
222
|
+
function: "run",
|
|
223
|
+
source,
|
|
224
|
+
inputVariables: [],
|
|
225
|
+
outputVariable: Feature_1.Feature.VARIABLES.PREPARE,
|
|
226
|
+
LocalTimeZoneEnabled: false,
|
|
227
|
+
},
|
|
228
|
+
conditions: [],
|
|
229
|
+
};
|
|
230
|
+
};
|
|
231
|
+
exports.prepareScriptTemplate = prepareScriptTemplate;
|
|
232
|
+
const basicScriptTemplate = ($id) => {
|
|
233
|
+
const id = $id.substring(0, 8);
|
|
234
|
+
let source = '\nasync function dwnRun() {\n return undefined;\n}\nasync function run(...args) {\n const id = "{{script-id}}";\n const type = "basic";\n let result = await dwnProcess(id, type, dwnRun, ...args);\n return result;\n}\n/**\n * @imports\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n */\nvar DwnError = class _DwnError extends Error {\n /**\n * Creates a new DwnError instance.\n *\n * @param {string} type The error type identifier (e.g., "VALIDATION_ERROR", "SCRIPT_ERROR")\n * @param {string} description Human-readable description of what went wrong\n * @param {{message?: string, messages?: string[], stack?: string, goto?: State | null, state?: State, at?: string, intent?: string | null, content?: string, recurrence?: ErrorRecurrence, code?: string | null, status?: FINALIZATION_STATUS}} [extras] Optional additional error context and metadata:\n * - `message`: Primary error message for user display\n * - `messages`: Array of error messages for different contexts\n * - `stack`: Stack trace or execution context information\n * - `goto`: Target state to redirect to on error (null means terminate)\n * - `state`: Flow state where the error occurred\n * - `at`: Location or context where the error occurred\n * - `intent`: Associated intent that caused the error\n * - `content`: Additional error content or context\n * - `recurrence`: Information about error recurrence patterns\n * - `code`: Error code for programmatic error handling\n * - `status`: Finalization status indicating how the error was resolved\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid input provided");\n *\n * const contextError = new DwnError("SCRIPT_ERROR", "Script execution failed", {\n * state: { id: "state-123", service: "main" },\n * intent: "user-input",\n * content: "invalid data",\n * messages: ["First attempt failed", "Retry failed"],\n * goto: { id: "error-handler", service: "main" }\n * });\n * ```\n */\n constructor(type, description, extras) {\n super();\n this.name = "DwnError";\n const _extras = _DwnError.enforceExtras(extras);\n this.type = type;\n this.description = description;\n this.at = _extras.at;\n this.content = _extras.content;\n this.state = _extras.state;\n this.recurrence = _extras.recurrence;\n this.goto = _extras.goto;\n this.message = _extras.message || undefined;\n this.messages = _extras.messages || [];\n this.intent = _extras.intent || undefined;\n this.code = _extras.code || undefined;\n this.status = _extras.status || undefined;\n this.stack = _extras.stack || undefined;\n if (!this.stack) {\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, _DwnError);\n }\n }\n }\n /**\n * Creates a DwnError instance from a serialized error string.\n *\n * Parses a DWN error string in the format "TYPE -|- DESCRIPTION -|- EXTRAS_JSON"\n * and reconstructs the original DwnError instance.\n *\n * @param {string} dwnErrorString Serialized error string from toString() method\n * @returns {DwnError | undefined} DwnError instance or undefined if parsing fails\n *\n * @example\n * ```typescript\n * const errorString = "SCRIPT_ERROR -|- Execution failed -|- {...}";\n * const error = DwnError.fromDwnError(errorString);\n * ```\n */\n static fromDwnError(dwnErrorString) {\n if (!dwnErrorString) return undefined;\n const parts = dwnErrorString.split("-|-");\n let type = parts.shift();\n if (!type) {\n return undefined;\n }\n type = type.trim();\n let description = parts.shift() || "";\n if (description) {\n description = description.trim();\n }\n let extras = undefined;\n try {\n extras = JSON.parse(parts.shift() || "{}");\n } catch (e) {\n }\n if (extras) {\n return new _DwnError(type, description, extras);\n }\n return new _DwnError(type, description);\n }\n /**\n * Creates a DwnError instance from a JSON object.\n *\n * Converts a generic Error object or JSON representation into a properly\n * structured DwnError instance with all required properties.\n *\n * @param {Error} data Error object or JSON data to convert\n * @returns {DwnError} New DwnError instance\n *\n * @example\n * ```typescript\n * const jsonData = { type: "API_ERROR", description: "Request failed" };\n * const error = DwnError.fromJson(jsonData);\n * ```\n */\n static fromJson(data) {\n const extras = _DwnError.enforceExtras(data);\n return new _DwnError(data.type, data.description, extras);\n }\n /**\n * Normalizes and validates error extras properties.\n *\n * Ensures all optional properties have default values and validates the structure\n * of the extras object. Used internally to maintain consistency across error instances.\n *\n * @param {DwnError | DwnErrorExtras} [entity] Error entity or extras object to normalize\n * @returns {Required<DwnErrorExtras>} Normalized extras object with all required properties\n *\n * @internal\n */\n static enforceExtras(entity) {\n if (!entity) entity = {};\n const extras = {};\n extras.message = entity.message || "";\n extras.messages = entity.messages || [];\n extras.stack = entity.stack || "";\n extras.goto = entity.goto;\n extras.state = entity.state || { id: "", service: "" };\n extras.at = entity.at || (new Date()).toISOString();\n extras.intent = entity.intent || "";\n extras.content = entity.content || "";\n extras.recurrence = entity.recurrence || { type: 1, state: 1, combined: 1 };\n extras.code = entity.code || undefined;\n extras.status = entity.status || undefined;\n return extras;\n }\n /**\n * Serializes the error to a string format.\n *\n * Converts the DwnError instance into a parseable string format using the pattern\n * "TYPE -|- DESCRIPTION -|- EXTRAS_JSON" for storage or transmission.\n *\n * @returns {string} Serialized error string\n *\n * @example\n * ```typescript\n * const error = new DwnError("API_ERROR", "Request failed");\n * const serialized = error.toString();\n * // "API_ERROR -|- Request failed -|- {...}"\n * ```\n */\n toString() {\n const extras = JSON.stringify(_DwnError.enforceExtras(this));\n return `${this.type} -|- ${this.description} -|- ${extras}`;\n }\n /**\n * Converts the error to a JSON object.\n *\n * Serializes all error properties into a plain JavaScript object suitable\n * for JSON serialization, API responses, or logging.\n *\n * @returns {Error} Plain object representation of the error\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid data");\n * const json = error.toJson();\n * console.log(JSON.stringify(json, null, 2));\n * ```\n */\n toJson() {\n return {\n type: this.type,\n at: this.at,\n description: this.description,\n message: this.message,\n messages: this.messages || [],\n stack: this.stack || "",\n intent: this.intent,\n content: this.content,\n goto: this.goto,\n state: this.state,\n recurrence: this.recurrence\n };\n }\n};\nvar SYSTEM_DWN_ERRORS = [\n "RUNTIME_ERROR",\n "MISCONFIGURATION_ERROR"\n];\n\n\nvar Logger = class {\n constructor() {\n this._logs = [];\n }\n /**\n * Logs an informational message.\n *\n * @param {...any} args Arguments to log (objects are automatically JSON stringified)\n */\n log(...args) {\n this._log("info", ...args);\n }\n /**\n * Logs a warning message.\n *\n * @param {...any} args Arguments to log (objects are automatically JSON stringified)\n */\n warn(...args) {\n this._log("warn", ...args);\n }\n /**\n * Logs an error message.\n *\n * @param {...any} args Arguments to log (objects are automatically JSON stringified)\n */\n error(...args) {\n this._log("error", ...args);\n }\n _log(level, ...args) {\n const message = args.map((arg) => {\n let parsed = "";\n try {\n if (typeof arg !== "object") throw new Error("Not an object");\n parsed = JSON.stringify(arg);\n } catch (err) {\n try {\n parsed = String(arg);\n } catch (err2) {\n parsed = "(unserializable)";\n }\n }\n return parsed;\n }).join(" ");\n const log = { date: new Date(), message, level };\n this._logs.unshift(log);\n }\n};\nvar console = new Logger();\n\n\nvar HttpError = class extends Error {\n constructor(message, status, response) {\n super(message);\n this.name = "HttpError";\n this.status = status;\n this.response = response;\n }\n};\nvar HttpClient = class {\n constructor() {\n this._logs = [];\n }\n /**\n * Performs an HTTP request with comprehensive logging and error handling.\n *\n * Makes HTTP requests with automatic JSON handling, response validation, and detailed logging.\n * All requests and responses are logged for debugging and monitoring purposes.\n *\n * @param {{url: string, method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH", params?: {[key: string]: string}, headers?: {[key: string]: string}, body?: Record<string, any> | Array<any> | string, valid?: ((status: number) => boolean) | number[] | number, reduce?: (response: FetchResponse) => string}} config HTTP request configuration:\n * - `url`: The target URL for the HTTP request (required)\n * - `method`: HTTP method to use (defaults to "GET")\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `body`: Request body (objects/arrays are automatically JSON stringified)\n * - `valid`: Custom validation for HTTP status codes (function, array, or single number)\n * - `reduce`: Custom function to process the response before logging\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response:\n * - `status`: HTTP status code\n * - `data`: Parsed response body (JSON parsed if possible, otherwise raw string)\n * - `headers`: Response headers as key-value object\n *\n * @throws {DwnError} Throws MISCONFIGURATION_ERROR if URL is missing or method is invalid\n * @throws {HttpError} Throws HttpError if the request fails or returns invalid status code\n */\n async request(config) {\n if (!config || !config.url) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n "HTTP request must have a URL."\n );\n }\n if (config.method && !["GET", "POST", "PUT", "DELETE", "PATCH"].includes(config.method)) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `Invalid HTTP method: ${config.method}`\n );\n }\n const req = this.prepareRequest(config);\n const response = await request.fetchAsync(req.url, req.options);\n const resp = this.prepareResponse(config, response);\n const log = {\n request: req.log,\n response: resp.log,\n duration: resp.log.at.getTime() - req.log.at.getTime()\n };\n this._logs.unshift(log);\n if (!resp.success) {\n throw new HttpError(\n `HTTP request failed with status ${resp.response.status}.`,\n resp.response.status,\n resp.response\n );\n }\n return resp.response;\n }\n /**\n * Performs a GET HTTP request.\n *\n * @param {string} url The target URL for the GET request\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async get(url, config) {\n return this.request({ ...config, url, method: "GET" });\n }\n /**\n * Performs a POST HTTP request.\n *\n * @param {string} url The target URL for the POST request\n * @param {Record<string, any> | Array<any> | string} [body] Request body (objects/arrays are automatically JSON stringified)\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async post(url, body, config) {\n return this.request({ ...config, url, method: "POST", body });\n }\n /**\n * Performs a PUT HTTP request.\n *\n * @param {string} url The target URL for the PUT request\n * @param {Record<string, any> | Array<any> | string} [body] Request body (objects/arrays are automatically JSON stringified)\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async put(url, body, config) {\n return this.request({ ...config, url, method: "PUT", body });\n }\n /**\n * Performs a DELETE HTTP request.\n *\n * @param {string} url The target URL for the DELETE request\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async delete(url, config) {\n return this.request({ ...config, url, method: "DELETE" });\n }\n /**\n * Performs a PATCH HTTP request.\n *\n * @param {string} url The target URL for the PATCH request\n * @param {Record<string, any> | Array<any> | string} [body] Request body (objects/arrays are automatically JSON stringified)\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async patch(url, body, config) {\n return this.request({ ...config, url, method: "PATCH", body });\n }\n prepareRequest(config) {\n const createQueryString = (params2 = {}) => {\n const pairs = [];\n for (const [key, value] of Object.entries(params2)) {\n if (value !== undefined && value !== null) {\n const encodedKey = encodeURIComponent(key);\n const encodedValue = encodeURIComponent(String(value));\n pairs.push(`${encodedKey}=${encodedValue}`);\n }\n }\n return pairs.join("&");\n };\n const params = createQueryString(config.params || {});\n const method = config.method || "GET";\n const headers = config.headers || {};\n let length = 0;\n let body = config.body || null;\n if (body && typeof body === "object") {\n body = JSON.stringify(body);\n headers["Content-Type"] = "application/json";\n }\n if (body && typeof body === "string") {\n length = body.length;\n }\n let url = config.url;\n if (params !== "") url += `?${params}`;\n let options = {\n method,\n headers,\n body\n };\n const log = {\n at: new Date(),\n url,\n method: method || "GET",\n headers: headers || {},\n length\n };\n return { url, options, log };\n }\n prepareResponse(config, resp) {\n const { status } = resp;\n let headers = {};\n for (const header of resp.headers) {\n const key = header.key;\n const values = header.value;\n if (values.length > 0) {\n headers[key] = values[0];\n }\n }\n const length = headers["content-length"] ? parseInt(headers["content-length"], 10) : resp.body ? resp.body.length : 0;\n let data = null;\n try {\n data = JSON.parse(resp.body);\n } catch (err) {\n data = resp.body;\n }\n let valid = (status2) => status2 >= 200 && status2 < 300;\n if (config.valid) {\n if (Array.isArray(config.valid)) {\n const expectedSet = new Set(config.valid);\n valid = (status2) => expectedSet.has(status2);\n } else if (typeof config.valid === "number") {\n const expectedNumber = config.valid;\n valid = (status2) => status2 === expectedNumber;\n } else if (typeof config.valid === "function") {\n valid = config.valid;\n }\n }\n const success = valid(status);\n let reduce = (raw) => {\n let body = "";\n try {\n if (typeof raw !== "object") {\n throw new Error("Not an object");\n }\n body = JSON.stringify(raw);\n } catch (err) {\n body = String(raw);\n }\n let reduced = false;\n if (body.length > 1e3) {\n body = body.substring(0, 1e3) + "...(truncated)";\n reduced = true;\n }\n return { body, reduced };\n };\n const log = {\n at: new Date(),\n status,\n length,\n success,\n ...reduce(resp.body)\n };\n const response = {\n status,\n data,\n headers\n };\n return { response, log, success };\n }\n};\nvar http = new HttpClient();\n\n\nfunction formatDate(date, config) {\n let tzOffset = config ? config.gmt || -3 : -3;\n const dateTz = new Date(date.getTime() + tzOffset * 36e5);\n const datetimeFormatted = dateTz.toISOString().split(".")[0];\n const offsetSign = tzOffset >= 0 ? "+" : "-";\n const offsetHours = Math.abs(Math.floor(tzOffset)).toString().padStart(2, "0");\n const offsetMinutes = Math.abs(tzOffset % 1 * 60).toString().padStart(2, "0");\n return {\n datetime: `${datetimeFormatted}${offsetSign}${offsetHours}:${offsetMinutes}`,\n time: dateTz.toISOString().split("T")[1].split("Z")[0]\n };\n}\n\n\nasync function dwnProcess(id, type, fn, ...args) {\n let result = undefined;\n let error = null;\n try {\n result = await fn(...args);\n if (!id && (console._logs.length > 0 || http._logs.length > 0)) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n "Script must have an ID to capture logs."\n );\n }\n } catch (err) {\n if (err instanceof HttpError) {\n const description = `[${id}] HTTP request failed with status ${err.status}.`;\n const stack = err && err.stack ? String(err.stack) : "";\n err = new DwnError("HTTP_ERROR", description, {\n code: `S-${err.status}`,\n stack,\n goto: null\n });\n } else if (!(err instanceof DwnError)) {\n const description = `[${id}] Unexpected error ${String(err)}`;\n const stack = err && err.stack ? String(err.stack) : "";\n err = new DwnError("SCRIPT_ERROR", description, {\n stack,\n goto: null\n });\n }\n error = err;\n } finally {\n await dwnFlush(id, type, error);\n }\n if (error) {\n await context.setVariableAsync("dwnError", error.toString());\n }\n return result;\n}\nasync function dwnFlush(id, type, error = null) {\n let config = {};\n try {\n const configStr = await context.getVariableAsync("dwnConfig");\n config = JSON.parse(configStr || "");\n } catch (err) {\n }\n await dwnFlushGlobalLogs(config);\n if (type === "complete") {\n await dwnFlushLocalLogs(config, id);\n }\n if (error) {\n await dwnFlushError(config, error);\n }\n}\nasync function dwnFlushLocalLogs(config, id) {\n const { datetime } = formatDate(new Date(), config);\n const _logs = console._logs.map((log) => {\n const { level, message, date } = log;\n const { time } = formatDate(date, config);\n return `[${time}](${level}) ${message}`;\n });\n const _http = http._logs.map((log) => log);\n const data = { datetime, logs: _logs, http: _http };\n const name = `${"dwnScript"}-${id}`;\n await context.setVariableAsync(name, JSON.stringify(data));\n}\nasync function dwnFlushGlobalLogs(config) {\n const size = config.stackSize ? config.stackSize.logs || 10 : 10;\n if (console._logs.length === 0) return;\n let logs = [];\n try {\n const logsStr = await context.getVariableAsync("dwnLogger");\n logs = JSON.parse(logsStr || "[]");\n if (!logs || !Array.isArray(logs)) {\n throw new Error("Invalid logs format");\n }\n } catch (err) {\n logs = [];\n }\n const _logs = console._logs.map((log) => {\n const { level, message, date } = log;\n const { datetime } = formatDate(date, config);\n return `[${datetime}](${level}) ${message}`;\n });\n logs = [..._logs, ...logs].slice(0, size);\n await context.setVariableAsync("dwnLogger", JSON.stringify(logs));\n}\nasync function dwnFlushError(config, error) {\n const contract = config.connection ? config.connection.contract || "" : "";\n const key = config.connection ? config.connection.key || "" : "";\n if (!contract || !key) return;\n let category = "dwn-track-error";\n let items = [error.type, error.code || "", error.description || ""];\n let action = items.join("-|-").trim();\n const url = `https://${contract}.http.msging.net/commands`;\n const headers = {\n "Content-Type": "application/json",\n Authorization: key\n };\n const body = {\n id: Math.random().toString(36).substring(2, 15),\n to: "postmaster@analytics.msging.net",\n method: "set",\n type: "application/vnd.iris.eventTrack+json",\n uri: "/event-track",\n resource: {\n category,\n action\n }\n };\n request.fetchAsync(url, { method: "POST", headers, body });\n}\n';
|
|
235
|
+
source = source.replace(/{{script-id}}/g, id);
|
|
236
|
+
return {
|
|
237
|
+
$id,
|
|
238
|
+
$typeOfContent: "",
|
|
239
|
+
type: "ExecuteScriptV2",
|
|
240
|
+
$title: `DWN Script ${id}`,
|
|
241
|
+
settings: {
|
|
242
|
+
function: "run",
|
|
243
|
+
source,
|
|
244
|
+
inputVariables: [],
|
|
245
|
+
outputVariable: `SCRIPT${id}`,
|
|
246
|
+
LocalTimeZoneEnabled: false,
|
|
247
|
+
},
|
|
248
|
+
conditions: [],
|
|
249
|
+
};
|
|
250
|
+
};
|
|
251
|
+
exports.basicScriptTemplate = basicScriptTemplate;
|
|
252
|
+
const completeScriptTemplate = ($id) => {
|
|
253
|
+
const id = $id.substring(0, 8);
|
|
254
|
+
let source = '\nasync function dwnRun() {\n return undefined;\n}\nasync function run(...args) {\n const id = "{{script-id}}";\n const type = "complete";\n let result = await dwnProcess(id, type, dwnRun, ...args);\n return result;\n}\n/**\n * @imports\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n */\nvar DwnError = class _DwnError extends Error {\n /**\n * Creates a new DwnError instance.\n *\n * @param {string} type The error type identifier (e.g., "VALIDATION_ERROR", "SCRIPT_ERROR")\n * @param {string} description Human-readable description of what went wrong\n * @param {{message?: string, messages?: string[], stack?: string, goto?: State | null, state?: State, at?: string, intent?: string | null, content?: string, recurrence?: ErrorRecurrence, code?: string | null, status?: FINALIZATION_STATUS}} [extras] Optional additional error context and metadata:\n * - `message`: Primary error message for user display\n * - `messages`: Array of error messages for different contexts\n * - `stack`: Stack trace or execution context information\n * - `goto`: Target state to redirect to on error (null means terminate)\n * - `state`: Flow state where the error occurred\n * - `at`: Location or context where the error occurred\n * - `intent`: Associated intent that caused the error\n * - `content`: Additional error content or context\n * - `recurrence`: Information about error recurrence patterns\n * - `code`: Error code for programmatic error handling\n * - `status`: Finalization status indicating how the error was resolved\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid input provided");\n *\n * const contextError = new DwnError("SCRIPT_ERROR", "Script execution failed", {\n * state: { id: "state-123", service: "main" },\n * intent: "user-input",\n * content: "invalid data",\n * messages: ["First attempt failed", "Retry failed"],\n * goto: { id: "error-handler", service: "main" }\n * });\n * ```\n */\n constructor(type, description, extras) {\n super();\n this.name = "DwnError";\n const _extras = _DwnError.enforceExtras(extras);\n this.type = type;\n this.description = description;\n this.at = _extras.at;\n this.content = _extras.content;\n this.state = _extras.state;\n this.recurrence = _extras.recurrence;\n this.goto = _extras.goto;\n this.message = _extras.message || undefined;\n this.messages = _extras.messages || [];\n this.intent = _extras.intent || undefined;\n this.code = _extras.code || undefined;\n this.status = _extras.status || undefined;\n this.stack = _extras.stack || undefined;\n if (!this.stack) {\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, _DwnError);\n }\n }\n }\n /**\n * Creates a DwnError instance from a serialized error string.\n *\n * Parses a DWN error string in the format "TYPE -|- DESCRIPTION -|- EXTRAS_JSON"\n * and reconstructs the original DwnError instance.\n *\n * @param {string} dwnErrorString Serialized error string from toString() method\n * @returns {DwnError | undefined} DwnError instance or undefined if parsing fails\n *\n * @example\n * ```typescript\n * const errorString = "SCRIPT_ERROR -|- Execution failed -|- {...}";\n * const error = DwnError.fromDwnError(errorString);\n * ```\n */\n static fromDwnError(dwnErrorString) {\n if (!dwnErrorString) return undefined;\n const parts = dwnErrorString.split("-|-");\n let type = parts.shift();\n if (!type) {\n return undefined;\n }\n type = type.trim();\n let description = parts.shift() || "";\n if (description) {\n description = description.trim();\n }\n let extras = undefined;\n try {\n extras = JSON.parse(parts.shift() || "{}");\n } catch (e) {\n }\n if (extras) {\n return new _DwnError(type, description, extras);\n }\n return new _DwnError(type, description);\n }\n /**\n * Creates a DwnError instance from a JSON object.\n *\n * Converts a generic Error object or JSON representation into a properly\n * structured DwnError instance with all required properties.\n *\n * @param {Error} data Error object or JSON data to convert\n * @returns {DwnError} New DwnError instance\n *\n * @example\n * ```typescript\n * const jsonData = { type: "API_ERROR", description: "Request failed" };\n * const error = DwnError.fromJson(jsonData);\n * ```\n */\n static fromJson(data) {\n const extras = _DwnError.enforceExtras(data);\n return new _DwnError(data.type, data.description, extras);\n }\n /**\n * Normalizes and validates error extras properties.\n *\n * Ensures all optional properties have default values and validates the structure\n * of the extras object. Used internally to maintain consistency across error instances.\n *\n * @param {DwnError | DwnErrorExtras} [entity] Error entity or extras object to normalize\n * @returns {Required<DwnErrorExtras>} Normalized extras object with all required properties\n *\n * @internal\n */\n static enforceExtras(entity) {\n if (!entity) entity = {};\n const extras = {};\n extras.message = entity.message || "";\n extras.messages = entity.messages || [];\n extras.stack = entity.stack || "";\n extras.goto = entity.goto;\n extras.state = entity.state || { id: "", service: "" };\n extras.at = entity.at || (new Date()).toISOString();\n extras.intent = entity.intent || "";\n extras.content = entity.content || "";\n extras.recurrence = entity.recurrence || { type: 1, state: 1, combined: 1 };\n extras.code = entity.code || undefined;\n extras.status = entity.status || undefined;\n return extras;\n }\n /**\n * Serializes the error to a string format.\n *\n * Converts the DwnError instance into a parseable string format using the pattern\n * "TYPE -|- DESCRIPTION -|- EXTRAS_JSON" for storage or transmission.\n *\n * @returns {string} Serialized error string\n *\n * @example\n * ```typescript\n * const error = new DwnError("API_ERROR", "Request failed");\n * const serialized = error.toString();\n * // "API_ERROR -|- Request failed -|- {...}"\n * ```\n */\n toString() {\n const extras = JSON.stringify(_DwnError.enforceExtras(this));\n return `${this.type} -|- ${this.description} -|- ${extras}`;\n }\n /**\n * Converts the error to a JSON object.\n *\n * Serializes all error properties into a plain JavaScript object suitable\n * for JSON serialization, API responses, or logging.\n *\n * @returns {Error} Plain object representation of the error\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid data");\n * const json = error.toJson();\n * console.log(JSON.stringify(json, null, 2));\n * ```\n */\n toJson() {\n return {\n type: this.type,\n at: this.at,\n description: this.description,\n message: this.message,\n messages: this.messages || [],\n stack: this.stack || "",\n intent: this.intent,\n content: this.content,\n goto: this.goto,\n state: this.state,\n recurrence: this.recurrence\n };\n }\n};\nvar SYSTEM_DWN_ERRORS = [\n "RUNTIME_ERROR",\n "MISCONFIGURATION_ERROR"\n];\n\n\nvar Logger = class {\n constructor() {\n this._logs = [];\n }\n /**\n * Logs an informational message.\n *\n * @param {...any} args Arguments to log (objects are automatically JSON stringified)\n */\n log(...args) {\n this._log("info", ...args);\n }\n /**\n * Logs a warning message.\n *\n * @param {...any} args Arguments to log (objects are automatically JSON stringified)\n */\n warn(...args) {\n this._log("warn", ...args);\n }\n /**\n * Logs an error message.\n *\n * @param {...any} args Arguments to log (objects are automatically JSON stringified)\n */\n error(...args) {\n this._log("error", ...args);\n }\n _log(level, ...args) {\n const message = args.map((arg) => {\n let parsed = "";\n try {\n if (typeof arg !== "object") throw new Error("Not an object");\n parsed = JSON.stringify(arg);\n } catch (err) {\n try {\n parsed = String(arg);\n } catch (err2) {\n parsed = "(unserializable)";\n }\n }\n return parsed;\n }).join(" ");\n const log = { date: new Date(), message, level };\n this._logs.unshift(log);\n }\n};\nvar console = new Logger();\n\n\nvar HttpError = class extends Error {\n constructor(message, status, response) {\n super(message);\n this.name = "HttpError";\n this.status = status;\n this.response = response;\n }\n};\nvar HttpClient = class {\n constructor() {\n this._logs = [];\n }\n /**\n * Performs an HTTP request with comprehensive logging and error handling.\n *\n * Makes HTTP requests with automatic JSON handling, response validation, and detailed logging.\n * All requests and responses are logged for debugging and monitoring purposes.\n *\n * @param {{url: string, method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH", params?: {[key: string]: string}, headers?: {[key: string]: string}, body?: Record<string, any> | Array<any> | string, valid?: ((status: number) => boolean) | number[] | number, reduce?: (response: FetchResponse) => string}} config HTTP request configuration:\n * - `url`: The target URL for the HTTP request (required)\n * - `method`: HTTP method to use (defaults to "GET")\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `body`: Request body (objects/arrays are automatically JSON stringified)\n * - `valid`: Custom validation for HTTP status codes (function, array, or single number)\n * - `reduce`: Custom function to process the response before logging\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response:\n * - `status`: HTTP status code\n * - `data`: Parsed response body (JSON parsed if possible, otherwise raw string)\n * - `headers`: Response headers as key-value object\n *\n * @throws {DwnError} Throws MISCONFIGURATION_ERROR if URL is missing or method is invalid\n * @throws {HttpError} Throws HttpError if the request fails or returns invalid status code\n */\n async request(config) {\n if (!config || !config.url) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n "HTTP request must have a URL."\n );\n }\n if (config.method && !["GET", "POST", "PUT", "DELETE", "PATCH"].includes(config.method)) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `Invalid HTTP method: ${config.method}`\n );\n }\n const req = this.prepareRequest(config);\n const response = await request.fetchAsync(req.url, req.options);\n const resp = this.prepareResponse(config, response);\n const log = {\n request: req.log,\n response: resp.log,\n duration: resp.log.at.getTime() - req.log.at.getTime()\n };\n this._logs.unshift(log);\n if (!resp.success) {\n throw new HttpError(\n `HTTP request failed with status ${resp.response.status}.`,\n resp.response.status,\n resp.response\n );\n }\n return resp.response;\n }\n /**\n * Performs a GET HTTP request.\n *\n * @param {string} url The target URL for the GET request\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async get(url, config) {\n return this.request({ ...config, url, method: "GET" });\n }\n /**\n * Performs a POST HTTP request.\n *\n * @param {string} url The target URL for the POST request\n * @param {Record<string, any> | Array<any> | string} [body] Request body (objects/arrays are automatically JSON stringified)\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async post(url, body, config) {\n return this.request({ ...config, url, method: "POST", body });\n }\n /**\n * Performs a PUT HTTP request.\n *\n * @param {string} url The target URL for the PUT request\n * @param {Record<string, any> | Array<any> | string} [body] Request body (objects/arrays are automatically JSON stringified)\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async put(url, body, config) {\n return this.request({ ...config, url, method: "PUT", body });\n }\n /**\n * Performs a DELETE HTTP request.\n *\n * @param {string} url The target URL for the DELETE request\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async delete(url, config) {\n return this.request({ ...config, url, method: "DELETE" });\n }\n /**\n * Performs a PATCH HTTP request.\n *\n * @param {string} url The target URL for the PATCH request\n * @param {Record<string, any> | Array<any> | string} [body] Request body (objects/arrays are automatically JSON stringified)\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async patch(url, body, config) {\n return this.request({ ...config, url, method: "PATCH", body });\n }\n prepareRequest(config) {\n const createQueryString = (params2 = {}) => {\n const pairs = [];\n for (const [key, value] of Object.entries(params2)) {\n if (value !== undefined && value !== null) {\n const encodedKey = encodeURIComponent(key);\n const encodedValue = encodeURIComponent(String(value));\n pairs.push(`${encodedKey}=${encodedValue}`);\n }\n }\n return pairs.join("&");\n };\n const params = createQueryString(config.params || {});\n const method = config.method || "GET";\n const headers = config.headers || {};\n let length = 0;\n let body = config.body || null;\n if (body && typeof body === "object") {\n body = JSON.stringify(body);\n headers["Content-Type"] = "application/json";\n }\n if (body && typeof body === "string") {\n length = body.length;\n }\n let url = config.url;\n if (params !== "") url += `?${params}`;\n let options = {\n method,\n headers,\n body\n };\n const log = {\n at: new Date(),\n url,\n method: method || "GET",\n headers: headers || {},\n length\n };\n return { url, options, log };\n }\n prepareResponse(config, resp) {\n const { status } = resp;\n let headers = {};\n for (const header of resp.headers) {\n const key = header.key;\n const values = header.value;\n if (values.length > 0) {\n headers[key] = values[0];\n }\n }\n const length = headers["content-length"] ? parseInt(headers["content-length"], 10) : resp.body ? resp.body.length : 0;\n let data = null;\n try {\n data = JSON.parse(resp.body);\n } catch (err) {\n data = resp.body;\n }\n let valid = (status2) => status2 >= 200 && status2 < 300;\n if (config.valid) {\n if (Array.isArray(config.valid)) {\n const expectedSet = new Set(config.valid);\n valid = (status2) => expectedSet.has(status2);\n } else if (typeof config.valid === "number") {\n const expectedNumber = config.valid;\n valid = (status2) => status2 === expectedNumber;\n } else if (typeof config.valid === "function") {\n valid = config.valid;\n }\n }\n const success = valid(status);\n let reduce = (raw) => {\n let body = "";\n try {\n if (typeof raw !== "object") {\n throw new Error("Not an object");\n }\n body = JSON.stringify(raw);\n } catch (err) {\n body = String(raw);\n }\n let reduced = false;\n if (body.length > 1e3) {\n body = body.substring(0, 1e3) + "...(truncated)";\n reduced = true;\n }\n return { body, reduced };\n };\n const log = {\n at: new Date(),\n status,\n length,\n success,\n ...reduce(resp.body)\n };\n const response = {\n status,\n data,\n headers\n };\n return { response, log, success };\n }\n};\nvar http = new HttpClient();\n\n\nfunction formatDate(date, config) {\n let tzOffset = config ? config.gmt || -3 : -3;\n const dateTz = new Date(date.getTime() + tzOffset * 36e5);\n const datetimeFormatted = dateTz.toISOString().split(".")[0];\n const offsetSign = tzOffset >= 0 ? "+" : "-";\n const offsetHours = Math.abs(Math.floor(tzOffset)).toString().padStart(2, "0");\n const offsetMinutes = Math.abs(tzOffset % 1 * 60).toString().padStart(2, "0");\n return {\n datetime: `${datetimeFormatted}${offsetSign}${offsetHours}:${offsetMinutes}`,\n time: dateTz.toISOString().split("T")[1].split("Z")[0]\n };\n}\n\n\nasync function dwnProcess(id, type, fn, ...args) {\n let result = undefined;\n let error = null;\n try {\n result = await fn(...args);\n if (!id && (console._logs.length > 0 || http._logs.length > 0)) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n "Script must have an ID to capture logs."\n );\n }\n } catch (err) {\n if (err instanceof HttpError) {\n const description = `[${id}] HTTP request failed with status ${err.status}.`;\n const stack = err && err.stack ? String(err.stack) : "";\n err = new DwnError("HTTP_ERROR", description, {\n code: `S-${err.status}`,\n stack,\n goto: null\n });\n } else if (!(err instanceof DwnError)) {\n const description = `[${id}] Unexpected error ${String(err)}`;\n const stack = err && err.stack ? String(err.stack) : "";\n err = new DwnError("SCRIPT_ERROR", description, {\n stack,\n goto: null\n });\n }\n error = err;\n } finally {\n await dwnFlush(id, type, error);\n }\n if (error) {\n await context.setVariableAsync("dwnError", error.toString());\n }\n return result;\n}\nasync function dwnFlush(id, type, error = null) {\n let config = {};\n try {\n const configStr = await context.getVariableAsync("dwnConfig");\n config = JSON.parse(configStr || "");\n } catch (err) {\n }\n await dwnFlushGlobalLogs(config);\n if (type === "complete") {\n await dwnFlushLocalLogs(config, id);\n }\n if (error) {\n await dwnFlushError(config, error);\n }\n}\nasync function dwnFlushLocalLogs(config, id) {\n const { datetime } = formatDate(new Date(), config);\n const _logs = console._logs.map((log) => {\n const { level, message, date } = log;\n const { time } = formatDate(date, config);\n return `[${time}](${level}) ${message}`;\n });\n const _http = http._logs.map((log) => log);\n const data = { datetime, logs: _logs, http: _http };\n const name = `${"dwnScript"}-${id}`;\n await context.setVariableAsync(name, JSON.stringify(data));\n}\nasync function dwnFlushGlobalLogs(config) {\n const size = config.stackSize ? config.stackSize.logs || 10 : 10;\n if (console._logs.length === 0) return;\n let logs = [];\n try {\n const logsStr = await context.getVariableAsync("dwnLogger");\n logs = JSON.parse(logsStr || "[]");\n if (!logs || !Array.isArray(logs)) {\n throw new Error("Invalid logs format");\n }\n } catch (err) {\n logs = [];\n }\n const _logs = console._logs.map((log) => {\n const { level, message, date } = log;\n const { datetime } = formatDate(date, config);\n return `[${datetime}](${level}) ${message}`;\n });\n logs = [..._logs, ...logs].slice(0, size);\n await context.setVariableAsync("dwnLogger", JSON.stringify(logs));\n}\nasync function dwnFlushError(config, error) {\n const contract = config.connection ? config.connection.contract || "" : "";\n const key = config.connection ? config.connection.key || "" : "";\n if (!contract || !key) return;\n let category = "dwn-track-error";\n let items = [error.type, error.code || "", error.description || ""];\n let action = items.join("-|-").trim();\n const url = `https://${contract}.http.msging.net/commands`;\n const headers = {\n "Content-Type": "application/json",\n Authorization: key\n };\n const body = {\n id: Math.random().toString(36).substring(2, 15),\n to: "postmaster@analytics.msging.net",\n method: "set",\n type: "application/vnd.iris.eventTrack+json",\n uri: "/event-track",\n resource: {\n category,\n action\n }\n };\n request.fetchAsync(url, { method: "POST", headers, body });\n}\n';
|
|
255
|
+
source = source.replace(/{{script-id}}/g, id);
|
|
256
|
+
return {
|
|
257
|
+
$id,
|
|
258
|
+
$typeOfContent: "",
|
|
259
|
+
type: "ExecuteScriptV2",
|
|
260
|
+
$title: `DWN Script ${id}`,
|
|
261
|
+
settings: {
|
|
262
|
+
function: "run",
|
|
263
|
+
source,
|
|
264
|
+
inputVariables: [],
|
|
265
|
+
outputVariable: `SCRIPT${id}`,
|
|
266
|
+
LocalTimeZoneEnabled: false,
|
|
267
|
+
},
|
|
268
|
+
conditions: [],
|
|
269
|
+
};
|
|
270
|
+
};
|
|
271
|
+
exports.completeScriptTemplate = completeScriptTemplate;
|
|
272
|
+
const intentScriptTemplate = ($id) => {
|
|
273
|
+
const id = $id.substring(0, 8);
|
|
274
|
+
let source = '/*\nenum INTENT_TYPE { REGEX = "regex", FUZZY = "fuzzy", STATIC = "static" }\ninterface IntentSpec {\n\tid: string;\n\ttype: INTENT_TYPE;\n\tpatterns?: string[];\n}\n*/\n\n\nvar PREPARE_EXAMPLE = [\n {\n id: "REJECTED",\n label: "Intent de rejeição",\n type: "regex",\n patterns: ["nao aceito.*", "nao.*"]\n },\n {\n id: "ACCEPTED",\n label: "Intent de aceitação",\n type: "regex",\n patterns: ["aceito.*", "sim.*"]\n }\n];\nfunction dwnInputContent(text) {\n return String(text).trim().toLowerCase().normalize("NFD").replace(/[\\u0300-\\u036f]/g, "").replace(/[^a-z0-9\\s]/g, "");\n}\nfunction dwnIntentRegex(content, spec) {\n const { id, patterns } = spec;\n let intent = null;\n for (const pattern of patterns || []) {\n if (new RegExp(pattern, "i").test(content)) {\n intent = { id, type: "regex", pattern, score: 0 };\n }\n }\n return intent;\n}\nfunction dwnIntentFuzzy(content, spec) {\n const { id, patterns } = spec;\n const normalized = dwnInputContent(content);\n let intent = null;\n let highest = 0;\n function levenshtein(a, b) {\n const matrix = [];\n for (let i = 0; i <= b.length; i++) matrix[i] = [i];\n for (let j = 0; j <= a.length; j++) matrix[0][j] = j;\n for (let i = 1; i <= b.length; i++) {\n for (let j = 1; j <= a.length; j++) {\n if (b[i - 1] === a[j - 1]) {\n matrix[i][j] = matrix[i - 1][j - 1];\n } else {\n matrix[i][j] = Math.min(\n matrix[i - 1][j - 1] + 1,\n matrix[i][j - 1] + 1,\n matrix[i - 1][j] + 1\n );\n }\n }\n }\n return matrix[b.length][a.length];\n }\n for (const pattern of patterns || []) {\n const example = dwnInputContent(pattern);\n const maxLen = Math.max(normalized.length, example.length);\n const score = maxLen === 0 ? 1 : 1 - levenshtein(normalized, example) / maxLen;\n if (score > highest) {\n highest = score;\n intent = { id, type: "fuzzy", pattern, score };\n }\n }\n return intent;\n}\nfunction dwnIntentStatic(content, spec) {\n const { id, patterns } = spec;\n if ((patterns || []).includes(content)) {\n return { id, type: "static", pattern: content, score: 0 };\n }\n return null;\n}\nfunction dwnProcessIntents(content, prepare, minScore = 0.75) {\n let result = null;\n for (const spec of prepare) {\n const { type } = spec;\n if (type === "fuzzy") {\n const intent = dwnIntentFuzzy(content, spec);\n if (intent && (!result || result.score < intent.score)) {\n result = intent;\n }\n continue;\n }\n if (type === "regex") {\n const intent = dwnIntentRegex(content, spec);\n if (intent) {\n result = intent;\n break;\n }\n }\n if (type === "static") {\n const intent = dwnIntentStatic(content, spec);\n if (intent) {\n result = intent;\n break;\n }\n }\n }\n if (result && result.type === "fuzzy" && result.score < minScore) {\n result = null;\n }\n return result;\n}\nasync function dwnRun(...args) {\n const intents = [\n // TODO: define your intents\n ];\n const content = "";\n const intent = dwnProcessIntents(content, intents);\n return JSON.stringify({ intent });\n}\nasync function run(...args) {\n const id = "{{script-id}}";\n const type = "basic";\n return await dwnProcess(id, type, dwnRun, ...args);\n}\n/**\n * @imports\n * @version 2.0.3\n * @copyright 2026 Dawntech. All rights reserved.\n * @license All Rights Reserved\n */\nvar DwnError = class _DwnError extends Error {\n /**\n * Creates a new DwnError instance.\n *\n * @param {string} type The error type identifier (e.g., "VALIDATION_ERROR", "SCRIPT_ERROR")\n * @param {string} description Human-readable description of what went wrong\n * @param {{message?: string, messages?: string[], stack?: string, goto?: State | null, state?: State, at?: string, intent?: string | null, content?: string, recurrence?: ErrorRecurrence, code?: string | null, status?: FINALIZATION_STATUS}} [extras] Optional additional error context and metadata:\n * - `message`: Primary error message for user display\n * - `messages`: Array of error messages for different contexts\n * - `stack`: Stack trace or execution context information\n * - `goto`: Target state to redirect to on error (null means terminate)\n * - `state`: Flow state where the error occurred\n * - `at`: Location or context where the error occurred\n * - `intent`: Associated intent that caused the error\n * - `content`: Additional error content or context\n * - `recurrence`: Information about error recurrence patterns\n * - `code`: Error code for programmatic error handling\n * - `status`: Finalization status indicating how the error was resolved\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid input provided");\n *\n * const contextError = new DwnError("SCRIPT_ERROR", "Script execution failed", {\n * state: { id: "state-123", service: "main" },\n * intent: "user-input",\n * content: "invalid data",\n * messages: ["First attempt failed", "Retry failed"],\n * goto: { id: "error-handler", service: "main" }\n * });\n * ```\n */\n constructor(type, description, extras) {\n super();\n this.name = "DwnError";\n const _extras = _DwnError.enforceExtras(extras);\n this.type = type;\n this.description = description;\n this.at = _extras.at;\n this.content = _extras.content;\n this.state = _extras.state;\n this.recurrence = _extras.recurrence;\n this.goto = _extras.goto;\n this.message = _extras.message || undefined;\n this.messages = _extras.messages || [];\n this.intent = _extras.intent || undefined;\n this.code = _extras.code || undefined;\n this.status = _extras.status || undefined;\n this.stack = _extras.stack || undefined;\n if (!this.stack) {\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, _DwnError);\n }\n }\n }\n /**\n * Creates a DwnError instance from a serialized error string.\n *\n * Parses a DWN error string in the format "TYPE -|- DESCRIPTION -|- EXTRAS_JSON"\n * and reconstructs the original DwnError instance.\n *\n * @param {string} dwnErrorString Serialized error string from toString() method\n * @returns {DwnError | undefined} DwnError instance or undefined if parsing fails\n *\n * @example\n * ```typescript\n * const errorString = "SCRIPT_ERROR -|- Execution failed -|- {...}";\n * const error = DwnError.fromDwnError(errorString);\n * ```\n */\n static fromDwnError(dwnErrorString) {\n if (!dwnErrorString) return undefined;\n const parts = dwnErrorString.split("-|-");\n let type = parts.shift();\n if (!type) {\n return undefined;\n }\n type = type.trim();\n let description = parts.shift() || "";\n if (description) {\n description = description.trim();\n }\n let extras = undefined;\n try {\n extras = JSON.parse(parts.shift() || "{}");\n } catch (e) {\n }\n if (extras) {\n return new _DwnError(type, description, extras);\n }\n return new _DwnError(type, description);\n }\n /**\n * Creates a DwnError instance from a JSON object.\n *\n * Converts a generic Error object or JSON representation into a properly\n * structured DwnError instance with all required properties.\n *\n * @param {Error} data Error object or JSON data to convert\n * @returns {DwnError} New DwnError instance\n *\n * @example\n * ```typescript\n * const jsonData = { type: "API_ERROR", description: "Request failed" };\n * const error = DwnError.fromJson(jsonData);\n * ```\n */\n static fromJson(data) {\n const extras = _DwnError.enforceExtras(data);\n return new _DwnError(data.type, data.description, extras);\n }\n /**\n * Normalizes and validates error extras properties.\n *\n * Ensures all optional properties have default values and validates the structure\n * of the extras object. Used internally to maintain consistency across error instances.\n *\n * @param {DwnError | DwnErrorExtras} [entity] Error entity or extras object to normalize\n * @returns {Required<DwnErrorExtras>} Normalized extras object with all required properties\n *\n * @internal\n */\n static enforceExtras(entity) {\n if (!entity) entity = {};\n const extras = {};\n extras.message = entity.message || "";\n extras.messages = entity.messages || [];\n extras.stack = entity.stack || "";\n extras.goto = entity.goto;\n extras.state = entity.state || { id: "", service: "" };\n extras.at = entity.at || (new Date()).toISOString();\n extras.intent = entity.intent || "";\n extras.content = entity.content || "";\n extras.recurrence = entity.recurrence || { type: 1, state: 1, combined: 1 };\n extras.code = entity.code || undefined;\n extras.status = entity.status || undefined;\n return extras;\n }\n /**\n * Serializes the error to a string format.\n *\n * Converts the DwnError instance into a parseable string format using the pattern\n * "TYPE -|- DESCRIPTION -|- EXTRAS_JSON" for storage or transmission.\n *\n * @returns {string} Serialized error string\n *\n * @example\n * ```typescript\n * const error = new DwnError("API_ERROR", "Request failed");\n * const serialized = error.toString();\n * // "API_ERROR -|- Request failed -|- {...}"\n * ```\n */\n toString() {\n const extras = JSON.stringify(_DwnError.enforceExtras(this));\n return `${this.type} -|- ${this.description} -|- ${extras}`;\n }\n /**\n * Converts the error to a JSON object.\n *\n * Serializes all error properties into a plain JavaScript object suitable\n * for JSON serialization, API responses, or logging.\n *\n * @returns {Error} Plain object representation of the error\n *\n * @example\n * ```typescript\n * const error = new DwnError("VALIDATION_ERROR", "Invalid data");\n * const json = error.toJson();\n * console.log(JSON.stringify(json, null, 2));\n * ```\n */\n toJson() {\n return {\n type: this.type,\n at: this.at,\n description: this.description,\n message: this.message,\n messages: this.messages || [],\n stack: this.stack || "",\n intent: this.intent,\n content: this.content,\n goto: this.goto,\n state: this.state,\n recurrence: this.recurrence\n };\n }\n};\nvar SYSTEM_DWN_ERRORS = [\n "RUNTIME_ERROR",\n "MISCONFIGURATION_ERROR"\n];\n\n\nvar Logger = class {\n constructor() {\n this._logs = [];\n }\n /**\n * Logs an informational message.\n *\n * @param {...any} args Arguments to log (objects are automatically JSON stringified)\n */\n log(...args) {\n this._log("info", ...args);\n }\n /**\n * Logs a warning message.\n *\n * @param {...any} args Arguments to log (objects are automatically JSON stringified)\n */\n warn(...args) {\n this._log("warn", ...args);\n }\n /**\n * Logs an error message.\n *\n * @param {...any} args Arguments to log (objects are automatically JSON stringified)\n */\n error(...args) {\n this._log("error", ...args);\n }\n _log(level, ...args) {\n const message = args.map((arg) => {\n let parsed = "";\n try {\n if (typeof arg !== "object") throw new Error("Not an object");\n parsed = JSON.stringify(arg);\n } catch (err) {\n try {\n parsed = String(arg);\n } catch (err2) {\n parsed = "(unserializable)";\n }\n }\n return parsed;\n }).join(" ");\n const log = { date: new Date(), message, level };\n this._logs.unshift(log);\n }\n};\nvar console = new Logger();\n\n\nvar HttpError = class extends Error {\n constructor(message, status, response) {\n super(message);\n this.name = "HttpError";\n this.status = status;\n this.response = response;\n }\n};\nvar HttpClient = class {\n constructor() {\n this._logs = [];\n }\n /**\n * Performs an HTTP request with comprehensive logging and error handling.\n *\n * Makes HTTP requests with automatic JSON handling, response validation, and detailed logging.\n * All requests and responses are logged for debugging and monitoring purposes.\n *\n * @param {{url: string, method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH", params?: {[key: string]: string}, headers?: {[key: string]: string}, body?: Record<string, any> | Array<any> | string, valid?: ((status: number) => boolean) | number[] | number, reduce?: (response: FetchResponse) => string}} config HTTP request configuration:\n * - `url`: The target URL for the HTTP request (required)\n * - `method`: HTTP method to use (defaults to "GET")\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `body`: Request body (objects/arrays are automatically JSON stringified)\n * - `valid`: Custom validation for HTTP status codes (function, array, or single number)\n * - `reduce`: Custom function to process the response before logging\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response:\n * - `status`: HTTP status code\n * - `data`: Parsed response body (JSON parsed if possible, otherwise raw string)\n * - `headers`: Response headers as key-value object\n *\n * @throws {DwnError} Throws MISCONFIGURATION_ERROR if URL is missing or method is invalid\n * @throws {HttpError} Throws HttpError if the request fails or returns invalid status code\n */\n async request(config) {\n if (!config || !config.url) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n "HTTP request must have a URL."\n );\n }\n if (config.method && !["GET", "POST", "PUT", "DELETE", "PATCH"].includes(config.method)) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n `Invalid HTTP method: ${config.method}`\n );\n }\n const req = this.prepareRequest(config);\n const response = await request.fetchAsync(req.url, req.options);\n const resp = this.prepareResponse(config, response);\n const log = {\n request: req.log,\n response: resp.log,\n duration: resp.log.at.getTime() - req.log.at.getTime()\n };\n this._logs.unshift(log);\n if (!resp.success) {\n throw new HttpError(\n `HTTP request failed with status ${resp.response.status}.`,\n resp.response.status,\n resp.response\n );\n }\n return resp.response;\n }\n /**\n * Performs a GET HTTP request.\n *\n * @param {string} url The target URL for the GET request\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async get(url, config) {\n return this.request({ ...config, url, method: "GET" });\n }\n /**\n * Performs a POST HTTP request.\n *\n * @param {string} url The target URL for the POST request\n * @param {Record<string, any> | Array<any> | string} [body] Request body (objects/arrays are automatically JSON stringified)\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async post(url, body, config) {\n return this.request({ ...config, url, method: "POST", body });\n }\n /**\n * Performs a PUT HTTP request.\n *\n * @param {string} url The target URL for the PUT request\n * @param {Record<string, any> | Array<any> | string} [body] Request body (objects/arrays are automatically JSON stringified)\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async put(url, body, config) {\n return this.request({ ...config, url, method: "PUT", body });\n }\n /**\n * Performs a DELETE HTTP request.\n *\n * @param {string} url The target URL for the DELETE request\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async delete(url, config) {\n return this.request({ ...config, url, method: "DELETE" });\n }\n /**\n * Performs a PATCH HTTP request.\n *\n * @param {string} url The target URL for the PATCH request\n * @param {Record<string, any> | Array<any> | string} [body] Request body (objects/arrays are automatically JSON stringified)\n * @param {{params?: {[key: string]: string}, headers?: {[key: string]: string}, valid?: ((status: number) => boolean) | number[] | number}} [config] Optional request configuration:\n * - `params`: Query parameters to append to the URL\n * - `headers`: HTTP headers to include in the request\n * - `valid`: Custom validation for HTTP status codes\n *\n * @returns {Promise<{status: number, data: any, headers: {[key: string]: string}}>} Promise resolving to HTTP response\n */\n async patch(url, body, config) {\n return this.request({ ...config, url, method: "PATCH", body });\n }\n prepareRequest(config) {\n const createQueryString = (params2 = {}) => {\n const pairs = [];\n for (const [key, value] of Object.entries(params2)) {\n if (value !== undefined && value !== null) {\n const encodedKey = encodeURIComponent(key);\n const encodedValue = encodeURIComponent(String(value));\n pairs.push(`${encodedKey}=${encodedValue}`);\n }\n }\n return pairs.join("&");\n };\n const params = createQueryString(config.params || {});\n const method = config.method || "GET";\n const headers = config.headers || {};\n let length = 0;\n let body = config.body || null;\n if (body && typeof body === "object") {\n body = JSON.stringify(body);\n headers["Content-Type"] = "application/json";\n }\n if (body && typeof body === "string") {\n length = body.length;\n }\n let url = config.url;\n if (params !== "") url += `?${params}`;\n let options = {\n method,\n headers,\n body\n };\n const log = {\n at: new Date(),\n url,\n method: method || "GET",\n headers: headers || {},\n length\n };\n return { url, options, log };\n }\n prepareResponse(config, resp) {\n const { status } = resp;\n let headers = {};\n for (const header of resp.headers) {\n const key = header.key;\n const values = header.value;\n if (values.length > 0) {\n headers[key] = values[0];\n }\n }\n const length = headers["content-length"] ? parseInt(headers["content-length"], 10) : resp.body ? resp.body.length : 0;\n let data = null;\n try {\n data = JSON.parse(resp.body);\n } catch (err) {\n data = resp.body;\n }\n let valid = (status2) => status2 >= 200 && status2 < 300;\n if (config.valid) {\n if (Array.isArray(config.valid)) {\n const expectedSet = new Set(config.valid);\n valid = (status2) => expectedSet.has(status2);\n } else if (typeof config.valid === "number") {\n const expectedNumber = config.valid;\n valid = (status2) => status2 === expectedNumber;\n } else if (typeof config.valid === "function") {\n valid = config.valid;\n }\n }\n const success = valid(status);\n let reduce = (raw) => {\n let body = "";\n try {\n if (typeof raw !== "object") {\n throw new Error("Not an object");\n }\n body = JSON.stringify(raw);\n } catch (err) {\n body = String(raw);\n }\n let reduced = false;\n if (body.length > 1e3) {\n body = body.substring(0, 1e3) + "...(truncated)";\n reduced = true;\n }\n return { body, reduced };\n };\n const log = {\n at: new Date(),\n status,\n length,\n success,\n ...reduce(resp.body)\n };\n const response = {\n status,\n data,\n headers\n };\n return { response, log, success };\n }\n};\nvar http = new HttpClient();\n\n\nfunction formatDate(date, config) {\n let tzOffset = config ? config.gmt || -3 : -3;\n const dateTz = new Date(date.getTime() + tzOffset * 36e5);\n const datetimeFormatted = dateTz.toISOString().split(".")[0];\n const offsetSign = tzOffset >= 0 ? "+" : "-";\n const offsetHours = Math.abs(Math.floor(tzOffset)).toString().padStart(2, "0");\n const offsetMinutes = Math.abs(tzOffset % 1 * 60).toString().padStart(2, "0");\n return {\n datetime: `${datetimeFormatted}${offsetSign}${offsetHours}:${offsetMinutes}`,\n time: dateTz.toISOString().split("T")[1].split("Z")[0]\n };\n}\n\n\nasync function dwnProcess(id, type, fn, ...args) {\n let result = undefined;\n let error = null;\n try {\n result = await fn(...args);\n if (!id && (console._logs.length > 0 || http._logs.length > 0)) {\n throw new DwnError(\n "MISCONFIGURATION_ERROR",\n "Script must have an ID to capture logs."\n );\n }\n } catch (err) {\n if (err instanceof HttpError) {\n const description = `[${id}] HTTP request failed with status ${err.status}.`;\n const stack = err && err.stack ? String(err.stack) : "";\n err = new DwnError("HTTP_ERROR", description, {\n code: `S-${err.status}`,\n stack,\n goto: null\n });\n } else if (!(err instanceof DwnError)) {\n const description = `[${id}] Unexpected error ${String(err)}`;\n const stack = err && err.stack ? String(err.stack) : "";\n err = new DwnError("SCRIPT_ERROR", description, {\n stack,\n goto: null\n });\n }\n error = err;\n } finally {\n await dwnFlush(id, type, error);\n }\n if (error) {\n await context.setVariableAsync("dwnError", error.toString());\n }\n return result;\n}\nasync function dwnFlush(id, type, error = null) {\n let config = {};\n try {\n const configStr = await context.getVariableAsync("dwnConfig");\n config = JSON.parse(configStr || "");\n } catch (err) {\n }\n await dwnFlushGlobalLogs(config);\n if (type === "complete") {\n await dwnFlushLocalLogs(config, id);\n }\n if (error) {\n await dwnFlushError(config, error);\n }\n}\nasync function dwnFlushLocalLogs(config, id) {\n const { datetime } = formatDate(new Date(), config);\n const _logs = console._logs.map((log) => {\n const { level, message, date } = log;\n const { time } = formatDate(date, config);\n return `[${time}](${level}) ${message}`;\n });\n const _http = http._logs.map((log) => log);\n const data = { datetime, logs: _logs, http: _http };\n const name = `${"dwnScript"}-${id}`;\n await context.setVariableAsync(name, JSON.stringify(data));\n}\nasync function dwnFlushGlobalLogs(config) {\n const size = config.stackSize ? config.stackSize.logs || 10 : 10;\n if (console._logs.length === 0) return;\n let logs = [];\n try {\n const logsStr = await context.getVariableAsync("dwnLogger");\n logs = JSON.parse(logsStr || "[]");\n if (!logs || !Array.isArray(logs)) {\n throw new Error("Invalid logs format");\n }\n } catch (err) {\n logs = [];\n }\n const _logs = console._logs.map((log) => {\n const { level, message, date } = log;\n const { datetime } = formatDate(date, config);\n return `[${datetime}](${level}) ${message}`;\n });\n logs = [..._logs, ...logs].slice(0, size);\n await context.setVariableAsync("dwnLogger", JSON.stringify(logs));\n}\nasync function dwnFlushError(config, error) {\n const contract = config.connection ? config.connection.contract || "" : "";\n const key = config.connection ? config.connection.key || "" : "";\n if (!contract || !key) return;\n let category = "dwn-track-error";\n let items = [error.type, error.code || "", error.description || ""];\n let action = items.join("-|-").trim();\n const url = `https://${contract}.http.msging.net/commands`;\n const headers = {\n "Content-Type": "application/json",\n Authorization: key\n };\n const body = {\n id: Math.random().toString(36).substring(2, 15),\n to: "postmaster@analytics.msging.net",\n method: "set",\n type: "application/vnd.iris.eventTrack+json",\n uri: "/event-track",\n resource: {\n category,\n action\n }\n };\n request.fetchAsync(url, { method: "POST", headers, body });\n}\n';
|
|
275
|
+
source = source.replace(/{{script-id}}/g, id);
|
|
276
|
+
return {
|
|
277
|
+
$id,
|
|
278
|
+
$typeOfContent: "",
|
|
279
|
+
type: "ExecuteScriptV2",
|
|
280
|
+
$title: `DWN Intent ${id}`,
|
|
281
|
+
settings: {
|
|
282
|
+
function: "run",
|
|
283
|
+
source,
|
|
284
|
+
inputVariables: [],
|
|
285
|
+
outputVariable: `INTENT${id}`,
|
|
286
|
+
LocalTimeZoneEnabled: false,
|
|
287
|
+
},
|
|
288
|
+
conditions: [],
|
|
289
|
+
};
|
|
290
|
+
};
|
|
291
|
+
exports.intentScriptTemplate = intentScriptTemplate;
|
|
292
|
+
//# sourceMappingURL=scripts.js.map
|