@lovrabet/rabetbase-cli 2.5.13 → 2.6.0-beta.2
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/README.md +42 -17
- package/lib/api/api-doc.js +3 -1
- package/lib/api/api-group.js +3 -1
- package/lib/api/fetch-model-list.js +1 -1
- package/lib/api/generate-api-file.js +8 -1
- package/lib/api/generate-sdk-config-file.js +1 -1
- package/lib/api/legacy-api-file.js +2 -1
- package/lib/api/model-registry-file.js +11 -1
- package/lib/api/model-registry-scaffold.js +2 -1
- package/lib/api/model-source.js +3 -1
- package/lib/auth/auth-server-ui.js +2 -1
- package/lib/auth/auth-server.js +5 -1
- package/lib/auth/constant.js +1 -1
- package/lib/auth/get-cookie.js +1 -1
- package/lib/auth/get-session-user.js +1 -1
- package/lib/auth/is-session-valid.js +1 -1
- package/lib/auth/login-success-html.js +3 -1
- package/lib/auth/logout.js +1 -1
- package/lib/cli-flags.js +1 -1
- package/lib/cli.js +5 -1
- package/lib/commands/api/generate.js +4 -1
- package/lib/commands/api/index.js +1 -1
- package/lib/commands/api/list.js +2 -1
- package/lib/commands/api/pull.js +10 -1
- package/lib/commands/api/shared.js +1 -1
- package/lib/commands/app/detail.js +1 -1
- package/lib/commands/app/index.js +1 -1
- package/lib/commands/app/list.js +5 -1
- package/lib/commands/app/members-list.js +1 -1
- package/lib/commands/app/remote-directory.js +1 -1
- package/lib/commands/app/shared.js +4 -1
- package/lib/commands/app-config/delete.js +2 -1
- package/lib/commands/app-config/get.js +2 -1
- package/lib/commands/app-config/index.js +1 -1
- package/lib/commands/app-config/list.js +2 -1
- package/lib/commands/app-config/set.js +3 -1
- package/lib/commands/app-config/shared.d.ts +9 -2
- package/lib/commands/app-config/shared.js +6 -1
- package/lib/commands/auth/index.js +1 -1
- package/lib/commands/bff/create.js +11 -1
- package/lib/commands/bff/delete.js +6 -1
- package/lib/commands/bff/detail.js +1 -1
- package/lib/commands/bff/index.js +1 -1
- package/lib/commands/bff/list.js +1 -1
- package/lib/commands/bff/logs.js +4 -1
- package/lib/commands/bff/pull.js +22 -1
- package/lib/commands/bff/push.js +16 -1
- package/lib/commands/bff/status.js +3 -1
- package/lib/commands/cli-skill/index.js +2 -1
- package/lib/commands/cli-update.js +7 -1
- package/lib/commands/codegen/index.js +1 -1
- package/lib/commands/codegen/sdk.js +1 -1
- package/lib/commands/codegen/sql.js +1 -1
- package/lib/commands/common/app-registry.js +4 -1
- package/lib/commands/common/app-selector.js +4 -1
- package/lib/commands/common/async-task.js +2 -1
- package/lib/commands/common/dry-run.js +1 -1
- package/lib/commands/common/flags.js +3 -1
- package/lib/commands/common/local-file.js +1 -1
- package/lib/commands/common/validate.js +1 -1
- package/lib/commands/config/delete.js +2 -1
- package/lib/commands/config/get.js +1 -1
- package/lib/commands/config/index.js +1 -1
- package/lib/commands/config/init.js +5 -1
- package/lib/commands/config/list.js +1 -1
- package/lib/commands/config/set.js +4 -1
- package/lib/commands/config/shared.js +2 -1
- package/lib/commands/dataset/batch-design.js +9 -1
- package/lib/commands/dataset/business-group-update.js +10 -1
- package/lib/commands/dataset/business-groups.js +1 -1
- package/lib/commands/dataset/capability.js +3 -1
- package/lib/commands/dataset/cross-relation-create.js +2 -1
- package/lib/commands/dataset/cross-relation-delete.js +1 -1
- package/lib/commands/dataset/cross-relation-list.js +2 -1
- package/lib/commands/dataset/cross-relation-shared.js +10 -1
- package/lib/commands/dataset/cross-relation-update.js +2 -1
- package/lib/commands/dataset/delete.js +6 -1
- package/lib/commands/dataset/design-context.js +1 -1
- package/lib/commands/dataset/design-start.js +1 -1
- package/lib/commands/dataset/design-status.js +1 -1
- package/lib/commands/dataset/design-sync-retry.js +1 -1
- package/lib/commands/dataset/design-sync-status.js +1 -1
- package/lib/commands/dataset/design-validate.js +1 -1
- package/lib/commands/dataset/detail.js +5 -1
- package/lib/commands/dataset/extend-update.js +7 -1
- package/lib/commands/dataset/field-restore.js +7 -1
- package/lib/commands/dataset/field-update.js +7 -1
- package/lib/commands/dataset/generate.js +19 -1
- package/lib/commands/dataset/index.js +3 -1
- package/lib/commands/dataset/list.js +2 -1
- package/lib/commands/dataset/operations.js +2 -1
- package/lib/commands/dataset/relation-audit.js +7 -1
- package/lib/commands/dataset/relation-create.js +3 -1
- package/lib/commands/dataset/relation-delete.js +3 -1
- package/lib/commands/dataset/relation-shared.js +21 -1
- package/lib/commands/dataset/relation-update.js +4 -1
- package/lib/commands/dataset/relations.js +7 -1
- package/lib/commands/dataset/rename.js +4 -1
- package/lib/commands/dataset/restore.js +7 -1
- package/lib/commands/dataset/user-deleted-field-list.js +3 -1
- package/lib/commands/db/analysis-batching.js +3 -1
- package/lib/commands/db/analyze-batch-plan.js +2 -1
- package/lib/commands/db/analyze-cancel.js +1 -1
- package/lib/commands/db/analyze-start.js +3 -1
- package/lib/commands/db/analyze-status.js +6 -1
- package/lib/commands/db/create.js +4 -1
- package/lib/commands/db/cross-db-analysis-shared.js +3 -1
- package/lib/commands/db/cross-db-analyze-latest.js +1 -1
- package/lib/commands/db/cross-db-analyze-start.js +2 -1
- package/lib/commands/db/cross-db-analyze-status.js +1 -1
- package/lib/commands/db/delete.js +3 -1
- package/lib/commands/db/detail.js +1 -1
- package/lib/commands/db/diff-refresh-start.js +1 -1
- package/lib/commands/db/diff-refresh-status.js +2 -1
- package/lib/commands/db/diff.js +3 -1
- package/lib/commands/db/index.js +2 -1
- package/lib/commands/db/list.js +2 -1
- package/lib/commands/db/shared.js +3 -1
- package/lib/commands/db/table-diff-shared.js +2 -1
- package/lib/commands/db/tables.js +2 -1
- package/lib/commands/db/test.js +2 -1
- package/lib/commands/db/update.js +4 -1
- package/lib/commands/deployment/index.js +1 -1
- package/lib/commands/deployment/sync-all.js +3 -1
- package/lib/commands/deployment/sync-jobs.js +2 -1
- package/lib/commands/deployment/sync-status.js +2 -1
- package/lib/commands/doctor.js +12 -1
- package/lib/commands/file/index.js +3 -1
- package/lib/commands/flow/create.js +2 -1
- package/lib/commands/flow/detail.js +3 -1
- package/lib/commands/flow/index.js +1 -1
- package/lib/commands/flow/list.js +2 -1
- package/lib/commands/flow/page-list.js +2 -1
- package/lib/commands/flow/publish.js +2 -1
- package/lib/commands/flow/runtime-resources-shared.js +3 -1
- package/lib/commands/flow/runtime-role-list.js +2 -1
- package/lib/commands/flow/runtime-role-user-list.js +2 -1
- package/lib/commands/flow/runtime-user-search.js +2 -1
- package/lib/commands/flow/shared.js +6 -1
- package/lib/commands/flow/update.js +4 -1
- package/lib/commands/flow/validate.js +2 -1
- package/lib/commands/instant-api-policy/current.js +1 -1
- package/lib/commands/instant-api-policy/index.js +1 -1
- package/lib/commands/instant-api-policy/init.js +2 -1
- package/lib/commands/instant-api-policy/publish.js +5 -1
- package/lib/commands/instant-api-policy/pull.js +2 -1
- package/lib/commands/instant-api-policy/revision.js +1 -1
- package/lib/commands/instant-api-policy/revisions.js +1 -1
- package/lib/commands/instant-api-policy/rollback.js +5 -1
- package/lib/commands/instant-api-policy/shared.js +5 -1
- package/lib/commands/instant-api-policy/validate.js +1 -1
- package/lib/commands/issue/context.js +1 -1
- package/lib/commands/issue/index.js +1 -1
- package/lib/commands/issue/nudge.js +2 -1
- package/lib/commands/issue/report.js +5 -1
- package/lib/commands/kb/create.js +5 -1
- package/lib/commands/kb/delete.js +5 -1
- package/lib/commands/kb/detail.js +1 -1
- package/lib/commands/kb/import-api.d.ts +3 -0
- package/lib/commands/kb/import-api.js +1 -0
- package/lib/commands/kb/import-resume.d.ts +2 -0
- package/lib/commands/kb/import-resume.js +2 -0
- package/lib/commands/kb/import-shared.d.ts +69 -0
- package/lib/commands/kb/import-shared.js +9 -0
- package/lib/commands/kb/import-status.d.ts +2 -0
- package/lib/commands/kb/import-status.js +1 -0
- package/lib/commands/kb/import.d.ts +2 -0
- package/lib/commands/kb/import.js +3 -0
- package/lib/commands/kb/index.js +1 -1
- package/lib/commands/kb/list.js +1 -1
- package/lib/commands/kb/search.js +3 -1
- package/lib/commands/kb/shared.js +9 -1
- package/lib/commands/kb/update.js +7 -1
- package/lib/commands/logs/index.js +2 -1
- package/lib/commands/menu/asset-update.js +8 -1
- package/lib/commands/menu/delete.js +15 -1
- package/lib/commands/menu/external-link-create.js +16 -1
- package/lib/commands/menu/external-link-update.js +10 -1
- package/lib/commands/menu/group-create.js +8 -1
- package/lib/commands/menu/group-update.js +6 -1
- package/lib/commands/menu/index.js +2 -1
- package/lib/commands/menu/list.js +1 -1
- package/lib/commands/menu/move.js +6 -1
- package/lib/commands/menu/regroup-start.js +11 -1
- package/lib/commands/menu/rename.js +9 -1
- package/lib/commands/menu/shared/compare-table.js +2 -1
- package/lib/commands/menu/shared/delete-plan.js +13 -1
- package/lib/commands/menu/shared/facts.js +5 -1
- package/lib/commands/menu/shared/index.js +1 -1
- package/lib/commands/menu/shared/inquirer.js +4 -1
- package/lib/commands/menu/shared/local-pages.js +5 -1
- package/lib/commands/menu/shared/logic.js +3 -1
- package/lib/commands/menu/shared/mutations.js +9 -1
- package/lib/commands/menu/shared/path.js +1 -1
- package/lib/commands/menu/shared/service.js +4 -1
- package/lib/commands/menu/shared/subapp-assets.js +4 -1
- package/lib/commands/menu/shared/sync-core.js +7 -1
- package/lib/commands/menu/shared/types.js +1 -1
- package/lib/commands/menu/shared/update-core.js +8 -1
- package/lib/commands/menu/shared/valid-url.js +1 -1
- package/lib/commands/menu/subapp-assets-status.js +1 -1
- package/lib/commands/menu/subapp-assets-update.js +7 -1
- package/lib/commands/menu/sync.js +7 -1
- package/lib/commands/menu/visibility-update.js +13 -1
- package/lib/commands/metric/contract.d.ts +8 -0
- package/lib/commands/metric/contract.js +5 -0
- package/lib/commands/metric/definition.d.ts +43 -0
- package/lib/commands/metric/definition.js +4 -0
- package/lib/commands/metric/delete.d.ts +2 -0
- package/lib/commands/metric/delete.js +3 -0
- package/lib/commands/metric/detail.d.ts +2 -0
- package/lib/commands/metric/detail.js +1 -0
- package/lib/commands/metric/example.d.ts +2 -0
- package/lib/commands/metric/example.js +1 -0
- package/lib/commands/metric/index.d.ts +2 -0
- package/lib/commands/metric/index.js +1 -0
- package/lib/commands/metric/list.d.ts +2 -0
- package/lib/commands/metric/list.js +2 -0
- package/lib/commands/metric/publication-diff.d.ts +8 -0
- package/lib/commands/metric/publication-diff.js +1 -0
- package/lib/commands/metric/publish.d.ts +2 -0
- package/lib/commands/metric/publish.js +4 -0
- package/lib/commands/metric/schema.d.ts +2 -0
- package/lib/commands/metric/schema.js +1 -0
- package/lib/commands/metric/shared.d.ts +14 -0
- package/lib/commands/metric/shared.js +2 -0
- package/lib/commands/metric/validate.d.ts +2 -0
- package/lib/commands/metric/validate.js +1 -0
- package/lib/commands/notification/config-create.js +4 -1
- package/lib/commands/notification/config-delete.js +4 -1
- package/lib/commands/notification/config-list.js +2 -1
- package/lib/commands/notification/config-update.js +4 -1
- package/lib/commands/notification/index.js +1 -1
- package/lib/commands/notification/shared.js +18 -1
- package/lib/commands/ocr/index.js +4 -1
- package/lib/commands/page/create.js +6 -1
- package/lib/commands/page/custom/detail.js +2 -1
- package/lib/commands/page/custom/list.js +2 -1
- package/lib/commands/page/custom/publish.js +3 -1
- package/lib/commands/page/custom/shared.js +3 -1
- package/lib/commands/page/custom/syntax.js +2 -1
- package/lib/commands/page/custom/update.js +3 -1
- package/lib/commands/page/data-list-status.js +2 -1
- package/lib/commands/page/generate-start.js +5 -1
- package/lib/commands/page/generate-status.js +4 -1
- package/lib/commands/page/index.js +2 -1
- package/lib/commands/page/pull.js +6 -1
- package/lib/commands/page/push.js +11 -1
- package/lib/commands/page/relation-audit.js +15 -1
- package/lib/commands/page/restore.js +5 -1
- package/lib/commands/page/shared.js +16 -1
- package/lib/commands/page/sync.js +2 -1
- package/lib/commands/project/api-architecture-upgrade.js +11 -1
- package/lib/commands/project/create/enhanced-guided-create.js +2 -1
- package/lib/commands/project/create/format-elapsed.js +1 -1
- package/lib/commands/project/create/main.js +13 -1
- package/lib/commands/project/create/materialize-project-template.js +12 -1
- package/lib/commands/project/create/project-name.js +1 -1
- package/lib/commands/project/create/project-template-archive.js +5 -1
- package/lib/commands/project/create/project-template-path.js +1 -1
- package/lib/commands/project/create/use-copy-project-template.js +2 -1
- package/lib/commands/project/create/use-format-code.js +1 -1
- package/lib/commands/project/create/use-install-dependencies.js +1 -1
- package/lib/commands/project/domain-routing-sync.js +1 -1
- package/lib/commands/project/index.js +4 -1
- package/lib/commands/project/upgrade.js +7 -1
- package/lib/commands/registry.js +10 -1
- package/lib/commands/role/delete.js +2 -1
- package/lib/commands/role/detail.js +1 -1
- package/lib/commands/role/index.js +1 -1
- package/lib/commands/role/list.js +2 -1
- package/lib/commands/role/shared.js +8 -1
- package/lib/commands/role/update.js +3 -1
- package/lib/commands/role/user-add.js +2 -1
- package/lib/commands/role/user-remove.js +2 -1
- package/lib/commands/role/user-resolve.js +1 -1
- package/lib/commands/rule/get.js +1 -1
- package/lib/commands/rule/index.js +1 -1
- package/lib/commands/rule/list.js +1 -1
- package/lib/commands/rule/set.js +7 -1
- package/lib/commands/rule/shared.js +4 -1
- package/lib/commands/run/index.js +5 -1
- package/lib/commands/schema.js +1 -1
- package/lib/commands/sql/create.js +7 -1
- package/lib/commands/sql/delete.js +4 -1
- package/lib/commands/sql/detail.js +1 -1
- package/lib/commands/sql/exec.js +1 -1
- package/lib/commands/sql/index.js +1 -1
- package/lib/commands/sql/list.js +2 -1
- package/lib/commands/sql/pull.js +10 -1
- package/lib/commands/sql/push.js +9 -1
- package/lib/commands/sql/shared.js +5 -1
- package/lib/commands/sql/status.js +3 -1
- package/lib/commands/sql/validate.js +5 -1
- package/lib/commands/task/index.js +1 -1
- package/lib/commands/task/status.js +2 -1
- package/lib/commands/tenant/index.js +1 -1
- package/lib/commands/tenant/members-list.js +2 -1
- package/lib/commands/tenant/shared.js +2 -1
- package/lib/commands/user-account/dingding-sandbox-bind.js +2 -1
- package/lib/commands/user-account/feishu-bind.js +2 -1
- package/lib/commands/user-account/index.js +1 -1
- package/lib/commands/workspace/add.js +1 -1
- package/lib/commands/workspace/index.js +7 -1
- package/lib/commands/workspace/remove.js +1 -1
- package/lib/config/domain-config.js +8 -1
- package/lib/config/project-domain-routing.js +3 -1
- package/lib/config/region-config.js +2 -1
- package/lib/config/schema.js +7 -1
- package/lib/constant/cdn.js +2 -1
- package/lib/constant/cli.js +8 -1
- package/lib/constant/defaults.js +1 -1
- package/lib/constant/domain.js +4 -1
- package/lib/constant/env.js +1 -1
- package/lib/constant/output.js +1 -1
- package/lib/constant/paths.js +1 -1
- package/lib/constant/region.js +1 -1
- package/lib/constant/risk.js +1 -1
- package/lib/constant/routing-profile.js +1 -1
- package/lib/context/app-resolver.js +7 -1
- package/lib/context/auth-resolver.js +1 -1
- package/lib/context/config-loader.js +7 -1
- package/lib/context.js +9 -1
- package/lib/core/alias-resolver.js +5 -1
- package/lib/core/api-client.d.ts +14 -7
- package/lib/core/api-client.js +69 -1
- package/lib/core/bff/config.js +1 -1
- package/lib/core/bff/file-system.js +6 -1
- package/lib/core/bff/hash.js +1 -1
- package/lib/core/bff/hook-directory.js +9 -1
- package/lib/core/bff/lock.js +2 -1
- package/lib/core/bff/types.js +1 -1
- package/lib/core/bff/utils.js +3 -1
- package/lib/core/cross-db-analysis.js +1 -1
- package/lib/core/cross-db-relation.js +1 -1
- package/lib/core/db-resolver.js +2 -1
- package/lib/core/flow-config.js +49 -1
- package/lib/core/instant-api-policy/config.js +7 -1
- package/lib/core/instant-api-policy/endpoints.js +1 -1
- package/lib/core/kb-management-client.d.ts +11 -0
- package/lib/core/kb-management-client.js +4 -1
- package/lib/core/kb-search-client.js +3 -1
- package/lib/core/page/file-system.js +2 -1
- package/lib/core/page/hash.js +1 -1
- package/lib/core/page/lock.js +2 -1
- package/lib/core/page/lr-smart-jsx.js +4 -1
- package/lib/core/page/types.js +1 -1
- package/lib/core/sql-index-auditor.js +14 -1
- package/lib/core/sql-sync/config.js +1 -1
- package/lib/core/sql-sync/file-system.js +3 -1
- package/lib/core/sql-sync/hash.js +1 -1
- package/lib/core/sql-sync/lock.js +2 -1
- package/lib/core/sql-sync/types.js +1 -1
- package/lib/core/sql-sync/utils.js +2 -1
- package/lib/core/sql-validator.js +15 -1
- package/lib/errors.js +3 -1
- package/lib/framework/build-all-flags.js +1 -1
- package/lib/framework/error-output.js +1 -1
- package/lib/framework/explicit-yes.js +1 -1
- package/lib/framework/flags.js +1 -1
- package/lib/framework/help.js +2 -1
- package/lib/framework/index.js +1 -1
- package/lib/framework/output.js +2 -1
- package/lib/framework/response.js +1 -1
- package/lib/framework/runner-alias.js +2 -1
- package/lib/framework/runner.js +9 -1
- package/lib/framework/schema-export.js +1 -1
- package/lib/framework/supported-flags.js +2 -1
- package/lib/framework/types.js +1 -1
- package/lib/generated/build-info.d.ts +4 -4
- package/lib/generated/build-info.js +1 -1
- package/lib/generated/official-routing.js +3 -1
- package/lib/generated/routing-contract.js +1 -1
- package/lib/help.js +1 -1
- package/lib/runtime/confirmation.js +2 -1
- package/lib/runtime/event.js +1 -1
- package/lib/runtime/index.js +4 -1
- package/lib/runtime/queue.js +1 -1
- package/lib/runtime/resolve.js +2 -1
- package/lib/runtime/types.js +1 -1
- package/lib/services/dataset-design/checkpoint.js +2 -1
- package/lib/services/dataset-design/commands.js +14 -1
- package/lib/services/dataset-design/contract.js +8 -1
- package/lib/skills/builtin-skill.js +8 -1
- package/lib/skills/install-updated-skill.d.ts +8 -0
- package/lib/skills/install-updated-skill.js +3 -0
- package/lib/skills/local-skills-installer.d.ts +2 -0
- package/lib/skills/local-skills-installer.js +1 -0
- package/lib/skills/main.js +2 -1
- package/lib/skills/npx-skills-add.d.ts +6 -6
- package/lib/skills/npx-skills-add.js +5 -1
- package/lib/skills/skill-presence.d.ts +1 -30
- package/lib/skills/skill-presence.js +2 -1
- package/lib/telemetry/cli-command-trace.js +2 -1
- package/lib/telemetry/cli-help-trace.js +1 -1
- package/lib/telemetry/ensure-cli-otel-config.js +1 -1
- package/lib/telemetry/register-otel-exit-shutdown.js +1 -1
- package/lib/telemetry/send-cli-trace-log.js +1 -1
- package/lib/types/index.js +1 -1
- package/lib/utils/ai_config.js +3 -1
- package/lib/utils/apply-jq-filter.js +1 -1
- package/lib/utils/cdn-config.js +1 -1
- package/lib/utils/check-sdk-version.js +5 -1
- package/lib/utils/cli-version-check.js +4 -1
- package/lib/utils/cli-version-policy.js +3 -1
- package/lib/utils/config.js +1 -1
- package/lib/utils/entity-with-id.js +1 -1
- package/lib/utils/file-utils.js +1 -1
- package/lib/utils/guides-cdn.js +3 -1
- package/lib/utils/http-client.js +2 -1
- package/lib/utils/is-non-interactive.js +1 -1
- package/lib/utils/logger.js +3 -1
- package/lib/utils/params.js +1 -1
- package/lib/utils/platform.js +1 -1
- package/lib/utils/sleep.js +1 -1
- package/lib/utils/template-replacer.js +5 -1
- package/lib/utils/update-notice.js +3 -1
- package/lib/utils/version.js +1 -1
- package/lib/utils/with-active-cookie.js +1 -1
- package/lib/utils/write-cli-side-channel.js +1 -1
- package/package.json +10 -7
- package/skills/rabetbase/SKILL.md +11 -7
- package/skills/rabetbase/guides/backend-function.md +3 -1
- package/skills/rabetbase/guides/data-api-guidelines.md +1 -1
- package/skills/rabetbase/guides/frontend-development.md +1 -0
- package/skills/rabetbase/guides/metric-development.md +185 -0
- package/skills/rabetbase/references/rabetbase-app-config.md +4 -3
- package/skills/rabetbase/references/rabetbase-cli-skill-install.md +5 -5
- package/skills/rabetbase/references/rabetbase-dataset-design.md +1 -1
- package/skills/rabetbase/references/rabetbase-kb.md +16 -0
- package/skills/rabetbase/references/rabetbase-metric.md +119 -0
- package/skills/rabetbase/references/rabetbase-update.md +7 -5
- package/skills/rabetbase-dataset-generation/SKILL.md +1 -1
- package/skills/rabetbase-dataset-generation/references/workflow.md +1 -1
- package/skills/rabetbase-metrics-generation/SKILL.md +22 -0
- package/skills/rabetbase-metrics-generation/references/verification.md +19 -0
- package/skills/rabetbase-metrics-generation/references/workflow.md +41 -0
- package/skills/rabetbase-metrics-generation/templates/statistics-delivery.md +11 -0
- package/skills/rabetbase-page-generation/SKILL.md +1 -1
- package/skills/rabetbase-page-generation/references/generation.md +1 -1
- package/skills/rabetbase.manifest.json +5 -3
- package/templates/metrics/definition.json +78 -0
- package/templates/metrics/metric-definition.schema.json +136 -0
- package/lib/postinstall.d.ts +0 -3
- package/lib/postinstall.js +0 -1
- package/scripts/postinstall.mjs +0 -24
- package/templates/README.md +0 -130
package/lib/commands/bff/list.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{listBffScripts}from"../../core/api-client.js";export const bffList={service:"bff",command:"list",description:"List Backend Function scripts",risk:"read",flags:[{name:"type",type:"string",description:"Script type filter",default:"ENDPOINT",enum:["ENDPOINT","COMMON"]},{name:"name",type:"string",description:"Filter by script name"},{name:"verbose",type:"boolean",description:"Return full script objects"}],async execute(ctx){const scripts=await listBffScripts(ctx.appCode,ctx.str("type"),{scriptName:ctx.str("name")||undefined});const verbose=ctx.bool("verbose");return{ok:true,data:verbose?scripts:scripts.map(s=>({id:s.id,functionName:s.functionName??"",description:s.description||"(unnamed)",scriptType:s.scriptType})),message:scripts.length===0?"No Backend Function scripts found.":undefined}}};
|
package/lib/commands/bff/logs.js
CHANGED
|
@@ -1 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import{APPCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{searchBffScriptLogs}from"../../core/api-client.js";import{CliErrors}from"../../errors.js";const DEFAULT_SINCE_MINUTES=30;const DEFAULT_LIMIT=200;const MAX_LIMIT=1e3;const LOG_LEVELS=["DEBUG","INFO","WARN","ERROR"];export function resolveBffLogQuery(ctx,now=Date.now()){const rawSince=ctx.flag("since");const rawStartTime=ctx.flag("start-time");const rawEndTime=ctx.flag("end-time");if(rawSince!==undefined&&rawStartTime!==undefined){throw CliErrors.validation("--since cannot be combined with --start-time.")}const endTime=rawEndTime===undefined?now:readPositiveInteger(ctx.num("end-time"),"--end-time");const startTime=rawStartTime===undefined?endTime-readSinceMinutes(ctx)*6e4:readPositiveInteger(ctx.num("start-time"),"--start-time");if(startTime<=0){throw CliErrors.validation("The resolved log start time must be greater than 0.")}if(startTime>endTime){
|
|
2
|
+
throw CliErrors.validation("--start-time must be less than or equal to --end-time.")}const limit=readPositiveInteger(ctx.num("limit",DEFAULT_LIMIT),"--limit");if(limit>MAX_LIMIT){throw CliErrors.validation(`--limit must be between 1 and ${MAX_LIMIT}.`)}const level=ctx.str("level").trim().toUpperCase()||undefined;const keyword=ctx.str("keyword").trim()||undefined;return{appCode:ctx.appCode,startTime:startTime,endTime:endTime,...rawStartTime===undefined?{sinceMinutes:readSinceMinutes(ctx)}:{},...level?{level:level}:{},...keyword?{keyword:keyword}:{},limit:limit}}function readSinceMinutes(ctx){return readPositiveInteger(ctx.num("since",DEFAULT_SINCE_MINUTES),"--since")}function readPositiveInteger(value,flag){if(!Number.isSafeInteger(value)||value<=0){throw CliErrors.validation(`${flag} must be a positive integer.`)}return value}export const bffLogs={service:"bff",command:"logs",description:"Query recent Backend Function runtime logs for development debugging",risk:"read",
|
|
3
|
+
structuredErrors:true,flags:[APPCODE_FLAG_OPTIONAL,{name:"since",type:"number",description:`Minutes before the end time to query (default: ${DEFAULT_SINCE_MINUTES})`},{name:"start-time",type:"number",description:"Query start time as a Unix timestamp in milliseconds"},{name:"end-time",type:"number",description:"Query end time as a Unix timestamp in milliseconds (default: now)"},{name:"level",type:"string",description:"Filter by log level",enum:LOG_LEVELS},{name:"keyword",type:"string",description:"Filter formatted log lines by keyword"},{name:"limit",type:"number",description:`Maximum log lines to return (1-${MAX_LIMIT})`,default:DEFAULT_LIMIT}],async validate(ctx){resolveBffLogQuery(ctx)},async execute(ctx){const query=resolveBffLogQuery(ctx);const{sinceMinutes:_sinceMinutes,...apiQuery}=query;const logs=await searchBffScriptLogs(apiQuery);return{ok:true,data:{query:query,count:logs.length,logs:logs},
|
|
4
|
+
message:logs.length===0?"No Backend Function logs found for the selected range.":`Found ${logs.length} Backend Function log line(s).`}}};
|
package/lib/commands/bff/pull.js
CHANGED
|
@@ -1 +1,22 @@
|
|
|
1
|
-
function a43_0x36f9(_0x15d8df,_0x4a00db){_0x15d8df=_0x15d8df-0x1d4;const _0x176d07=a43_0x176d();let _0x36f9fa=_0x176d07[_0x15d8df];return _0x36f9fa;}const a43_0x24b3b8=a43_0x36f9;(function(_0x376e93,_0x433bcc){const _0x135909=a43_0x36f9,_0x33a4ff=_0x376e93();while(!![]){try{const _0xb9268=-parseInt(_0x135909(0x23d))/0x1+-parseInt(_0x135909(0x258))/0x2*(-parseInt(_0x135909(0x1f3))/0x3)+-parseInt(_0x135909(0x240))/0x4+parseInt(_0x135909(0x1d5))/0x5*(parseInt(_0x135909(0x208))/0x6)+parseInt(_0x135909(0x1e3))/0x7+parseInt(_0x135909(0x1fa))/0x8+-parseInt(_0x135909(0x224))/0x9;if(_0xb9268===_0x433bcc)break;else _0x33a4ff['push'](_0x33a4ff['shift']());}catch(_0x3a47ab){_0x33a4ff['push'](_0x33a4ff['shift']());}}}(a43_0x176d,0x4e6e7));import{createInterface}from'node:readline';import{readFile,rename,stat,unlink,writeFile}from'node:fs/promises';import{randomUUID}from'node:crypto';import{dirname,join}from'node:path';import{BFF_LIST_PAGE_SIZE,listBffScripts,getBffScriptStatistics}from'../../core/api-client.js';import{loadAliasMap}from'../../core/alias-resolver.js';import{resolveApiModelSource}from'../../api/model-source.js';import{loadBffProjectConfig}from'../../core/bff/config.js';import{createHookLocationMap,directoryExists,ensureParentDirectory,fileExists,isSafeLockKeySegment,normalizeBffType,resolveLocalFilePathFromLockKey,resolveRemoteScriptTarget,scanLocalBffFunctions}from'../../core/bff/file-system.js';import{computeContentHash,computeFileHash}from'../../core/bff/hash.js';import{assertUnambiguousHookAliases}from'../../core/bff/hook-directory.js';import{createEmptyBffLock,ensureLockScope,readBffLockFile,writeBffLockFile}from'../../core/bff/lock.js';import{CliErrors}from'../../errors.js';import{CLI_BIN_NAME}from'../../constant/cli.js';export const bffPull={'service':a43_0x24b3b8(0x23e),'command':a43_0x24b3b8(0x229),'description':'Pull\x20remote\x20Backend\x20Function\x20scripts\x20to\x20local','risk':a43_0x24b3b8(0x1ef),'structuredErrors':!![],'flags':[{'name':a43_0x24b3b8(0x236),'type':'string','description':a43_0x24b3b8(0x234),'enum':[a43_0x24b3b8(0x216),'ENDPOINT',a43_0x24b3b8(0x239)]},{'name':'force','type':a43_0x24b3b8(0x215),'description':a43_0x24b3b8(0x1d4)}],async 'dryRun'(_0x476ecc){const _0x2bf616=a43_0x24b3b8,_0x547c52=loadBffProjectConfig(_0x476ecc['appCode']),_0x214999=await readBffLockFile(_0x547c52[_0x2bf616(0x204)]),{appLock:_0x10ed18}=ensureLockScope(_0x214999??createEmptyBffLock(),_0x476ecc[_0x2bf616(0x1f0)],_0x547c52[_0x2bf616(0x25b)],_0x2bf616(0x229)),_0x80f6d=normalizeBffType(_0x476ecc[_0x2bf616(0x1ea)](_0x2bf616(0x236)))??undefined,[_0x294988,_0x5e729b]=await Promise[_0x2bf616(0x250)]([listBffScripts(_0x476ecc[_0x2bf616(0x1f0)],_0x80f6d),getBffScriptStatistics(_0x476ecc[_0x2bf616(0x1f0)])]),_0x3cde14=_0x294988[_0x2bf616(0x1f1)](_0x2cbae1=>normalizeBffType(_0x2cbae1['scriptType'])===_0x2bf616(0x239)),_0x5bcb0b=_0x3cde14?buildDatasetCodeToAliasMap(_0x476ecc['apiDir'],_0x476ecc[_0x2bf616(0x1f0)],_0x476ecc[_0x2bf616(0x1e0)]||_0x476ecc[_0x2bf616(0x23a)]?.[_0x2bf616(0x1e6)]||_0x476ecc[_0x2bf616(0x23a)]?.[_0x2bf616(0x252)]):new Map(),_0x3def1e=_0x3cde14?await planHookDirectoryMigration(_0x547c52,_0x10ed18,_0x5bcb0b,await scanLocalBffFunctions(_0x547c52,_0x2bf616(0x239))):undefined,_0x1121ba=createHookLocationMap(_0x5e729b),_0x525b52=[];for(const _0x485c6b of _0x294988){const _0x29e237=resolveRemoteScriptTarget(_0x547c52,_0x485c6b,_0x1121ba,_0x3def1e?.['projectedFunctions']??_0x10ed18[_0x2bf616(0x249)],_0x5bcb0b);if(!_0x29e237){_0x525b52['push']({'scriptType':_0x485c6b['scriptType'],'functionName':_0x485c6b[_0x2bf616(0x23f)]??'','status':_0x2bf616(0x269),'reason':'unresolvable\x20target\x20path'});continue;}const _0x4f2b77=(_0x3def1e?.[_0x2bf616(0x1da)]??_0x10ed18[_0x2bf616(0x249)])[_0x29e237['lockKey']],_0x46ef96=_0x485c6b[_0x2bf616(0x200)]!=null?computeContentHash(_0x485c6b[_0x2bf616(0x200)]):undefined,_0xc4f110=await hasUnsyncedLocalChanges(resolveMigratedSourceFilePath(_0x3def1e,_0x29e237)??_0x29e237[_0x2bf616(0x218)],_0x4f2b77,_0x46ef96),_0x501465=_0xc4f110?localUnsyncedConflict(_0x29e237,_0x485c6b['id']):undefined;_0x525b52['push']({'lockKey':_0x29e237[_0x2bf616(0x231)],'filePath':_0x29e237['filePath'],'remoteId':_0x485c6b['id']??null,'status':_0x501465?_0x2bf616(0x261):_0x2bf616(0x230),..._0x501465?{'conflict':_0x501465}:{},..._0x29e237['hookLocation']?{'alias':_0x29e237[_0x2bf616(0x1fc)][_0x2bf616(0x1e5)]??null,'datasetCode':_0x29e237[_0x2bf616(0x1fc)][_0x2bf616(0x24e)],'operationType':_0x29e237['hookLocation']['operationType'],'functionNode':_0x29e237['hookLocation'][_0x2bf616(0x246)]}:{}});}return{'method':_0x2bf616(0x226),'url':_0x2bf616(0x22b)+_0x476ecc[_0x2bf616(0x1f0)]+(_0x80f6d?_0x2bf616(0x1f7)+_0x80f6d:'')+_0x2bf616(0x20e)+BFF_LIST_PAGE_SIZE,'body':{'appCode':_0x476ecc[_0x2bf616(0x1f0)],'filterType':_0x80f6d??null,..._0x3def1e&&_0x3def1e[_0x2bf616(0x1dc)][_0x2bf616(0x237)]>0x0?{'hookDirectoryMigrations':_0x3def1e[_0x2bf616(0x1dc)][_0x2bf616(0x265)](_0xd6b18f=>({'from':_0xd6b18f[_0x2bf616(0x244)],'to':_0xd6b18f[_0x2bf616(0x214)]}))}:{},'files':_0x525b52},'description':'Would\x20inspect\x20'+_0x525b52[_0x2bf616(0x237)]+_0x2bf616(0x1fd)};},async 'execute'(_0x50224a){const _0x2febea=a43_0x24b3b8,_0xe3526b=loadBffProjectConfig(_0x50224a[_0x2febea(0x1f0)]),_0x3955a7=await readBffLockFile(_0xe3526b[_0x2febea(0x204)]),{lockData:_0x3bbb56,appLock:_0x41658b}=ensureLockScope(_0x3955a7??createEmptyBffLock(),_0x50224a[_0x2febea(0x1f0)],_0xe3526b[_0x2febea(0x25b)],_0x2febea(0x229)),_0x17153d=normalizeBffType(_0x50224a[_0x2febea(0x1ea)](_0x2febea(0x236)))??undefined;if(_0x50224a[_0x2febea(0x1ea)](_0x2febea(0x236))&&!_0x17153d)throw CliErrors[_0x2febea(0x21e)](_0x2febea(0x221));const [_0x32921c,_0xa27575]=await Promise[_0x2febea(0x250)]([listBffScripts(_0x50224a['appCode'],_0x17153d),getBffScriptStatistics(_0x50224a[_0x2febea(0x1f0)])]);if(_0x32921c[_0x2febea(0x237)]===0x0)return{'ok':!![],'data':{'pulled':[],'skipped':[],'conflicts':[],'failed':[]},'message':_0x2febea(0x219)};const _0x50ae3a=_0x50224a['bool'](_0x2febea(0x212));if(_0x50ae3a&&!_0x50224a[_0x2febea(0x211)]){const _0x1193c8=await confirmForce();if(!_0x1193c8)throw CliErrors[_0x2febea(0x255)](_0x2febea(0x232));}if(_0x50ae3a&&_0x50224a[_0x2febea(0x211)]){}const _0x2cde6a=_0x32921c['some'](_0x1979ff=>normalizeBffType(_0x1979ff[_0x2febea(0x238)])===_0x2febea(0x239)),_0x12b1cd=_0x2cde6a?buildDatasetCodeToAliasMap(_0x50224a[_0x2febea(0x245)],_0x50224a[_0x2febea(0x1f0)],_0x50224a[_0x2febea(0x1e0)]||_0x50224a['mergedCli']?.[_0x2febea(0x1e6)]||_0x50224a[_0x2febea(0x23a)]?.[_0x2febea(0x252)]):new Map(),_0x78d90e=createHookLocationMap(_0xa27575),_0x361c4a=JSON[_0x2febea(0x209)](JSON['stringify'](_0x3bbb56)),_0x553352=_0x50224a['appCode'],_0x5dcd5a=_0x361c4a[_0x2febea(0x222)][_0x553352];if(!_0x5dcd5a)throw new Error('Lock\x20scope\x20for\x20app\x20\x22'+_0x553352+_0x2febea(0x1eb));const _0x154a6d=_0x2cde6a?await applyHookDirectoryMigration(await planHookDirectoryMigration(_0xe3526b,_0x5dcd5a,_0x12b1cd,await scanLocalBffFunctions(_0xe3526b,_0x2febea(0x239))),_0x5dcd5a):undefined,_0x225089=createPullFileTransaction(),_0x2cd7e9=[],_0x27ff13=[],_0x10c59d=[],_0x6ede95=[];for(const _0x371366 of _0x32921c){const _0x48488d=resolveRemoteScriptTarget(_0xe3526b,_0x371366,_0x78d90e,_0x5dcd5a['functions'],_0x12b1cd);if(!_0x48488d){_0x27ff13[_0x2febea(0x260)]({'lockKey':_0x371366[_0x2febea(0x238)]+'/'+_0x371366[_0x2febea(0x23f)],'reason':'unresolvable\x20target\x20path'});continue;}const _0x9be609=_0x5dcd5a[_0x2febea(0x249)][_0x48488d['lockKey']];try{if(!_0x371366['id'])throw new Error(_0x2febea(0x1ed));if(_0x371366[_0x2febea(0x200)]==null)throw new Error(_0x2febea(0x1e9));const _0x56b666=_0x371366['scriptContent'],_0xccf711=computeContentHash(_0x56b666);if(!_0x50ae3a){const _0x5b182d=await hasUnsyncedLocalChanges(_0x48488d[_0x2febea(0x218)],_0x9be609,_0xccf711);if(_0x5b182d){_0x10c59d[_0x2febea(0x260)](localUnsyncedConflict(_0x48488d,_0x371366['id']));continue;}}await _0x225089[_0x2febea(0x21b)](_0x48488d[_0x2febea(0x218)],_0x56b666);const _0x31b684={'hash':_0xccf711,'remoteId':_0x371366['id'],'version':_0x371366['version']};_0x48488d['type']==='HOOK'&&_0x48488d[_0x2febea(0x1fc)]&&(_0x31b684['alias']=_0x48488d[_0x2febea(0x1fc)][_0x2febea(0x1e5)],_0x31b684[_0x2febea(0x24e)]=_0x48488d[_0x2febea(0x1fc)][_0x2febea(0x24e)],_0x31b684['operationType']=_0x48488d[_0x2febea(0x1fc)][_0x2febea(0x25c)],_0x31b684['functionNode']=_0x48488d[_0x2febea(0x1fc)][_0x2febea(0x246)]),_0x5dcd5a['functions'][_0x48488d[_0x2febea(0x231)]]=_0x31b684,_0x2cd7e9[_0x2febea(0x260)]({'lockKey':_0x48488d[_0x2febea(0x231)],'remoteId':_0x371366['id']});}catch(_0x2c5355){_0x6ede95[_0x2febea(0x260)]({'lockKey':_0x48488d[_0x2febea(0x231)],'error':_0x2c5355 instanceof Error?_0x2c5355[_0x2febea(0x223)]:String(_0x2c5355)});}}_0x5dcd5a[_0x2febea(0x1e1)]=new Date()[_0x2febea(0x1e2)]();try{await writeBffLockFile(_0xe3526b['lockFilePath'],_0x361c4a);}catch(_0x1b693f){const _0x88566b=[...await _0x225089[_0x2febea(0x251)](),...await _0x154a6d?.[_0x2febea(0x251)]()??[]];throw withRollbackErrors(_0x1b693f,_0x2febea(0x1d8),_0x88566b);}return{'ok':_0x6ede95[_0x2febea(0x237)]===0x0,'data':{'pulled':_0x2cd7e9,'skipped':_0x27ff13,'conflicts':_0x10c59d,'failed':_0x6ede95},'message':formatPullMessage(_0x2cd7e9[_0x2febea(0x237)],_0x27ff13[_0x2febea(0x237)],_0x10c59d[_0x2febea(0x237)],_0x6ede95['length'])};}};function localUnsyncedConflict(_0x52e353,_0x1cf6dc){const _0x4f01e5=a43_0x24b3b8,_0x472ba8=_0x52e353[_0x4f01e5(0x231)]['split']('/')['at'](-0x1);return{'code':_0x4f01e5(0x213),'lockKey':_0x52e353[_0x4f01e5(0x231)],'filePath':_0x52e353['filePath'],..._0x1cf6dc!=null?{'remoteId':_0x1cf6dc}:{},'message':'Local\x20script\x20differs\x20from\x20the\x20last\x20pulled\x20version.\x20Review\x20it\x20before\x20choosing\x20the\x20source\x20of\x20truth.','nextAction':{'action':_0x4f01e5(0x207),'command':CLI_BIN_NAME+_0x4f01e5(0x235)+_0x52e353['type']+_0x4f01e5(0x228)+_0x472ba8+_0x4f01e5(0x1f2),'requiresReview':!![],'message':'If\x20the\x20reviewed\x20local\x20script\x20should\x20win,\x20run\x20this\x20command\x20to\x20update\x20the\x20remote\x20script.\x20Do\x20not\x20use\x20--force\x20to\x20resolve\x20a\x20content\x20conflict.'}};}function a43_0x176d(){const _0x9a142f=['requires','lockFilePath','has','Failed\x20to\x20rename\x20HOOK\x20directory\x20\x22','push_local','36BYNWmh','parse','utf8','\x22:\x20the\x20target\x20directory\x20already\x20exists.\x20Resolve\x20the\x20directories\x20and\x20retry.','keyChanges','join','¤tPage=1&pageSize=','NFC','flatMap','nonInteractive','force','BFF_LOCAL_UNSYNCED','newDirectory','boolean','COMMON','scriptsRootDir','filePath','No\x20remote\x20Backend\x20Function\x20scripts\x20found.','Cannot\x20migrate\x20HOOK\x20lock\x20keys\x20\x22','write','\x22:\x20its\x20target\x20directory\x20is\x20unsafe.','move','validation','\x20skipped','\x22\x20and\x20\x22','--type\x20must\x20be\x20COMMON,\x20ENDPOINT,\x20or\x20HOOK.','apps','message','2658078rqnHqw','\x22:\x20it\x20is\x20now\x20another\x20Dataset\x20alias\x20and\x20contains\x20untracked\x20scripts.\x20Resolve\x20the\x20directory\x20manually\x20before\x20retrying.','GET','split','\x20--name\x20','pull','get','/api/management/library/scripts/list?appCode=','sourceDirectoryPathByNewDirectory','Could\x20not\x20restore\x20temporary\x20HOOK\x20directory\x20\x22','\x22\x20to\x20\x22','newDirectoryPath','would_pull','lockKey','Force\x20pull\x20cancelled.','dev','Pull\x20only\x20this\x20script\x20type','\x20bff\x20push\x20--type\x20','type','length','scriptType','HOOK','mergedCli','entry','require','508076bzDrFj','bff','functionName','478000ctOHRE','\x20resolution','\x22:\x20its\x20target\x20\x22','Could\x20not\x20restore\x20HOOK\x20directory\x20\x22','oldDirectory','apiDir','functionNode','Could\x20not\x20restore\x20local\x20script\x20\x22','stderr','functions','profileName','\x22:\x20','trim','\x22.\x20Resolve\x20the\x20lock\x20entries\x20manually\x20before\x20retrying.','datasetCode','\x22:\x20both\x20target\x20\x22','all','rollback','defaultApp','content','case-rename','cancelled','Cannot\x20migrate\x20HOOK\x20lock\x20key\x20\x22','.hook-directory-migrate-','146qqkIhd','Cannot\x20migrate\x20HOOK\x20directories\x20\x22','oldDirectoryPath','scriptsRoot','operationType','\x22\x20from\x20the\x20lock\x20file.','stdin','mode','push','conflict','newLockKey','set','\x22\x20is\x20another\x20legacy\x20key\x20being\x20migrated.\x20Resolve\x20the\x20lock\x20entries\x20manually\x20before\x20retrying.','map','\x22:\x20the\x20destination\x20is\x20another\x20Dataset\x20alias.\x20Resolve\x20the\x20directory\x20manually\x20before\x20retrying.','Cannot\x20migrate\x20HOOK\x20directory\x20\x22','HOOK/','skipped','toLowerCase','Force\x20overwrite\x20local\x20unsynced\x20changes','520055geOXPh','normalize','hash','Failed\x20to\x20write\x20the\x20Backend\x20Function\x20lock\x20file;\x20local\x20changes\x20could\x20not\x20be\x20completely\x20rolled\x20back.','entries','projectedFunctions','\x22\x20may\x20remain.','migrations','Cannot\x20migrate\x20unsafe\x20HOOK\x20lock\x20key\x20\x22','ino','\x22:\x20target\x20lock\x20key\x20is\x20already\x20bound\x20to\x20another\x20script.','selectedAppName','lastSync','toISOString','228508rerdJi','close','alias','currentApp','\x20failed','yes','Remote\x20script\x20missing\x20content.','str','\x22\x20not\x20found\x20after\x20ensureLockScope.','.js','Remote\x20script\x20missing\x20id.','code','read','appCode','some','\x20--format\x20compress','5331XEtWni','rekey','filter','\x22.\x20Resolve\x20the\x20directories\x20manually\x20before\x20retrying.','&type=','\x22;\x20temporary\x20directory\x20\x22','oldLockKey','3661936RlSXpb','ENOENT','hookLocation','\x20remote\x20Backend\x20Function\x20script(s)\x20for\x20pull','Pull\x20complete:\x20','sourceFilePathByNewLockKey','scriptContent','\x20pulled','remoteId'];a43_0x176d=function(){return _0x9a142f;};return a43_0x176d();}function formatPullMessage(_0x1fb84d,_0x3f787b,_0x1ef4f4,_0x39921b){const _0x26e044=a43_0x24b3b8,_0x490f8a=[_0x26e044(0x1fe)+_0x1fb84d+_0x26e044(0x201),_0x3f787b+_0x26e044(0x21f)];_0x1ef4f4>0x0&&_0x490f8a[_0x26e044(0x260)](_0x1ef4f4+'\x20conflict'+(_0x1ef4f4===0x1?'':'s')+'\x20'+(_0x1ef4f4===0x1?_0x26e044(0x203):_0x26e044(0x23c))+_0x26e044(0x241));if(_0x39921b>0x0)_0x490f8a[_0x26e044(0x260)](_0x39921b+_0x26e044(0x1e7));return _0x490f8a[_0x26e044(0x20d)](',\x20');}async function hasUnsyncedLocalChanges(_0x569fb4,_0x57ba61,_0x15187){const _0x15fb39=a43_0x24b3b8;if(!await fileExists(_0x569fb4))return![];const _0x2fdfc9=await computeFileHash(_0x569fb4);if(!_0x57ba61)return _0x15187?_0x2fdfc9!==_0x15187:!![];return _0x2fdfc9!==_0x57ba61[_0x15fb39(0x1d7)];}function createPullFileTransaction(){const _0x56116e=new Map(),_0x3eac13=async(_0x220b8f,_0x4dacb0)=>{const _0x5263d7=a43_0x36f9;try{if(_0x4dacb0['existed'])await ensureParentDirectory(_0x220b8f),await writeFile(_0x220b8f,_0x4dacb0[_0x5263d7(0x253)]);else try{await unlink(_0x220b8f);}catch(_0x14c130){if(_0x14c130[_0x5263d7(0x1ee)]!==_0x5263d7(0x1fb))throw _0x14c130;}return undefined;}catch(_0x131c82){return _0x131c82 instanceof Error?_0x131c82:new Error(String(_0x131c82));}};return{async 'write'(_0xa0a444,_0x1603b9){const _0x279c9a=a43_0x36f9;if(!_0x56116e[_0x279c9a(0x205)](_0xa0a444))try{_0x56116e[_0x279c9a(0x263)](_0xa0a444,{'existed':!![],'content':await readFile(_0xa0a444)});}catch(_0x2cb44b){if(_0x2cb44b[_0x279c9a(0x1ee)]!=='ENOENT')throw _0x2cb44b;_0x56116e[_0x279c9a(0x263)](_0xa0a444,{'existed':![]});}try{await ensureParentDirectory(_0xa0a444),await writeFile(_0xa0a444,_0x1603b9,_0x279c9a(0x20a));}catch(_0x102d78){const _0x3088dc=await _0x3eac13(_0xa0a444,_0x56116e[_0x279c9a(0x22a)](_0xa0a444));if(!_0x3088dc)_0x56116e['delete'](_0xa0a444);throw withRollbackErrors(_0x102d78,'Failed\x20to\x20write\x20local\x20script\x20\x22'+_0xa0a444+'\x22.',_0x3088dc?[_0x3088dc]:[]);}},async 'rollback'(){const _0x8a2ec9=a43_0x36f9,_0x3a8a4b=[];for(const [_0x3dc8b6,_0x2a18a1]of[..._0x56116e[_0x8a2ec9(0x1d9)]()]['reverse']()){const _0x4e5226=await _0x3eac13(_0x3dc8b6,_0x2a18a1);_0x4e5226&&_0x3a8a4b[_0x8a2ec9(0x260)](new Error(_0x8a2ec9(0x247)+_0x3dc8b6+_0x8a2ec9(0x24b)+_0x4e5226['message']));}return _0x3a8a4b;}};}function withRollbackErrors(_0x287409,_0xdeaf78,_0x42f3c9){const _0x21f56b=a43_0x24b3b8,_0x408310=_0x287409 instanceof Error?_0x287409:new Error(String(_0x287409));if(_0x42f3c9[_0x21f56b(0x237)]===0x0)return _0x408310;return new AggregateError([_0x408310,..._0x42f3c9],_0xdeaf78+'\x20Recovery\x20errors:\x20'+_0x42f3c9[_0x21f56b(0x265)](_0xb74659=>_0xb74659[_0x21f56b(0x223)])['join'](';\x20'));}function buildDatasetCodeToAliasMap(_0x356e2e,_0xa9fc3a,_0x2d5988){const _0x1a770c=a43_0x24b3b8,_0x3c8a34=resolveApiModelSource(_0x356e2e,_0xa9fc3a,_0x2d5988),_0x3d81c3=loadAliasMap(_0x356e2e,undefined,_0x3c8a34[_0x1a770c(0x218)],_0x3c8a34[_0x1a770c(0x24a)]);return assertUnambiguousHookAliases(_0x3d81c3),new Map(_0x3d81c3['map'](_0x612960=>[_0x612960['datasetCode'][_0x1a770c(0x26a)](),_0x612960[_0x1a770c(0x1e5)]]));}async function planHookDirectoryMigration(_0x11aae3,_0x57ffd5,_0x3bc841,_0x4416cf){const _0x5f143b=a43_0x24b3b8,_0x2d3c6a=new Map();for(const [_0x5e59a3,_0x52319a]of Object[_0x5f143b(0x1d9)](_0x57ffd5[_0x5f143b(0x249)])){const [_0x3419dd,_0x380667,_0xaeafc4,_0x56cdf9,_0x586987,..._0x239cc7]=_0x5e59a3['split']('/');if(_0x3419dd!=='HOOK'||!_0x380667||!_0xaeafc4||!_0x56cdf9||!_0x586987||_0x239cc7[_0x5f143b(0x237)]>0x0||!_0x52319a['datasetCode'])continue;const _0x3df9c9=_0x3bc841[_0x5f143b(0x22a)](_0x52319a[_0x5f143b(0x24e)]['toLowerCase']()),_0x373e82=_0x3df9c9??_0x52319a['datasetCode'];if(!isSafeHookDirectorySegment(_0x380667))throw CliErrors[_0x5f143b(0x21e)]('Cannot\x20migrate\x20unsafe\x20HOOK\x20directory\x20\x22'+_0x380667+_0x5f143b(0x25d));if(!isSafeHookDirectorySegment(_0x373e82))throw CliErrors['validation'](_0x5f143b(0x267)+_0x380667+_0x5f143b(0x21c));if(_0x380667===_0x373e82)continue;const _0x2bf0db=_0x2d3c6a['get'](_0x380667)??{'datasetCode':_0x52319a[_0x5f143b(0x24e)],'alias':_0x3df9c9,'keyChanges':[]};if(_0x2bf0db[_0x5f143b(0x24e)]!==_0x52319a['datasetCode'])throw CliErrors[_0x5f143b(0x21e)](_0x5f143b(0x267)+_0x380667+'\x22:\x20it\x20is\x20tracked\x20by\x20multiple\x20Datasets.');const _0x287c3d=_0x5f143b(0x268)+_0x373e82+'/'+_0xaeafc4+'/'+_0x56cdf9+'/'+_0x586987;try{resolveLocalFilePathFromLockKey(_0x11aae3,_0x5e59a3),resolveLocalFilePathFromLockKey(_0x11aae3,_0x287c3d);}catch(_0x51822b){throw CliErrors[_0x5f143b(0x21e)](_0x5f143b(0x1dd)+_0x5e59a3+_0x5f143b(0x24b)+(_0x51822b instanceof Error?_0x51822b[_0x5f143b(0x223)]:String(_0x51822b)));}_0x2bf0db[_0x5f143b(0x20c)]['push']({'oldLockKey':_0x5e59a3,'newLockKey':_0x287c3d,'entry':_0x52319a}),_0x2d3c6a[_0x5f143b(0x263)](_0x380667,_0x2bf0db);}const _0x348c33=new Set([..._0x2d3c6a['values']()][_0x5f143b(0x210)](_0x1c169e=>_0x1c169e['keyChanges']['map'](_0x4b6479=>_0x4b6479[_0x5f143b(0x1f9)]))),_0x2634d7=new Map(),_0x107e04=new Map();for(const [_0x103561,_0x21283e]of _0x2d3c6a){const _0x3c6a1c=_0x21283e['alias']??_0x21283e['datasetCode'],_0x3370af=hookDirectoryIdentity(_0x3c6a1c),_0x2e04d1=_0x2634d7[_0x5f143b(0x22a)](_0x3370af);if(_0x2e04d1&&_0x2e04d1!==_0x103561)throw CliErrors[_0x5f143b(0x21e)](_0x5f143b(0x259)+_0x2e04d1+_0x5f143b(0x220)+_0x103561+_0x5f143b(0x24f)+_0x3c6a1c+_0x5f143b(0x1f6));_0x2634d7[_0x5f143b(0x263)](_0x3370af,_0x103561);for(const _0x4a94b0 of _0x21283e['keyChanges']){const _0x2db68d=_0x107e04[_0x5f143b(0x22a)](_0x4a94b0[_0x5f143b(0x262)]);if(_0x2db68d&&_0x2db68d!==_0x4a94b0[_0x5f143b(0x1f9)])throw CliErrors['validation'](_0x5f143b(0x21a)+_0x2db68d+'\x22\x20and\x20\x22'+_0x4a94b0[_0x5f143b(0x1f9)]+'\x22:\x20both\x20target\x20\x22'+_0x4a94b0[_0x5f143b(0x262)]+_0x5f143b(0x24d));if(_0x348c33[_0x5f143b(0x205)](_0x4a94b0[_0x5f143b(0x262)]))throw CliErrors[_0x5f143b(0x21e)](_0x5f143b(0x256)+_0x4a94b0['oldLockKey']+_0x5f143b(0x242)+_0x4a94b0[_0x5f143b(0x262)]+_0x5f143b(0x264));_0x107e04[_0x5f143b(0x263)](_0x4a94b0[_0x5f143b(0x262)],_0x4a94b0[_0x5f143b(0x1f9)]);}}const _0x4dc3a7=new Map();for(const [_0xa2ce51,_0x212b97]of _0x3bc841){_0x4dc3a7['set'](hookDirectoryIdentity(_0x212b97),_0xa2ce51);}const _0x5c032d=[];for(const [_0x42cb98,_0x58de95]of _0x2d3c6a){const _0x339479=_0x58de95[_0x5f143b(0x1e5)]??_0x58de95[_0x5f143b(0x24e)],_0x40c073=join(_0x11aae3[_0x5f143b(0x217)],_0x5f143b(0x239),_0x42cb98),_0x33e45b=join(_0x11aae3[_0x5f143b(0x217)],_0x5f143b(0x239),_0x339479),_0x1419e1=await directoryExists(_0x40c073),_0x20208a=await directoryExists(_0x33e45b),_0x5678c5=_0x1419e1?_0x20208a?await sameDirectory(_0x40c073,_0x33e45b)?_0x5f143b(0x254):undefined:_0x5f143b(0x21d):_0x5f143b(0x1f4);if(!_0x5678c5)throw CliErrors[_0x5f143b(0x21e)](_0x5f143b(0x267)+_0x42cb98+_0x5f143b(0x22e)+_0x339479+_0x5f143b(0x20b));const _0x46ec83=_0x4dc3a7[_0x5f143b(0x22a)](hookDirectoryIdentity(_0x42cb98));if(_0x46ec83&&_0x46ec83!==_0x58de95['datasetCode'][_0x5f143b(0x26a)]()){const _0x3e8243=new Set(_0x58de95[_0x5f143b(0x20c)][_0x5f143b(0x265)](_0x2fbd01=>_0x2fbd01[_0x5f143b(0x1f9)])),_0x3ba6be=_0x4416cf[_0x5f143b(0x1f5)](_0x41ca19=>_0x41ca19[_0x5f143b(0x236)]==='HOOK'&&_0x41ca19[_0x5f143b(0x1e5)]!=null&&hookDirectoryIdentity(_0x41ca19['alias'])===hookDirectoryIdentity(_0x42cb98)&&!_0x3e8243['has'](_0x41ca19[_0x5f143b(0x231)]));if(_0x3ba6be[_0x5f143b(0x237)]>0x0)throw CliErrors['validation'](_0x5f143b(0x267)+_0x42cb98+_0x5f143b(0x225));}const _0x1e8c5f=_0x4dc3a7[_0x5f143b(0x22a)](hookDirectoryIdentity(_0x339479));if(_0x1e8c5f&&_0x1e8c5f!==_0x58de95[_0x5f143b(0x24e)]['toLowerCase']())throw CliErrors['validation'](_0x5f143b(0x267)+_0x42cb98+_0x5f143b(0x22e)+_0x339479+_0x5f143b(0x266));for(const _0x28a5b5 of _0x58de95[_0x5f143b(0x20c)]){const _0x18260d=_0x57ffd5[_0x5f143b(0x249)][_0x28a5b5[_0x5f143b(0x262)]];if(_0x18260d&&!_0x348c33[_0x5f143b(0x205)](_0x28a5b5[_0x5f143b(0x262)])&&!sameHookIdentity(_0x28a5b5[_0x5f143b(0x23b)],_0x18260d))throw CliErrors[_0x5f143b(0x21e)](_0x5f143b(0x267)+_0x42cb98+'\x22\x20to\x20\x22'+_0x339479+_0x5f143b(0x1df));}_0x5c032d[_0x5f143b(0x260)]({'oldDirectory':_0x42cb98,'newDirectory':_0x339479,'oldDirectoryPath':_0x40c073,'newDirectoryPath':_0x33e45b,'mode':_0x5678c5,'alias':_0x58de95[_0x5f143b(0x1e5)],'keyChanges':_0x58de95['keyChanges']});}const _0x30e17f={..._0x57ffd5[_0x5f143b(0x249)]},_0x36614a=new Map(),_0xd41ddd=new Map();for(const _0xa8e7ee of _0x5c032d){const _0x452d83=_0xa8e7ee[_0x5f143b(0x25f)]!==_0x5f143b(0x1f4);_0x452d83&&_0xd41ddd[_0x5f143b(0x263)](hookDirectoryIdentity(_0xa8e7ee[_0x5f143b(0x214)]),_0xa8e7ee['oldDirectoryPath']);for(const _0x588deb of _0xa8e7ee[_0x5f143b(0x20c)]){const _0x15c75c=_0x30e17f[_0x588deb['newLockKey']],_0xe1b099=_0x452d83?_0x588deb[_0x5f143b(0x23b)]:_0x15c75c??_0x588deb[_0x5f143b(0x23b)];_0x30e17f[_0x588deb[_0x5f143b(0x262)]]=canonicalizeHookEntry(_0xe1b099,_0xa8e7ee[_0x5f143b(0x1e5)]),delete _0x30e17f[_0x588deb['oldLockKey']],_0x452d83&&_0x36614a['set'](_0x588deb['newLockKey'],resolveLocalFilePathFromLockKey(_0x11aae3,_0x588deb['oldLockKey']));}}return{'migrations':_0x5c032d,'projectedFunctions':_0x30e17f,'sourceFilePathByNewLockKey':_0x36614a,'sourceDirectoryPathByNewDirectory':_0xd41ddd};}function resolveMigratedSourceFilePath(_0x3ec12f,_0x3c0203){const _0x1933e8=a43_0x24b3b8;if(!_0x3ec12f||!_0x3c0203)return undefined;const _0x3d6d21=_0x3ec12f[_0x1933e8(0x1ff)]['get'](_0x3c0203[_0x1933e8(0x231)]);if(_0x3d6d21)return _0x3d6d21;if(_0x3c0203[_0x1933e8(0x236)]!==_0x1933e8(0x239))return undefined;const [,_0x3f3f55,..._0x320569]=_0x3c0203[_0x1933e8(0x231)][_0x1933e8(0x227)]('/');if(!_0x3f3f55||_0x320569[_0x1933e8(0x237)]===0x0)return undefined;const _0x4295eb=_0x3ec12f[_0x1933e8(0x22c)][_0x1933e8(0x22a)](hookDirectoryIdentity(_0x3f3f55));return _0x4295eb?join(_0x4295eb,..._0x320569)+_0x1933e8(0x1ec):undefined;}function sameHookIdentity(_0x50bdef,_0x1b9088){const _0x43b955=a43_0x24b3b8;return _0x50bdef[_0x43b955(0x202)]===_0x1b9088[_0x43b955(0x202)]&&_0x50bdef[_0x43b955(0x24e)]===_0x1b9088[_0x43b955(0x24e)]&&_0x50bdef[_0x43b955(0x25c)]===_0x1b9088[_0x43b955(0x25c)]&&_0x50bdef[_0x43b955(0x246)]===_0x1b9088[_0x43b955(0x246)];}function canonicalizeHookEntry(_0x30c5cf,_0x231a4b){const {alias:_0x403318,..._0xcdb6e8}=_0x30c5cf;return _0x231a4b?{..._0xcdb6e8,'alias':_0x231a4b}:_0xcdb6e8;}function hookDirectoryIdentity(_0x533c00){const _0xacc40d=a43_0x24b3b8;return _0x533c00[_0xacc40d(0x1d6)](_0xacc40d(0x20f))[_0xacc40d(0x26a)]();}function isSafeHookDirectorySegment(_0x3ad914){return isSafeLockKeySegment(_0x3ad914);}async function sameDirectory(_0x4daad8,_0x321dbb){const _0x1ec111=a43_0x24b3b8,[_0x30bdf8,_0x2cc475]=await Promise['all']([stat(_0x4daad8),stat(_0x321dbb)]);return _0x30bdf8[_0x1ec111(0x233)]===_0x2cc475[_0x1ec111(0x233)]&&_0x30bdf8[_0x1ec111(0x1de)]===_0x2cc475['ino'];}async function applyHookDirectoryMigration(_0x7ad9c9,_0x3ce259){const _0x978626=a43_0x24b3b8,_0x34c8ce=_0x3ce259[_0x978626(0x249)],_0x44da71=_0x3ce259[_0x978626(0x1e1)],_0xf71e57=[],_0x54b986=async()=>{const _0x2f32f2=_0x978626,_0x30ccb0=[];_0x3ce259[_0x2f32f2(0x249)]=_0x34c8ce,_0x3ce259[_0x2f32f2(0x1e1)]=_0x44da71;for(const {migration:_0x2110ca,temporaryPath:_0x523a75}of[..._0xf71e57]['reverse']()){try{_0x523a75?(await rename(_0x2110ca[_0x2f32f2(0x22f)],_0x523a75),await rename(_0x523a75,_0x2110ca[_0x2f32f2(0x25a)])):await rename(_0x2110ca['newDirectoryPath'],_0x2110ca['oldDirectoryPath']);}catch(_0x51ba96){_0x30ccb0[_0x2f32f2(0x260)](new Error(_0x2f32f2(0x243)+_0x2110ca['oldDirectory']+'\x22\x20from\x20\x22'+_0x2110ca[_0x2f32f2(0x214)]+'\x22:\x20'+(_0x51ba96 instanceof Error?_0x51ba96[_0x2f32f2(0x223)]:String(_0x51ba96))));}}return _0x30ccb0;};try{for(const _0x579109 of _0x7ad9c9[_0x978626(0x1dc)]){if(_0x579109[_0x978626(0x25f)]===_0x978626(0x21d))await ensureParentDirectory(_0x579109[_0x978626(0x22f)]),await rename(_0x579109[_0x978626(0x25a)],_0x579109[_0x978626(0x22f)]),_0xf71e57['push']({'migration':_0x579109});else{if(_0x579109[_0x978626(0x25f)]===_0x978626(0x254)){const _0x5bf54c=join(dirname(_0x579109[_0x978626(0x25a)]),_0x978626(0x257)+randomUUID());await rename(_0x579109[_0x978626(0x25a)],_0x5bf54c);try{await rename(_0x5bf54c,_0x579109[_0x978626(0x22f)]);}catch(_0x57c7e0){try{await rename(_0x5bf54c,_0x579109[_0x978626(0x25a)]);}catch(_0x2d6fb1){throw withRollbackErrors(_0x57c7e0,_0x978626(0x206)+_0x579109['oldDirectory']+_0x978626(0x22e)+_0x579109[_0x978626(0x214)]+_0x978626(0x1f8)+_0x5bf54c+_0x978626(0x1db),[new Error(_0x978626(0x22d)+_0x5bf54c+'\x22\x20to\x20\x22'+_0x579109[_0x978626(0x244)]+_0x978626(0x24b)+(_0x2d6fb1 instanceof Error?_0x2d6fb1[_0x978626(0x223)]:String(_0x2d6fb1)))]);}throw _0x57c7e0;}_0xf71e57[_0x978626(0x260)]({'migration':_0x579109,'temporaryPath':_0x5bf54c});}}}return _0x3ce259[_0x978626(0x249)]=_0x7ad9c9[_0x978626(0x1da)],{'rollback':_0x54b986};}catch(_0x21a53b){const _0x5a2892=await _0x54b986();throw withRollbackErrors(_0x21a53b,'Failed\x20to\x20migrate\x20HOOK\x20directories;\x20local\x20changes\x20could\x20not\x20be\x20completely\x20rolled\x20back.',_0x5a2892);}}async function confirmForce(){const _0x1ef4cf=a43_0x24b3b8,_0x4cec76=createInterface({'input':process[_0x1ef4cf(0x25e)],'output':process[_0x1ef4cf(0x248)]}),_0x21e828=await new Promise(_0x4cc472=>{_0x4cec76['question']('Force\x20pull\x20will\x20overwrite\x20local\x20unsynced\x20changes.\x20Continue?\x20[y/N]\x20',_0x4cc472);});return _0x4cec76[_0x1ef4cf(0x1e4)](),['y',_0x1ef4cf(0x1e8)]['includes'](_0x21e828[_0x1ef4cf(0x24c)]()[_0x1ef4cf(0x26a)]());}
|
|
1
|
+
import{createInterface}from"node:readline";import{readFile,rename,stat,unlink,writeFile}from"node:fs/promises";import{randomUUID}from"node:crypto";import{dirname,join}from"node:path";import{BFF_LIST_PAGE_SIZE,listBffScripts,getBffScriptStatistics}from"../../core/api-client.js";import{loadAliasMap}from"../../core/alias-resolver.js";import{resolveApiModelSource}from"../../api/model-source.js";import{loadBffProjectConfig}from"../../core/bff/config.js";import{createHookLocationMap,directoryExists,ensureParentDirectory,fileExists,isSafeLockKeySegment,normalizeBffType,resolveLocalFilePathFromLockKey,resolveRemoteScriptTarget,scanLocalBffFunctions}from"../../core/bff/file-system.js";import{computeContentHash,computeFileHash}from"../../core/bff/hash.js";import{assertUnambiguousHookAliases}from"../../core/bff/hook-directory.js";import{createEmptyBffLock,ensureLockScope,readBffLockFile,writeBffLockFile}from"../../core/bff/lock.js";import{CliErrors}from"../../errors.js"
|
|
2
|
+
;import{CLI_BIN_NAME}from"../../constant/cli.js";export const bffPull={service:"bff",command:"pull",description:"Pull remote Backend Function scripts to local",risk:"read",structuredErrors:true,flags:[{name:"type",type:"string",description:"Pull only this script type",enum:["COMMON","ENDPOINT","HOOK"]},{name:"force",type:"boolean",description:"Force overwrite local unsynced changes"}],async dryRun(ctx){const config=loadBffProjectConfig(ctx.appCode);const rawLock=await readBffLockFile(config.lockFilePath);const{appLock:appLock}=ensureLockScope(rawLock??createEmptyBffLock(),ctx.appCode,config.scriptsRoot,"pull");const filterType=normalizeBffType(ctx.str("type"))??undefined;const[scripts,statistics]=await Promise.all([listBffScripts(ctx.appCode,filterType),getBffScriptStatistics(ctx.appCode)]);const hasHookScripts=scripts.some(script=>normalizeBffType(script.scriptType)==="HOOK")
|
|
3
|
+
;const datasetCodeToAlias=hasHookScripts?buildDatasetCodeToAliasMap(ctx.apiDir,ctx.appCode,ctx.selectedAppName||ctx.mergedCli?.currentApp||ctx.mergedCli?.defaultApp):new Map;const hookMigrationPlan=hasHookScripts?await planHookDirectoryMigration(config,appLock,datasetCodeToAlias,await scanLocalBffFunctions(config,"HOOK")):undefined;const hookLocationMap=createHookLocationMap(statistics);const preview=[];for(const script of scripts){const target=resolveRemoteScriptTarget(config,script,hookLocationMap,hookMigrationPlan?.projectedFunctions??appLock.functions,datasetCodeToAlias);if(!target){preview.push({scriptType:script.scriptType,functionName:script.functionName??"",status:"skipped",reason:"unresolvable target path"});continue}const lockEntry=(hookMigrationPlan?.projectedFunctions??appLock.functions)[target.lockKey];const remoteHash=script.scriptContent!=null?computeContentHash(script.scriptContent):undefined
|
|
4
|
+
;const hasConflict=await hasUnsyncedLocalChanges(resolveMigratedSourceFilePath(hookMigrationPlan,target)??target.filePath,lockEntry,remoteHash);const conflict=hasConflict?localUnsyncedConflict(target,script.id):undefined;preview.push({lockKey:target.lockKey,filePath:target.filePath,remoteId:script.id??null,status:conflict?"conflict":"would_pull",...conflict?{conflict:conflict}:{},...target.hookLocation?{alias:target.hookLocation.alias??null,datasetCode:target.hookLocation.datasetCode,operationType:target.hookLocation.operationType,functionNode:target.hookLocation.functionNode}:{}})}return{method:"GET",url:`/api/management/library/scripts/list?appCode=${ctx.appCode}${filterType?`&type=${filterType}`:""}¤tPage=1&pageSize=${BFF_LIST_PAGE_SIZE}`,body:{appCode:ctx.appCode,filterType:filterType??null,...hookMigrationPlan&&hookMigrationPlan.migrations.length>0?{hookDirectoryMigrations:hookMigrationPlan.migrations.map(migration=>({from:migration.oldDirectory,to:migration.newDirectory}))
|
|
5
|
+
}:{},files:preview},description:`Would inspect ${preview.length} remote Backend Function script(s) for pull`}},async execute(ctx){const config=loadBffProjectConfig(ctx.appCode);const rawLock=await readBffLockFile(config.lockFilePath);const{lockData:lockData,appLock:appLock}=ensureLockScope(rawLock??createEmptyBffLock(),ctx.appCode,config.scriptsRoot,"pull");const filterType=normalizeBffType(ctx.str("type"))??undefined;if(ctx.str("type")&&!filterType){throw CliErrors.validation("--type must be COMMON, ENDPOINT, or HOOK.")}const[scripts,statistics]=await Promise.all([listBffScripts(ctx.appCode,filterType),getBffScriptStatistics(ctx.appCode)]);if(scripts.length===0){return{ok:true,data:{pulled:[],skipped:[],conflicts:[],failed:[]},message:"No remote Backend Function scripts found."}}const force=ctx.bool("force");if(force&&!ctx.nonInteractive){const confirmed=await confirmForce();if(!confirmed){throw CliErrors.cancelled("Force pull cancelled.")}}if(force&&ctx.nonInteractive){}
|
|
6
|
+
const hasHookScripts=scripts.some(script=>normalizeBffType(script.scriptType)==="HOOK");const datasetCodeToAlias=hasHookScripts?buildDatasetCodeToAliasMap(ctx.apiDir,ctx.appCode,ctx.selectedAppName||ctx.mergedCli?.currentApp||ctx.mergedCli?.defaultApp):new Map;const hookLocationMap=createHookLocationMap(statistics);const nextLockData=JSON.parse(JSON.stringify(lockData));const currentAppCode=ctx.appCode;const nextAppLock=nextLockData.apps[currentAppCode];if(!nextAppLock){throw new Error(`Lock scope for app "${currentAppCode}" not found after ensureLockScope.`)}const hookMigration=hasHookScripts?await applyHookDirectoryMigration(await planHookDirectoryMigration(config,nextAppLock,datasetCodeToAlias,await scanLocalBffFunctions(config,"HOOK")),nextAppLock):undefined;const fileTransaction=createPullFileTransaction();const pulled=[];const skipped=[];const conflicts=[];const failed=[];for(const script of scripts){
|
|
7
|
+
const target=resolveRemoteScriptTarget(config,script,hookLocationMap,nextAppLock.functions,datasetCodeToAlias);if(!target){skipped.push({lockKey:`${script.scriptType}/${script.functionName}`,reason:"unresolvable target path"});continue}const lockEntry=nextAppLock.functions[target.lockKey];try{if(!script.id){throw new Error("Remote script missing id.")}if(script.scriptContent==null){throw new Error("Remote script missing content.")}const content=script.scriptContent;const remoteHash=computeContentHash(content);if(!force){const hasConflict=await hasUnsyncedLocalChanges(target.filePath,lockEntry,remoteHash);if(hasConflict){conflicts.push(localUnsyncedConflict(target,script.id));continue}}await fileTransaction.write(target.filePath,content);const nextEntry={hash:remoteHash,remoteId:script.id,version:script.version};if(target.type==="HOOK"&&target.hookLocation){nextEntry.alias=target.hookLocation.alias;nextEntry.datasetCode=target.hookLocation.datasetCode
|
|
8
|
+
;nextEntry.operationType=target.hookLocation.operationType;nextEntry.functionNode=target.hookLocation.functionNode}nextAppLock.functions[target.lockKey]=nextEntry;pulled.push({lockKey:target.lockKey,remoteId:script.id})}catch(error){failed.push({lockKey:target.lockKey,error:error instanceof Error?error.message:String(error)})}}nextAppLock.lastSync=(new Date).toISOString();try{await writeBffLockFile(config.lockFilePath,nextLockData)}catch(error){const rollbackErrors=[...await fileTransaction.rollback(),...await(hookMigration?.rollback())??[]];throw withRollbackErrors(error,"Failed to write the Backend Function lock file; local changes could not be completely rolled back.",rollbackErrors)}return{ok:failed.length===0,data:{pulled:pulled,skipped:skipped,conflicts:conflicts,failed:failed},message:formatPullMessage(pulled.length,skipped.length,conflicts.length,failed.length)}}};function localUnsyncedConflict(target,remoteId){const functionName=target.lockKey.split("/").at(-1);return{
|
|
9
|
+
code:"BFF_LOCAL_UNSYNCED",lockKey:target.lockKey,filePath:target.filePath,...remoteId!=null?{remoteId:remoteId}:{},message:"Local script differs from the last pulled version. Review it before choosing the source of truth.",nextAction:{action:"push_local",command:`${CLI_BIN_NAME} bff push --type ${target.type} --name ${functionName} --format compress`,requiresReview:true,message:"If the reviewed local script should win, run this command to update the remote script. Do not use --force to resolve a content conflict."}}}function formatPullMessage(pulled,skipped,conflicts,failed){const parts=[`Pull complete: ${pulled} pulled`,`${skipped} skipped`];if(conflicts>0){parts.push(`${conflicts} conflict${conflicts===1?"":"s"} ${conflicts===1?"requires":"require"} resolution`)}if(failed>0)parts.push(`${failed} failed`);return parts.join(", ")}async function hasUnsyncedLocalChanges(filePath,lockEntry,remoteHash){if(!await fileExists(filePath))return false
|
|
10
|
+
;const localHash=await computeFileHash(filePath);if(!lockEntry)return remoteHash?localHash!==remoteHash:true;return localHash!==lockEntry.hash}function createPullFileTransaction(){const snapshots=new Map;const restore=async(filePath,snapshot)=>{try{if(snapshot.existed){await ensureParentDirectory(filePath);await writeFile(filePath,snapshot.content)}else{try{await unlink(filePath)}catch(error){if(error.code!=="ENOENT")throw error}}return undefined}catch(error){return error instanceof Error?error:new Error(String(error))}};return{async write(filePath,content){if(!snapshots.has(filePath)){try{snapshots.set(filePath,{existed:true,content:await readFile(filePath)})}catch(error){if(error.code!=="ENOENT")throw error;snapshots.set(filePath,{existed:false})}}try{await ensureParentDirectory(filePath);await writeFile(filePath,content,"utf8")}catch(error){const rollbackError=await restore(filePath,snapshots.get(filePath));if(!rollbackError)snapshots.delete(filePath)
|
|
11
|
+
;throw withRollbackErrors(error,`Failed to write local script "${filePath}".`,rollbackError?[rollbackError]:[])}},async rollback(){const errors=[];for(const[filePath,snapshot]of[...snapshots.entries()].reverse()){const error=await restore(filePath,snapshot);if(error){errors.push(new Error(`Could not restore local script "${filePath}": ${error.message}`))}}return errors}}}function withRollbackErrors(cause,message,rollbackErrors){const original=cause instanceof Error?cause:new Error(String(cause));if(rollbackErrors.length===0)return original;return new AggregateError([original,...rollbackErrors],`${message} Recovery errors: ${rollbackErrors.map(error=>error.message).join("; ")}`)}function buildDatasetCodeToAliasMap(apiDir,appCode,selectedAppName){const source=resolveApiModelSource(apiDir,appCode,selectedAppName);const entries=loadAliasMap(apiDir,undefined,source.filePath,source.profileName);assertUnambiguousHookAliases(entries)
|
|
12
|
+
;return new Map(entries.map(entry=>[entry.datasetCode.toLowerCase(),entry.alias]))}async function planHookDirectoryMigration(config,appLock,datasetCodeToAlias,localHooks){const grouped=new Map;for(const[oldLockKey,entry]of Object.entries(appLock.functions)){const[type,directoryName,operationType,functionNode,functionName,...rest]=oldLockKey.split("/");if(type!=="HOOK"||!directoryName||!operationType||!functionNode||!functionName||rest.length>0||!entry.datasetCode)continue;const alias=datasetCodeToAlias.get(entry.datasetCode.toLowerCase());const newDirectory=alias??entry.datasetCode;if(!isSafeHookDirectorySegment(directoryName)){throw CliErrors.validation(`Cannot migrate unsafe HOOK directory "${directoryName}" from the lock file.`)}if(!isSafeHookDirectorySegment(newDirectory)){throw CliErrors.validation(`Cannot migrate HOOK directory "${directoryName}": its target directory is unsafe.`)}if(directoryName===newDirectory)continue;const group=grouped.get(directoryName)??{
|
|
13
|
+
datasetCode:entry.datasetCode,alias:alias,keyChanges:[]};if(group.datasetCode!==entry.datasetCode){throw CliErrors.validation(`Cannot migrate HOOK directory "${directoryName}": it is tracked by multiple Datasets.`)}const newLockKey=`HOOK/${newDirectory}/${operationType}/${functionNode}/${functionName}`;try{resolveLocalFilePathFromLockKey(config,oldLockKey);resolveLocalFilePathFromLockKey(config,newLockKey)}catch(error){throw CliErrors.validation(`Cannot migrate unsafe HOOK lock key "${oldLockKey}": ${error instanceof Error?error.message:String(error)}`)}group.keyChanges.push({oldLockKey:oldLockKey,newLockKey:newLockKey,entry:entry});grouped.set(directoryName,group)}const changingOldKeys=new Set([...grouped.values()].flatMap(group=>group.keyChanges.map(change=>change.oldLockKey)));const plannedDirectories=new Map;const plannedLockKeys=new Map;for(const[oldDirectory,group]of grouped){const newDirectory=group.alias??group.datasetCode;const directoryKey=hookDirectoryIdentity(newDirectory)
|
|
14
|
+
;const existingDirectorySource=plannedDirectories.get(directoryKey);if(existingDirectorySource&&existingDirectorySource!==oldDirectory){throw CliErrors.validation(`Cannot migrate HOOK directories "${existingDirectorySource}" and "${oldDirectory}": both target "${newDirectory}". Resolve the directories manually before retrying.`)}plannedDirectories.set(directoryKey,oldDirectory);for(const change of group.keyChanges){const existingKeySource=plannedLockKeys.get(change.newLockKey);if(existingKeySource&&existingKeySource!==change.oldLockKey){throw CliErrors.validation(`Cannot migrate HOOK lock keys "${existingKeySource}" and "${change.oldLockKey}": both target "${change.newLockKey}". Resolve the lock entries manually before retrying.`)}if(changingOldKeys.has(change.newLockKey)){throw CliErrors.validation(`Cannot migrate HOOK lock key "${change.oldLockKey}": its target "${change.newLockKey}" is another legacy key being migrated. Resolve the lock entries manually before retrying.`)}
|
|
15
|
+
plannedLockKeys.set(change.newLockKey,change.oldLockKey)}}const currentAliasOwners=new Map;for(const[datasetCode,alias]of datasetCodeToAlias){currentAliasOwners.set(hookDirectoryIdentity(alias),datasetCode)}const migrations=[];for(const[oldDirectory,group]of grouped){const newDirectory=group.alias??group.datasetCode;const oldDirectoryPath=join(config.scriptsRootDir,"HOOK",oldDirectory);const newDirectoryPath=join(config.scriptsRootDir,"HOOK",newDirectory);const oldExists=await directoryExists(oldDirectoryPath);const newExists=await directoryExists(newDirectoryPath);const mode=oldExists?newExists?await sameDirectory(oldDirectoryPath,newDirectoryPath)?"case-rename":undefined:"move":"rekey";if(!mode){throw CliErrors.validation(`Cannot migrate HOOK directory "${oldDirectory}" to "${newDirectory}": the target directory already exists. Resolve the directories and retry.`)}const owner=currentAliasOwners.get(hookDirectoryIdentity(oldDirectory))
|
|
16
|
+
;if(owner&&owner!==group.datasetCode.toLowerCase()){const trackedKeys=new Set(group.keyChanges.map(change=>change.oldLockKey));const unknownScripts=localHooks.filter(fn=>fn.type==="HOOK"&&fn.alias!=null&&hookDirectoryIdentity(fn.alias)===hookDirectoryIdentity(oldDirectory)&&!trackedKeys.has(fn.lockKey));if(unknownScripts.length>0){throw CliErrors.validation(`Cannot migrate HOOK directory "${oldDirectory}": it is now another Dataset alias and contains untracked scripts. Resolve the directory manually before retrying.`)}}const destinationOwner=currentAliasOwners.get(hookDirectoryIdentity(newDirectory));if(destinationOwner&&destinationOwner!==group.datasetCode.toLowerCase()){throw CliErrors.validation(`Cannot migrate HOOK directory "${oldDirectory}" to "${newDirectory}": the destination is another Dataset alias. Resolve the directory manually before retrying.`)}for(const change of group.keyChanges){const targetEntry=appLock.functions[change.newLockKey]
|
|
17
|
+
;if(targetEntry&&!changingOldKeys.has(change.newLockKey)&&!sameHookIdentity(change.entry,targetEntry)){throw CliErrors.validation(`Cannot migrate HOOK directory "${oldDirectory}" to "${newDirectory}": target lock key is already bound to another script.`)}}migrations.push({oldDirectory:oldDirectory,newDirectory:newDirectory,oldDirectoryPath:oldDirectoryPath,newDirectoryPath:newDirectoryPath,mode:mode,alias:group.alias,keyChanges:group.keyChanges})}const projectedFunctions={...appLock.functions};const sourceFilePathByNewLockKey=new Map;const sourceDirectoryPathByNewDirectory=new Map;for(const migration of migrations){const sourceWins=migration.mode!=="rekey";if(sourceWins){sourceDirectoryPathByNewDirectory.set(hookDirectoryIdentity(migration.newDirectory),migration.oldDirectoryPath)}for(const change of migration.keyChanges){const targetEntry=projectedFunctions[change.newLockKey];const selected=sourceWins?change.entry:targetEntry??change.entry
|
|
18
|
+
;projectedFunctions[change.newLockKey]=canonicalizeHookEntry(selected,migration.alias);delete projectedFunctions[change.oldLockKey];if(sourceWins){sourceFilePathByNewLockKey.set(change.newLockKey,resolveLocalFilePathFromLockKey(config,change.oldLockKey))}}}return{migrations:migrations,projectedFunctions:projectedFunctions,sourceFilePathByNewLockKey:sourceFilePathByNewLockKey,sourceDirectoryPathByNewDirectory:sourceDirectoryPathByNewDirectory}}function resolveMigratedSourceFilePath(plan,target){if(!plan||!target)return undefined;const trackedPath=plan.sourceFilePathByNewLockKey.get(target.lockKey);if(trackedPath)return trackedPath;if(target.type!=="HOOK")return undefined;const[,directoryName,...remainingSegments]=target.lockKey.split("/");if(!directoryName||remainingSegments.length===0)return undefined;const sourceDirectoryPath=plan.sourceDirectoryPathByNewDirectory.get(hookDirectoryIdentity(directoryName))
|
|
19
|
+
;return sourceDirectoryPath?`${join(sourceDirectoryPath,...remainingSegments)}.js`:undefined}function sameHookIdentity(left,right){return left.remoteId===right.remoteId&&left.datasetCode===right.datasetCode&&left.operationType===right.operationType&&left.functionNode===right.functionNode}function canonicalizeHookEntry(entry,alias){const{alias:_oldAlias,...withoutAlias}=entry;return alias?{...withoutAlias,alias:alias}:withoutAlias}function hookDirectoryIdentity(directoryName){return directoryName.normalize("NFC").toLowerCase()}function isSafeHookDirectorySegment(value){return isSafeLockKeySegment(value)}async function sameDirectory(left,right){const[leftStat,rightStat]=await Promise.all([stat(left),stat(right)]);return leftStat.dev===rightStat.dev&&leftStat.ino===rightStat.ino}async function applyHookDirectoryMigration(plan,appLock){const originalFunctions=appLock.functions;const originalLastSync=appLock.lastSync;const completed=[];const rollback=async()=>{const errors=[]
|
|
20
|
+
;appLock.functions=originalFunctions;appLock.lastSync=originalLastSync;for(const{migration:migration,temporaryPath:temporaryPath}of[...completed].reverse()){try{if(temporaryPath){await rename(migration.newDirectoryPath,temporaryPath);await rename(temporaryPath,migration.oldDirectoryPath)}else{await rename(migration.newDirectoryPath,migration.oldDirectoryPath)}}catch(error){errors.push(new Error(`Could not restore HOOK directory "${migration.oldDirectory}" from "${migration.newDirectory}": ${error instanceof Error?error.message:String(error)}`))}}return errors};try{for(const migration of plan.migrations){if(migration.mode==="move"){await ensureParentDirectory(migration.newDirectoryPath);await rename(migration.oldDirectoryPath,migration.newDirectoryPath);completed.push({migration:migration})}else if(migration.mode==="case-rename"){const temporaryPath=join(dirname(migration.oldDirectoryPath),`.hook-directory-migrate-${randomUUID()}`);await rename(migration.oldDirectoryPath,temporaryPath)
|
|
21
|
+
;try{await rename(temporaryPath,migration.newDirectoryPath)}catch(error){try{await rename(temporaryPath,migration.oldDirectoryPath)}catch(rollbackError){throw withRollbackErrors(error,`Failed to rename HOOK directory "${migration.oldDirectory}" to "${migration.newDirectory}"; temporary directory "${temporaryPath}" may remain.`,[new Error(`Could not restore temporary HOOK directory "${temporaryPath}" to "${migration.oldDirectory}": ${rollbackError instanceof Error?rollbackError.message:String(rollbackError)}`)])}throw error}completed.push({migration:migration,temporaryPath:temporaryPath})}}appLock.functions=plan.projectedFunctions;return{rollback:rollback}}catch(error){const rollbackErrors=await rollback();throw withRollbackErrors(error,"Failed to migrate HOOK directories; local changes could not be completely rolled back.",rollbackErrors)}}async function confirmForce(){const rl=createInterface({input:process.stdin,output:process.stderr});const answer=await new Promise(resolve=>{
|
|
22
|
+
rl.question("Force pull will overwrite local unsynced changes. Continue? [y/N] ",resolve)});rl.close();return["y","yes"].includes(answer.trim().toLowerCase())}
|
package/lib/commands/bff/push.js
CHANGED
|
@@ -1 +1,16 @@
|
|
|
1
|
-
const a44_0x1c3065=a44_0x529e;(function(_0x4d03d1,_0x5975dd){const _0x29400c=a44_0x529e,_0x7d28b7=_0x4d03d1();while(!![]){try{const _0x32469c=parseInt(_0x29400c(0x118))/0x1+-parseInt(_0x29400c(0x129))/0x2*(-parseInt(_0x29400c(0x133))/0x3)+parseInt(_0x29400c(0xe6))/0x4*(-parseInt(_0x29400c(0xd5))/0x5)+parseInt(_0x29400c(0xe5))/0x6*(parseInt(_0x29400c(0xdb))/0x7)+-parseInt(_0x29400c(0xea))/0x8+-parseInt(_0x29400c(0xe8))/0x9+parseInt(_0x29400c(0x120))/0xa*(parseInt(_0x29400c(0xf0))/0xb);if(_0x32469c===_0x5975dd)break;else _0x7d28b7['push'](_0x7d28b7['shift']());}catch(_0x16d8fc){_0x7d28b7['push'](_0x7d28b7['shift']());}}}(a44_0x3e74,0xf2edc));import{readFile}from'node:fs/promises';import{saveBffScript,getBffScriptInfo,getBffScriptStatistics,getPlatformErrorCode,listDatasets,clearBffScriptCache}from'../../core/api-client.js';import{loadAliasMap}from'../../core/alias-resolver.js';import{resolveApiModelSource}from'../../api/model-source.js';import{loadBffProjectConfig}from'../../core/bff/config.js';import{normalizeBffType,scanLocalBffFunctions}from'../../core/bff/file-system.js';import{buildHookDirectoryIndexes,assertUnambiguousHookAliases,assertUnambiguousHookDirectoryMappings,preflightPushHookDirectories,trackedHookDirectoryMappings}from'../../core/bff/hook-directory.js';import{computeFileHash}from'../../core/bff/hash.js';import{createEmptyBffLock,ensureLockScope,readBffLockFile,writeBffLockFile}from'../../core/bff/lock.js';import{extractScriptDescription,snakeToCamel}from'../../core/bff/utils.js';import{sleep}from'../../utils/sleep.js';import{CLI_BIN_NAME}from'../../constant/cli.js';import{CliErrors}from'../../errors.js';const CACHE_CLEAR_ATTEMPTS=0x2,CACHE_CLEAR_INTERVAL_MS=0x12c;export const bffPush={'service':a44_0x1c3065(0x104),'command':a44_0x1c3065(0x100),'description':a44_0x1c3065(0xe4),'risk':'write','structuredErrors':!![],'flags':[{'name':a44_0x1c3065(0xcf),'type':a44_0x1c3065(0x110),'description':a44_0x1c3065(0xfc),'enum':[a44_0x1c3065(0xdf),a44_0x1c3065(0xe9),'HOOK']},{'name':a44_0x1c3065(0xeb),'type':a44_0x1c3065(0x110),'description':a44_0x1c3065(0xee)},{'name':a44_0x1c3065(0x130),'type':'boolean','description':a44_0x1c3065(0xcb)}],async 'dryRun'(_0x25bd26){const _0x5c0245=a44_0x1c3065,_0x2d843f=loadBffProjectConfig(_0x25bd26['appCode']),_0x522aed=await readBffLockFile(_0x2d843f['lockFilePath']),{appLock:_0x1a082a}=ensureLockScope(_0x522aed??createEmptyBffLock(),_0x25bd26[_0x5c0245(0x108)],_0x2d843f[_0x5c0245(0x136)],_0x5c0245(0x100)),_0x25b0c0=await getTargetFunctions(_0x2d843f,_0x25bd26),_0x39ba58=_0x25b0c0[_0x5c0245(0x119)](_0x3caa0d=>_0x3caa0d['type']===_0x5c0245(0x122))?await scanLocalBffFunctions(_0x2d843f,'HOOK'):_0x25b0c0,_0x311808=await buildHookMaps(_0x25bd26[_0x5c0245(0x108)],_0x25bd26[_0x5c0245(0x10f)],_0x39ba58,_0x1a082a,_0x25bd26[_0x5c0245(0x103)]||_0x25bd26[_0x5c0245(0xfb)]?.[_0x5c0245(0x121)]||_0x25bd26[_0x5c0245(0xfb)]?.[_0x5c0245(0xd9)]),_0x2922bd=_0x25bd26['bool'](_0x5c0245(0x130)),_0x28ad02=[];for(const _0x4cf460 of _0x25b0c0){const _0xf6def2=await computeFileHash(_0x4cf460['filePath']),_0x10b170=_0x1a082a[_0x5c0245(0xce)][_0x4cf460[_0x5c0245(0xde)]],_0x421864=!!_0x10b170&&_0x10b170[_0x5c0245(0xe1)]===_0xf6def2,_0x27def8=_0x311808[_0x5c0245(0x109)]['get'](_0x4cf460[_0x5c0245(0xde)]),_0x8cd2ec=!!_0x10b170?.[_0x5c0245(0xf6)]&&_0x10b170[_0x5c0245(0xef)]==null&&(_0x2922bd||!_0x421864),_0x22e7fa=_0x8cd2ec?missingRemoteVersionConflict(_0x4cf460,_0x10b170):undefined,_0x269da3=_0x311808[_0x5c0245(0xd3)][_0x5c0245(0x116)](_0x4cf460[_0x5c0245(0xde)])?_0x5c0245(0x106):!_0x2922bd&&_0x421864?_0x5c0245(0x126):_0x22e7fa?'conflict':_0x5c0245(0x11c);_0x28ad02[_0x5c0245(0x100)]({'lockKey':_0x4cf460[_0x5c0245(0xde)],'filePath':_0x4cf460[_0x5c0245(0x137)],'remoteId':_0x10b170?.[_0x5c0245(0xf6)]??null,'mode':_0x10b170?.[_0x5c0245(0xf6)]?_0x5c0245(0x105):_0x5c0245(0x11f),'status':_0x269da3,..._0x311808[_0x5c0245(0xd3)][_0x5c0245(0x116)](_0x4cf460[_0x5c0245(0xde)])?{'error':_0x311808[_0x5c0245(0xd3)][_0x5c0245(0xcc)](_0x4cf460[_0x5c0245(0xde)])}:{},..._0x22e7fa?{'conflict':_0x22e7fa}:{},..._0x311808[_0x5c0245(0x135)][_0x5c0245(0x116)](_0x4cf460['lockKey'])?{'datasetCode':_0x10b170?.[_0x5c0245(0x13b)],'bindingPreserved':!![],'warnings':[existingHookWarning(_0x4cf460[_0x5c0245(0xde)])]}:{},..._0x27def8?{'alias':_0x27def8[_0x5c0245(0x11e)]??null,'datasetCode':_0x27def8['datasetCode'],'operationType':_0x4cf460[_0x5c0245(0xf1)],'functionNode':_0x4cf460[_0x5c0245(0xd4)],'warnings':_0x27def8['warnings']}:{}});}return{'method':_0x5c0245(0xf2),'url':_0x5c0245(0x115),'body':{'appCode':_0x25bd26['appCode'],'force':_0x2922bd,'files':_0x28ad02,'cacheClearAtRuntime':_0x28ad02[_0x5c0245(0x119)](_0x2f3030=>_0x2f3030[_0x5c0245(0x10a)]===_0x5c0245(0x11c)),'cacheClearAtRuntimeTimes':_0x28ad02[_0x5c0245(0x119)](_0x14f0d9=>_0x14f0d9['status']===_0x5c0245(0x11c))?CACHE_CLEAR_ATTEMPTS:0x0},'description':_0x5c0245(0x117)+_0x28ad02[_0x5c0245(0xfd)]+'\x20local\x20Backend\x20Function\x20script(s)\x20for\x20push\x20and\x20clear\x20runtime\x20cache\x20if\x20files\x20are\x20uploaded'};},async 'execute'(_0x2ffbf4){const _0x270509=a44_0x1c3065,_0x2f7422=loadBffProjectConfig(_0x2ffbf4[_0x270509(0x108)]),_0x7bf914=await readBffLockFile(_0x2f7422[_0x270509(0xd2)]),{lockData:_0x29fb03,appLock:_0x511b1b}=ensureLockScope(_0x7bf914??createEmptyBffLock(),_0x2ffbf4['appCode'],_0x2f7422[_0x270509(0x136)],_0x270509(0x100)),_0x3d000e=await getTargetFunctions(_0x2f7422,_0x2ffbf4);if(_0x3d000e[_0x270509(0xfd)]===0x0)return{'ok':!![],'data':{'uploaded':[],'skipped':[],'conflicts':[],'failed':[]},'message':_0x270509(0xd1)};const _0x2e943e=_0x2ffbf4['bool'](_0x270509(0x130)),_0x555c90=JSON[_0x270509(0x128)](JSON[_0x270509(0x12b)](_0x29fb03)),_0x7df380=_0x555c90[_0x270509(0x12e)][_0x2ffbf4[_0x270509(0x108)]];if(!_0x7df380)throw new Error(_0x270509(0x13d)+_0x2ffbf4[_0x270509(0x108)]+'\x22\x20not\x20found\x20after\x20ensureLockScope.');const _0x71a833=_0x3d000e[_0x270509(0x119)](_0x27d5b4=>_0x27d5b4[_0x270509(0xcf)]===_0x270509(0x122))?await scanLocalBffFunctions(_0x2f7422,_0x270509(0x122)):_0x3d000e,_0x3c47a3=await buildHookMaps(_0x2ffbf4[_0x270509(0x108)],_0x2ffbf4[_0x270509(0x10f)],_0x71a833,_0x7df380,_0x2ffbf4[_0x270509(0x103)]||_0x2ffbf4['mergedCli']?.[_0x270509(0x121)]||_0x2ffbf4['mergedCli']?.[_0x270509(0xd9)]),_0x46366c=[],_0xeab10e=[],_0x14e7d1=[],_0x553085=[];for(const _0x560106 of _0x3d000e){const _0x3461d5=_0x3c47a3[_0x270509(0xd3)][_0x270509(0xcc)](_0x560106[_0x270509(0xde)]);if(_0x3461d5){_0x553085[_0x270509(0x100)]({'lockKey':_0x560106['lockKey'],'error':_0x3461d5});continue;}const _0x3949c6=await computeFileHash(_0x560106[_0x270509(0x137)]),_0x57a16a=_0x7df380[_0x270509(0xce)][_0x560106[_0x270509(0xde)]];if(!_0x2e943e&&_0x57a16a&&_0x57a16a[_0x270509(0xe1)]===_0x3949c6){_0xeab10e['push']({'lockKey':_0x560106[_0x270509(0xde)],'reason':_0x270509(0x126)});continue;}if(_0x57a16a?.[_0x270509(0xf6)]&&_0x57a16a[_0x270509(0xef)]==null){_0x14e7d1[_0x270509(0x100)](missingRemoteVersionConflict(_0x560106,_0x57a16a));continue;}try{await uploadSingleFunction(_0x2ffbf4[_0x270509(0x108)],_0x560106,_0x7df380,_0x3c47a3);const _0xa9738c=_0x7df380[_0x270509(0xce)][_0x560106[_0x270509(0xde)]];_0x46366c[_0x270509(0x100)]({'lockKey':_0x560106[_0x270509(0xde)],'remoteId':_0xa9738c?.[_0x270509(0xf6)]??0x0});}catch(_0x536189){const _0x1da99f=remoteVersionChangedConflict(_0x560106,_0x57a16a,_0x536189);if(_0x1da99f){_0x14e7d1[_0x270509(0x100)](_0x1da99f);continue;}_0x553085[_0x270509(0x100)]({'lockKey':_0x560106[_0x270509(0xde)],'error':_0x536189 instanceof Error?_0x536189[_0x270509(0x10c)]:String(_0x536189)});}}_0x7df380[_0x270509(0xfe)]=new Date()[_0x270509(0xdd)](),await writeBffLockFile(_0x2f7422[_0x270509(0xd2)],_0x555c90),await waitForUploadedLockEntries(_0x2f7422['lockFilePath'],_0x2ffbf4['appCode'],_0x46366c['map'](_0x1baba9=>_0x1baba9[_0x270509(0xde)]));let _0x5a4795={'attempted':![],'cleared':![]};if(_0x46366c[_0x270509(0xfd)]>0x0)try{let _0x43820e='';for(let _0x1f25b2=0x0;_0x1f25b2<CACHE_CLEAR_ATTEMPTS;_0x1f25b2+=0x1){_0x43820e=await clearBffScriptCache(),_0x1f25b2<CACHE_CLEAR_ATTEMPTS-0x1&&await sleep(CACHE_CLEAR_INTERVAL_MS);}_0x5a4795={'attempted':!![],'cleared':!![],'message':_0x43820e||'Runtime\x20script\x20cache\x20cleared.'};}catch(_0x748f5b){_0x5a4795={'attempted':!![],'cleared':![],'error':_0x748f5b instanceof Error?_0x748f5b['message']:String(_0x748f5b)};}const _0x427533=_0x553085['length']===0x0&&(_0x5a4795[_0x270509(0x13a)]?_0x5a4795[_0x270509(0xe3)]:!![]),_0x41e5d3=_0x427533,_0x26f64e=_0x5a4795[_0x270509(0x13a)]?_0x5a4795[_0x270509(0xe3)]?_0x270509(0xdc):_0x270509(0x101):_0x270509(0x111);return{'ok':_0x41e5d3,'data':{'uploaded':_0x46366c,'skipped':_0xeab10e,'conflicts':_0x14e7d1,'failed':_0x553085,'cacheClear':_0x5a4795,'warnings':[...[..._0x3c47a3[_0x270509(0x109)][_0x270509(0x11b)]()][_0x270509(0xe2)](_0x401279=>_0x401279[_0x270509(0x12d)]),...[..._0x3c47a3[_0x270509(0x135)]][_0x270509(0xf4)](existingHookWarning)]},'message':formatPushMessage(_0x46366c[_0x270509(0xfd)],_0xeab10e[_0x270509(0xfd)],_0x14e7d1[_0x270509(0xfd)],_0x553085[_0x270509(0xfd)],_0x26f64e)};}};function missingRemoteVersionConflict(_0x31ec8c,_0x1c5aa1){const _0x55f064=a44_0x1c3065;return remoteVersionConflict(_0x31ec8c,_0x1c5aa1,_0x55f064(0xd6),'The\x20local\x20sync\x20lock\x20has\x20no\x20remote\x20version\x20for\x20this\x20script.');}function remoteVersionChangedConflict(_0x474f6c,_0xd5a32,_0x4b521e){const _0xaff146=a44_0x1c3065;if(!_0xd5a32?.[_0xaff146(0xf6)]||_0xd5a32[_0xaff146(0xef)]==null||!isRemoteVersionConflict(_0x4b521e))return undefined;return remoteVersionConflict(_0x474f6c,_0xd5a32,_0xaff146(0x123),_0xaff146(0xd0));}function remoteVersionConflict(_0x5c6900,_0x3f2efa,_0x1b36fa,_0x26d028){const _0x5110d2=a44_0x1c3065;return{'code':_0x1b36fa,'lockKey':_0x5c6900[_0x5110d2(0xde)],'filePath':_0x5c6900[_0x5110d2(0x137)],'remoteId':_0x3f2efa[_0x5110d2(0xf6)],..._0x3f2efa[_0x5110d2(0xef)]!=null?{'expectedVersion':_0x3f2efa['version']}:{},'message':_0x26d028,'nextAction':{'action':_0x5110d2(0xfa),'command':CLI_BIN_NAME+'\x20bff\x20detail\x20--id\x20'+_0x3f2efa[_0x5110d2(0xf6)]+_0x5110d2(0x131),'requiresReview':!![],'message':_0x5110d2(0x138)}};}function isRemoteVersionConflict(_0x2b2363){const _0xe6fc6b=a44_0x1c3065,_0x43c65a=_0x2b2363 instanceof Error?_0x2b2363[_0xe6fc6b(0x10c)]:String(_0x2b2363),_0x393b7f=getPlatformErrorCode(_0x2b2363)??'';return[_0x43c65a,_0x393b7f][_0xe6fc6b(0x119)](_0xcc2b85=>/(?:version|optimistic)[\s_-]*(?:conflict|mismatch|changed|stale|out[\s_-]*of[\s_-]*date)|(?:conflict|mismatch|changed|stale|out[\s_-]*of[\s_-]*date)[\s_-]*(?:version|optimistic)/i[_0xe6fc6b(0x10b)](_0xcc2b85));}function formatPushMessage(_0x28e726,_0x5bb011,_0x258d4d,_0x2befe4,_0x4897cf){const _0x30c59c=a44_0x1c3065,_0x1baa8c=[_0x30c59c(0xcd)+_0x28e726+_0x30c59c(0x12a),_0x5bb011+_0x30c59c(0xec)];_0x258d4d>0x0&&_0x1baa8c['push'](_0x258d4d+_0x30c59c(0x11a)+(_0x258d4d===0x1?'':'s')+'\x20'+(_0x258d4d===0x1?_0x30c59c(0x11d):_0x30c59c(0xe7))+_0x30c59c(0x13c));if(_0x2befe4>0x0)_0x1baa8c[_0x30c59c(0x100)](_0x2befe4+'\x20failed');return _0x1baa8c[_0x30c59c(0x100)](_0x4897cf),_0x1baa8c['join'](',\x20');}async function getTargetFunctions(_0x14485e,_0x28a473){const _0x4e9ce8=a44_0x1c3065,_0x67d1b5=_0x28a473['str'](_0x4e9ce8(0xcf)),_0x1d8d6c=_0x28a473['str'](_0x4e9ce8(0xeb)),_0x1aaed6=normalizeBffType(_0x67d1b5)??undefined;if(_0x1d8d6c&&!_0x1aaed6)throw CliErrors['validation'](_0x4e9ce8(0xf3));const _0xee6fab=await scanLocalBffFunctions(_0x14485e,_0x1aaed6);if(_0x1d8d6c){const _0x41033c=_0xee6fab[_0x4e9ce8(0x125)](_0x145706=>_0x145706[_0x4e9ce8(0xeb)]===_0x1d8d6c);if(_0x41033c[_0x4e9ce8(0xfd)]===0x0)throw CliErrors[_0x4e9ce8(0x139)](_0x4e9ce8(0xf9)+_0x1aaed6+'/'+_0x1d8d6c);return _0x41033c;}return _0xee6fab;}function a44_0x529e(_0x2b2e83,_0x5e7ba3){_0x2b2e83=_0x2b2e83-0xcb;const _0x3e7451=a44_0x3e74();let _0x529e7a=_0x3e7451[_0x2b2e83];return _0x529e7a;}function existingHookWarning(_0x144365){const _0x3612ef=a44_0x1c3065;return{'code':_0x3612ef(0x112),'lockKey':_0x144365,'message':_0x3612ef(0x113)};}async function buildHookMaps(_0x43a4d8,_0xf0582b,_0x2a275f,_0x230e7b,_0x1172d7){const _0x43f881=a44_0x1c3065,_0x1f4f5f=_0x2a275f[_0x43f881(0x119)](_0x136627=>_0x136627[_0x43f881(0xcf)]===_0x43f881(0x122));if(!_0x1f4f5f)return{'resolutions':new Map(),'failures':new Map(),'existingHooks':new Set()};const _0x505bef=resolveApiModelSource(_0xf0582b,_0x43a4d8,_0x1172d7),_0x36c245=loadAliasMap(_0xf0582b,undefined,_0x505bef[_0x43f881(0x137)],_0x505bef[_0x43f881(0xed)]);assertUnambiguousHookAliases(_0x36c245);const _0x5288b4=[..._0x36c245['map'](_0xb10e38=>[_0xb10e38['alias'],_0xb10e38['datasetCode']]),...trackedHookDirectoryMappings(_0x230e7b)[_0x43f881(0xf4)](_0x527b92=>[_0x527b92[_0x43f881(0x11e)],_0x527b92[_0x43f881(0x13b)]])],_0x16958b=await listDatasets(_0x43a4d8);assertUnambiguousHookDirectoryMappings(_0x5288b4[_0x43f881(0xf4)](([_0x4d6bce,_0x3399ef])=>({'alias':_0x4d6bce,'datasetCode':_0x3399ef})));const _0x2ab01b=buildHookDirectoryIndexes(_0x16958b,_0x5288b4),_0x131178=new Map(),_0x145933=preflightPushHookDirectories(_0x2a275f,_0x230e7b,_0x2ab01b,_0x131178),_0x13298a=new Set(),_0x4b6048=_0x2a275f['filter'](_0x3d750c=>_0x131178['get'](_0x3d750c[_0x43f881(0xde)])?.[_0x43f881(0xf5)](_0x43f881(0x10e))&&_0x230e7b[_0x43f881(0xce)][_0x3d750c['lockKey']]?.[_0x43f881(0xf6)]&&_0x230e7b[_0x43f881(0xce)][_0x3d750c[_0x43f881(0xde)]]?.[_0x43f881(0x13b)]);if(_0x4b6048[_0x43f881(0xfd)]>0x0){let _0x206244;try{_0x206244=await getBffScriptStatistics(_0x43a4d8);}catch(_0x1ffeac){for(const _0x508b84 of _0x4b6048)_0x131178[_0x43f881(0xf7)](_0x508b84[_0x43f881(0xde)],_0x43f881(0x114)+(_0x1ffeac instanceof Error?_0x1ffeac[_0x43f881(0x10c)]:String(_0x1ffeac)));return{'resolutions':_0x145933,'failures':_0x131178,'existingHooks':_0x13298a};}for(const _0x52fc45 of _0x4b6048){const _0x178c17=_0x230e7b[_0x43f881(0xce)][_0x52fc45[_0x43f881(0xde)]];try{const _0x3a1cc1=new Set(_0x2a275f['filter'](_0x5bda1c=>_0x5bda1c[_0x43f881(0xcf)]===_0x43f881(0x122)&&_0x230e7b[_0x43f881(0xce)][_0x5bda1c[_0x43f881(0xde)]]?.['datasetCode']===_0x178c17[_0x43f881(0x13b)])['map'](_0x483935=>_0x483935[_0x43f881(0x11e)]));if(_0x3a1cc1[_0x43f881(0xe0)]>0x1)throw CliErrors[_0x43f881(0x139)](_0x43f881(0xd7));const _0x2a08ce=_0x206244[_0x43f881(0xe2)](_0x4eb74b=>[{'datasetCode':_0x4eb74b['datasetCode'],'operationType':snakeToCamel(_0x4eb74b['operationType']),'functionNode':_0x43f881(0x107),'id':_0x4eb74b[_0x43f881(0xda)]},{'datasetCode':_0x4eb74b[_0x43f881(0x13b)],'operationType':snakeToCamel(_0x4eb74b[_0x43f881(0xf1)]),'functionNode':_0x43f881(0x12f),'id':_0x4eb74b[_0x43f881(0x124)]}])[_0x43f881(0x125)](_0x171e55=>_0x171e55['id']===_0x178c17[_0x43f881(0xf6)]),_0xacb4b5=await getBffScriptInfo(_0x178c17['remoteId']);if(_0xacb4b5['id']!==_0x178c17[_0x43f881(0xf6)]||_0xacb4b5[_0x43f881(0x108)]!==_0x43a4d8||_0xacb4b5[_0x43f881(0x102)]!=='HOOK'||_0xacb4b5[_0x43f881(0x127)]!==_0x52fc45[_0x43f881(0xeb)]||_0x178c17[_0x43f881(0xef)]==null||_0xacb4b5[_0x43f881(0xef)]!==_0x178c17[_0x43f881(0xef)]||_0x2a08ce['length']!==0x1||_0x2a08ce[0x0][_0x43f881(0x13b)]!==_0x178c17[_0x43f881(0x13b)]||_0x2a08ce[0x0][_0x43f881(0xf1)]!==_0x52fc45[_0x43f881(0xf1)]||_0x2a08ce[0x0][_0x43f881(0xd4)]!==_0x52fc45[_0x43f881(0xd4)]||_0x178c17[_0x43f881(0xf1)]!==_0x52fc45[_0x43f881(0xf1)]||_0x178c17[_0x43f881(0xd4)]!==_0x52fc45[_0x43f881(0xd4)])throw CliErrors[_0x43f881(0x139)](_0x43f881(0x12c));_0x13298a[_0x43f881(0x10d)](_0x52fc45['lockKey']),_0x131178['delete'](_0x52fc45[_0x43f881(0xde)]);}catch(_0x20063f){_0x131178['set'](_0x52fc45[_0x43f881(0xde)],_0x20063f instanceof Error?_0x20063f[_0x43f881(0x10c)]:String(_0x20063f));}}}return{'resolutions':_0x145933,'failures':_0x131178,'existingHooks':_0x13298a};}function a44_0x3e74(){const _0x52b059=['7380COHIyU','BFF_REMOTE_VERSION_MISSING','Multiple\x20HOOK\x20directories\x20reference\x20the\x20same\x20missing\x20Dataset.\x20Resolve\x20duplicate\x20directories\x20before\x20pushing.','datasetId','defaultApp','beforeScriptId','5868303XeYhPz','runtime\x20cache\x20cleared','toISOString','lockKey','COMMON','size','hash','flatMap','cleared','Push\x20local\x20Backend\x20Function\x20scripts\x20to\x20remote','6APnjvl','4508reaMor','require','6935463rOMseI','ENDPOINT','1150152uWZQtZ','name','\x20skipped','profileName','Push\x20only\x20the\x20named\x20function\x20(requires\x20--type)','version','9386223IyUzTJ','operationType','POST','--name\x20requires\x20--type\x20to\x20identify\x20the\x20function.','map','startsWith','remoteId','set','Lock\x20file\x20not\x20settled\x20after\x20push\x20for\x20','Local\x20function\x20not\x20found:\x20','review_remote_and_merge','mergedCli','Push\x20only\x20this\x20script\x20type','length','lastSync','description','push','runtime\x20cache\x20clear\x20failed','scriptType','selectedAppName','bff','update','failed','before','appCode','resolutions','status','test','message','add','HOOK_DATASET_NOT_FOUND:','apiDir','string','runtime\x20cache\x20not\x20needed','EXISTING_HOOK_BINDING_PRESERVED','Dataset\x20metadata\x20is\x20unavailable;\x20the\x20existing\x20script\x20and\x20binding\x20were\x20verified.\x20Update\x20by\x20script\x20ID\x20without\x20rebinding.','Cannot\x20verify\x20existing\x20HOOK\x20binding:\x20','/api/management/library/scripts/save','has','Would\x20inspect\x20','118495Hyralg','some','\x20conflict','values','would_push','requires','alias','create','30fkGtoM','currentApp','HOOK','BFF_REMOTE_VERSION_CHANGED','afterScriptId','filter','unchanged','functionName','parse','16046RfHkjP','\x20uploaded','stringify','Existing\x20HOOK\x20identity,\x20version\x20or\x20binding\x20does\x20not\x20match\x20the\x20local\x20lock.\x20Pull\x20and\x20review\x20before\x20pushing.','warnings','apps','after','force','\x20--format\x20compress','script','21VQPnqu','Incomplete\x20HOOK\x20path:\x20','existingHooks','scriptsRoot','filePath','Review\x20the\x20current\x20remote\x20source,\x20merge\x20it\x20into\x20the\x20local\x20script,\x20then\x20retry\x20push.\x20Do\x20not\x20use\x20--force\x20unless\x20you\x20intentionally\x20discard\x20local\x20changes.','validation','attempted','datasetCode','\x20resolution','Lock\x20scope\x20for\x20app\x20\x22',':\x20missing\x20remote\x20version.\x20Run\x20`push`\x20after\x20`pull`\x20to\x20sync\x20version\x20info.','dataset','Force\x20push\x20ignoring\x20hash\x20protection','get','Push\x20complete:\x20','functions','type','Remote\x20script\x20version\x20changed\x20since\x20the\x20last\x20pull.','No\x20local\x20Backend\x20Function\x20scripts\x20found.','lockFilePath','failures','functionNode'];a44_0x3e74=function(){return _0x52b059;};return a44_0x3e74();}async function uploadSingleFunction(_0x4b724e,_0x1c35c3,_0x214b38,_0x3b3613){const _0x2e79d4=a44_0x1c3065,_0x2dab4c=await readFile(_0x1c35c3[_0x2e79d4(0x137)],'utf8'),_0x529d95=await computeFileHash(_0x1c35c3['filePath']),_0x26ba8a=_0x214b38['functions'][_0x1c35c3[_0x2e79d4(0xde)]];if(_0x26ba8a?.[_0x2e79d4(0xf6)]&&_0x26ba8a[_0x2e79d4(0xef)]==null)throw CliErrors['validation'](_0x1c35c3[_0x2e79d4(0xde)]+_0x2e79d4(0x13e));let _0x4e7bb4=extractScriptDescription(_0x2dab4c);if(!_0x4e7bb4&&_0x26ba8a?.[_0x2e79d4(0xf6)]){const _0x2b4b9b=await getBffScriptInfo(_0x26ba8a[_0x2e79d4(0xf6)]);_0x4e7bb4=_0x2b4b9b['description']||undefined;}const _0x141343={'appCode':_0x4b724e,'functionName':_0x1c35c3[_0x2e79d4(0xeb)],'scriptType':_0x1c35c3[_0x2e79d4(0xcf)],'scriptContent':_0x2dab4c};if(_0x26ba8a?.[_0x2e79d4(0xf6)])_0x141343['id']=_0x26ba8a[_0x2e79d4(0xf6)];if(_0x26ba8a?.['version']!=null)_0x141343[_0x2e79d4(0xef)]=_0x26ba8a[_0x2e79d4(0xef)];if(_0x4e7bb4)_0x141343[_0x2e79d4(0xff)]=_0x4e7bb4;if(_0x1c35c3[_0x2e79d4(0xcf)]===_0x2e79d4(0x122)){const _0x13aa01=_0x3b3613['resolutions'][_0x2e79d4(0xcc)](_0x1c35c3[_0x2e79d4(0xde)]);if(!_0x13aa01&&!_0x3b3613[_0x2e79d4(0x135)][_0x2e79d4(0x116)](_0x1c35c3[_0x2e79d4(0xde)])||!_0x1c35c3[_0x2e79d4(0xf1)]||!_0x1c35c3['functionNode'])throw CliErrors[_0x2e79d4(0x139)](_0x2e79d4(0x134)+_0x1c35c3[_0x2e79d4(0xde)]);_0x13aa01&&(_0x141343[_0x2e79d4(0xd8)]=_0x13aa01[_0x2e79d4(0x13f)]['id'],_0x141343[_0x2e79d4(0xf1)]=_0x1c35c3[_0x2e79d4(0xf1)]),_0x141343['functionNode']=_0x1c35c3[_0x2e79d4(0xd4)];}const _0x785c11=await saveBffScript(_0x141343),_0x3a9bab=_0x785c11['id'],_0x44a042=_0x785c11[_0x2e79d4(0x132)]??await getBffScriptInfo(_0x3a9bab),_0x95261a={'hash':_0x529d95,'remoteId':_0x3a9bab,'version':_0x44a042[_0x2e79d4(0xef)]};if(_0x1c35c3['type']==='HOOK'){const _0x45adf2=_0x3b3613[_0x2e79d4(0x109)][_0x2e79d4(0xcc)](_0x1c35c3[_0x2e79d4(0xde)]);if(!_0x45adf2){_0x214b38[_0x2e79d4(0xce)][_0x1c35c3[_0x2e79d4(0xde)]]={..._0x26ba8a,..._0x95261a};return;}_0x95261a[_0x2e79d4(0x11e)]=_0x45adf2[_0x2e79d4(0x11e)]??_0x26ba8a?.[_0x2e79d4(0x11e)],_0x95261a[_0x2e79d4(0x13b)]=_0x45adf2['datasetCode'],_0x95261a[_0x2e79d4(0xf1)]=_0x1c35c3[_0x2e79d4(0xf1)],_0x95261a[_0x2e79d4(0xd4)]=_0x1c35c3[_0x2e79d4(0xd4)];}_0x214b38[_0x2e79d4(0xce)][_0x1c35c3[_0x2e79d4(0xde)]]=_0x95261a;}const LOCK_SETTLE_RETRY_COUNT=0x14,LOCK_SETTLE_DELAY_MS=0x64;async function waitForUploadedLockEntries(_0xf01919,_0x534b2e,_0x1a1dad){const _0xe99306=a44_0x1c3065;if(_0x1a1dad['length']===0x0)return;for(let _0x372ced=0x0;_0x372ced<LOCK_SETTLE_RETRY_COUNT;_0x372ced+=0x1){const _0x1ef31e=await readBffLockFile(_0xf01919),_0x4e5552=_0x1ef31e?.[_0xe99306(0x12e)]?.[_0x534b2e]?.[_0xe99306(0xce)]??{},_0x155716=_0x1a1dad['every'](_0x5a1bab=>!!_0x4e5552[_0x5a1bab]?.[_0xe99306(0xf6)]);if(_0x155716)return;await sleep(LOCK_SETTLE_DELAY_MS);}throw new Error(_0xe99306(0xf8)+_0x1a1dad['join'](',\x20')+'.');}
|
|
1
|
+
import{readFile}from"node:fs/promises";import{saveBffScript,getBffScriptInfo,getBffScriptStatistics,getPlatformErrorCode,listDatasets,clearBffScriptCache}from"../../core/api-client.js";import{loadAliasMap}from"../../core/alias-resolver.js";import{resolveApiModelSource}from"../../api/model-source.js";import{loadBffProjectConfig}from"../../core/bff/config.js";import{normalizeBffType,scanLocalBffFunctions}from"../../core/bff/file-system.js";import{buildHookDirectoryIndexes,assertUnambiguousHookAliases,assertUnambiguousHookDirectoryMappings,preflightPushHookDirectories,trackedHookDirectoryMappings}from"../../core/bff/hook-directory.js";import{computeFileHash}from"../../core/bff/hash.js";import{createEmptyBffLock,ensureLockScope,readBffLockFile,writeBffLockFile}from"../../core/bff/lock.js";import{extractScriptDescription,snakeToCamel}from"../../core/bff/utils.js";import{sleep}from"../../utils/sleep.js";import{CLI_BIN_NAME}from"../../constant/cli.js";import{CliErrors}from"../../errors.js"
|
|
2
|
+
;const CACHE_CLEAR_ATTEMPTS=2;const CACHE_CLEAR_INTERVAL_MS=300;export const bffPush={service:"bff",command:"push",description:"Push local Backend Function scripts to remote",risk:"write",structuredErrors:true,flags:[{name:"type",type:"string",description:"Push only this script type",enum:["COMMON","ENDPOINT","HOOK"]},{name:"name",type:"string",description:"Push only the named function (requires --type)"},{name:"force",type:"boolean",description:"Force push ignoring hash protection"}],async dryRun(ctx){const config=loadBffProjectConfig(ctx.appCode);const rawLock=await readBffLockFile(config.lockFilePath);const{appLock:appLock}=ensureLockScope(rawLock??createEmptyBffLock(),ctx.appCode,config.scriptsRoot,"push");const localFunctions=await getTargetFunctions(config,ctx);const preflightFunctions=localFunctions.some(fn=>fn.type==="HOOK")?await scanLocalBffFunctions(config,"HOOK"):localFunctions
|
|
3
|
+
;const hookMaps=await buildHookMaps(ctx.appCode,ctx.apiDir,preflightFunctions,appLock,ctx.selectedAppName||ctx.mergedCli?.currentApp||ctx.mergedCli?.defaultApp);const force=ctx.bool("force");const preview=[];for(const fn of localFunctions){const localHash=await computeFileHash(fn.filePath);const lockEntry=appLock.functions[fn.lockKey];const unchanged=!!lockEntry&&lockEntry.hash===localHash;const hook=hookMaps.resolutions.get(fn.lockKey);const missingRemoteVersion=!!lockEntry?.remoteId&&lockEntry.version==null&&(force||!unchanged);const conflict=missingRemoteVersion?missingRemoteVersionConflict(fn,lockEntry):undefined;const status=hookMaps.failures.has(fn.lockKey)?"failed":!force&&unchanged?"unchanged":conflict?"conflict":"would_push";preview.push({lockKey:fn.lockKey,filePath:fn.filePath,remoteId:lockEntry?.remoteId??null,mode:lockEntry?.remoteId?"update":"create",status:status,...hookMaps.failures.has(fn.lockKey)?{error:hookMaps.failures.get(fn.lockKey)}:{},...conflict?{
|
|
4
|
+
conflict:conflict}:{},...hookMaps.existingHooks.has(fn.lockKey)?{datasetCode:lockEntry?.datasetCode,bindingPreserved:true,warnings:[existingHookWarning(fn.lockKey)]}:{},...hook?{alias:hook.alias??null,datasetCode:hook.datasetCode,operationType:fn.operationType,functionNode:fn.functionNode,warnings:hook.warnings}:{}})}return{method:"POST",url:"/api/management/library/scripts/save",body:{appCode:ctx.appCode,force:force,files:preview,cacheClearAtRuntime:preview.some(item=>item.status==="would_push"),cacheClearAtRuntimeTimes:preview.some(item=>item.status==="would_push")?CACHE_CLEAR_ATTEMPTS:0},description:`Would inspect ${preview.length} local Backend Function script(s) for push and clear runtime cache if files are uploaded`}},async execute(ctx){const config=loadBffProjectConfig(ctx.appCode);const rawLock=await readBffLockFile(config.lockFilePath);const{lockData:lockData,appLock:appLock}=ensureLockScope(rawLock??createEmptyBffLock(),ctx.appCode,config.scriptsRoot,"push")
|
|
5
|
+
;const localFunctions=await getTargetFunctions(config,ctx);if(localFunctions.length===0){return{ok:true,data:{uploaded:[],skipped:[],conflicts:[],failed:[]},message:"No local Backend Function scripts found."}}const force=ctx.bool("force");const nextLockData=JSON.parse(JSON.stringify(lockData));const nextAppLock=nextLockData.apps[ctx.appCode];if(!nextAppLock){throw new Error(`Lock scope for app "${ctx.appCode}" not found after ensureLockScope.`)}const preflightFunctions=localFunctions.some(fn=>fn.type==="HOOK")?await scanLocalBffFunctions(config,"HOOK"):localFunctions;const hookMaps=await buildHookMaps(ctx.appCode,ctx.apiDir,preflightFunctions,nextAppLock,ctx.selectedAppName||ctx.mergedCli?.currentApp||ctx.mergedCli?.defaultApp);const uploaded=[];const skipped=[];const conflicts=[];const failed=[];for(const fn of localFunctions){const preflightError=hookMaps.failures.get(fn.lockKey);if(preflightError){failed.push({lockKey:fn.lockKey,error:preflightError});continue}
|
|
6
|
+
const localHash=await computeFileHash(fn.filePath);const lockEntry=nextAppLock.functions[fn.lockKey];if(!force&&lockEntry&&lockEntry.hash===localHash){skipped.push({lockKey:fn.lockKey,reason:"unchanged"});continue}if(lockEntry?.remoteId&&lockEntry.version==null){conflicts.push(missingRemoteVersionConflict(fn,lockEntry));continue}try{await uploadSingleFunction(ctx.appCode,fn,nextAppLock,hookMaps);const entry=nextAppLock.functions[fn.lockKey];uploaded.push({lockKey:fn.lockKey,remoteId:entry?.remoteId??0})}catch(error){const conflict=remoteVersionChangedConflict(fn,lockEntry,error);if(conflict){conflicts.push(conflict);continue}failed.push({lockKey:fn.lockKey,error:error instanceof Error?error.message:String(error)})}}nextAppLock.lastSync=(new Date).toISOString();await writeBffLockFile(config.lockFilePath,nextLockData);await waitForUploadedLockEntries(config.lockFilePath,ctx.appCode,uploaded.map(item=>item.lockKey));let cacheClear={attempted:false,cleared:false};if(uploaded.length>0){try{
|
|
7
|
+
let message="";for(let attempt=0;attempt<CACHE_CLEAR_ATTEMPTS;attempt+=1){message=await clearBffScriptCache();if(attempt<CACHE_CLEAR_ATTEMPTS-1){await sleep(CACHE_CLEAR_INTERVAL_MS)}}cacheClear={attempted:true,cleared:true,message:message||"Runtime script cache cleared."}}catch(error){cacheClear={attempted:true,cleared:false,error:error instanceof Error?error.message:String(error)}}}const primarySucceeded=failed.length===0&&(cacheClear.attempted?cacheClear.cleared:true);const ok=primarySucceeded;const cacheMessage=cacheClear.attempted?cacheClear.cleared?"runtime cache cleared":"runtime cache clear failed":"runtime cache not needed";return{ok:ok,data:{uploaded:uploaded,skipped:skipped,conflicts:conflicts,failed:failed,cacheClear:cacheClear,warnings:[...[...hookMaps.resolutions.values()].flatMap(item=>item.warnings),...[...hookMaps.existingHooks].map(existingHookWarning)]},message:formatPushMessage(uploaded.length,skipped.length,conflicts.length,failed.length,cacheMessage)}}}
|
|
8
|
+
;function missingRemoteVersionConflict(fn,lockEntry){return remoteVersionConflict(fn,lockEntry,"BFF_REMOTE_VERSION_MISSING","The local sync lock has no remote version for this script.")}function remoteVersionChangedConflict(fn,lockEntry,error){if(!lockEntry?.remoteId||lockEntry.version==null||!isRemoteVersionConflict(error)){return undefined}return remoteVersionConflict(fn,lockEntry,"BFF_REMOTE_VERSION_CHANGED","Remote script version changed since the last pull.")}function remoteVersionConflict(fn,lockEntry,code,message){return{code:code,lockKey:fn.lockKey,filePath:fn.filePath,remoteId:lockEntry.remoteId,...lockEntry.version!=null?{expectedVersion:lockEntry.version}:{},message:message,nextAction:{action:"review_remote_and_merge",command:`${CLI_BIN_NAME} bff detail --id ${lockEntry.remoteId} --format compress`,requiresReview:true,message:"Review the current remote source, merge it into the local script, then retry push. Do not use --force unless you intentionally discard local changes."
|
|
9
|
+
}}}function isRemoteVersionConflict(error){const message=error instanceof Error?error.message:String(error);const remoteCode=getPlatformErrorCode(error)??"";return[message,remoteCode].some(value=>/(?:version|optimistic)[\s_-]*(?:conflict|mismatch|changed|stale|out[\s_-]*of[\s_-]*date)|(?:conflict|mismatch|changed|stale|out[\s_-]*of[\s_-]*date)[\s_-]*(?:version|optimistic)/i.test(value))}function formatPushMessage(uploaded,skipped,conflicts,failed,cacheMessage){const parts=[`Push complete: ${uploaded} uploaded`,`${skipped} skipped`];if(conflicts>0){parts.push(`${conflicts} conflict${conflicts===1?"":"s"} ${conflicts===1?"requires":"require"} resolution`)}if(failed>0)parts.push(`${failed} failed`);parts.push(cacheMessage);return parts.join(", ")}async function getTargetFunctions(config,ctx){const typeFlag=ctx.str("type");const nameFlag=ctx.str("name");const filterType=normalizeBffType(typeFlag)??undefined;if(nameFlag&&!filterType){
|
|
10
|
+
throw CliErrors.validation("--name requires --type to identify the function.")}const allFunctions=await scanLocalBffFunctions(config,filterType);if(nameFlag){const matches=allFunctions.filter(fn=>fn.name===nameFlag);if(matches.length===0){throw CliErrors.validation(`Local function not found: ${filterType}/${nameFlag}`)}return matches}return allFunctions}function existingHookWarning(lockKey){return{code:"EXISTING_HOOK_BINDING_PRESERVED",lockKey:lockKey,message:"Dataset metadata is unavailable; the existing script and binding were verified. Update by script ID without rebinding."}}async function buildHookMaps(appCode,apiDir,localFunctions,appLock,selectedAppName){const hasHooks=localFunctions.some(fn=>fn.type==="HOOK");if(!hasHooks)return{resolutions:new Map,failures:new Map,existingHooks:new Set};const source=resolveApiModelSource(apiDir,appCode,selectedAppName);const aliasEntries=loadAliasMap(apiDir,undefined,source.filePath,source.profileName)
|
|
11
|
+
;assertUnambiguousHookAliases(aliasEntries);const aliasToDatasetCode=[...aliasEntries.map(entry=>[entry.alias,entry.datasetCode]),...trackedHookDirectoryMappings(appLock).map(entry=>[entry.alias,entry.datasetCode])];const datasets=await listDatasets(appCode);assertUnambiguousHookDirectoryMappings(aliasToDatasetCode.map(([alias,datasetCode])=>({alias:alias,datasetCode:datasetCode})));const indexes=buildHookDirectoryIndexes(datasets,aliasToDatasetCode);const failures=new Map;const resolutions=preflightPushHookDirectories(localFunctions,appLock,indexes,failures);const existingHooks=new Set;const candidates=localFunctions.filter(fn=>failures.get(fn.lockKey)?.startsWith("HOOK_DATASET_NOT_FOUND:")&&appLock.functions[fn.lockKey]?.remoteId&&appLock.functions[fn.lockKey]?.datasetCode);if(candidates.length>0){let statistics;try{statistics=await getBffScriptStatistics(appCode)}catch(error){
|
|
12
|
+
for(const fn of candidates)failures.set(fn.lockKey,`Cannot verify existing HOOK binding: ${error instanceof Error?error.message:String(error)}`);return{resolutions:resolutions,failures:failures,existingHooks:existingHooks}}for(const fn of candidates){const entry=appLock.functions[fn.lockKey];try{const directories=new Set(localFunctions.filter(item=>item.type==="HOOK"&&appLock.functions[item.lockKey]?.datasetCode===entry.datasetCode).map(item=>item.alias));if(directories.size>1){throw CliErrors.validation("Multiple HOOK directories reference the same missing Dataset. Resolve duplicate directories before pushing.")}const bindings=statistics.flatMap(item=>[{datasetCode:item.datasetCode,operationType:snakeToCamel(item.operationType),functionNode:"before",id:item.beforeScriptId},{datasetCode:item.datasetCode,operationType:snakeToCamel(item.operationType),functionNode:"after",id:item.afterScriptId}]).filter(item=>item.id===entry.remoteId);const remote=await getBffScriptInfo(entry.remoteId)
|
|
13
|
+
;if(remote.id!==entry.remoteId||remote.appCode!==appCode||remote.scriptType!=="HOOK"||remote.functionName!==fn.name||entry.version==null||remote.version!==entry.version||bindings.length!==1||bindings[0].datasetCode!==entry.datasetCode||bindings[0].operationType!==fn.operationType||bindings[0].functionNode!==fn.functionNode||entry.operationType!==fn.operationType||entry.functionNode!==fn.functionNode){throw CliErrors.validation("Existing HOOK identity, version or binding does not match the local lock. Pull and review before pushing.")}existingHooks.add(fn.lockKey);failures.delete(fn.lockKey)}catch(error){failures.set(fn.lockKey,error instanceof Error?error.message:String(error))}}}return{resolutions:resolutions,failures:failures,existingHooks:existingHooks}}async function uploadSingleFunction(appCode,fn,appLock,hookMaps){const sourceCode=await readFile(fn.filePath,"utf8");const hash=await computeFileHash(fn.filePath);const lockEntry=appLock.functions[fn.lockKey]
|
|
14
|
+
;if(lockEntry?.remoteId&&lockEntry.version==null){throw CliErrors.validation(`${fn.lockKey}: missing remote version. Run \`push\` after \`pull\` to sync version info.`)}let descriptionToSend=extractScriptDescription(sourceCode);if(!descriptionToSend&&lockEntry?.remoteId){const remote=await getBffScriptInfo(lockEntry.remoteId);descriptionToSend=remote.description||undefined}const payload={appCode:appCode,functionName:fn.name,scriptType:fn.type,scriptContent:sourceCode};if(lockEntry?.remoteId)payload["id"]=lockEntry.remoteId;if(lockEntry?.version!=null)payload["version"]=lockEntry.version;if(descriptionToSend)payload["description"]=descriptionToSend;if(fn.type==="HOOK"){const hook=hookMaps.resolutions.get(fn.lockKey);if(!hook&&!hookMaps.existingHooks.has(fn.lockKey)||!fn.operationType||!fn.functionNode){throw CliErrors.validation(`Incomplete HOOK path: ${fn.lockKey}`)}if(hook){payload["datasetId"]=hook.dataset.id;payload["operationType"]=fn.operationType}
|
|
15
|
+
payload["functionNode"]=fn.functionNode}const saved=await saveBffScript(payload);const remoteId=saved.id;const latestScript=saved.script??await getBffScriptInfo(remoteId);const nextEntry={hash:hash,remoteId:remoteId,version:latestScript.version};if(fn.type==="HOOK"){const hook=hookMaps.resolutions.get(fn.lockKey);if(!hook){appLock.functions[fn.lockKey]={...lockEntry,...nextEntry};return}nextEntry.alias=hook.alias??lockEntry?.alias;nextEntry.datasetCode=hook.datasetCode;nextEntry.operationType=fn.operationType;nextEntry.functionNode=fn.functionNode}appLock.functions[fn.lockKey]=nextEntry}const LOCK_SETTLE_RETRY_COUNT=20;const LOCK_SETTLE_DELAY_MS=100;async function waitForUploadedLockEntries(lockFilePath,appCode,lockKeys){if(lockKeys.length===0)return;for(let i=0;i<LOCK_SETTLE_RETRY_COUNT;i+=1){const latestLock=await readBffLockFile(lockFilePath);const functions=latestLock?.apps?.[appCode]?.functions??{};const allPresent=lockKeys.every(lockKey=>!!functions[lockKey]?.remoteId)
|
|
16
|
+
;if(allPresent)return;await sleep(LOCK_SETTLE_DELAY_MS)}throw new Error(`Lock file not settled after push for ${lockKeys.join(", ")}.`)}
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import{listBffScripts,getBffScriptStatistics}from"../../core/api-client.js";import{loadAliasMap}from"../../core/alias-resolver.js";import{resolveApiModelSource}from"../../api/model-source.js";import{loadBffProjectConfig}from"../../core/bff/config.js";import{createHookLocationMap,resolveRemoteScriptTarget,scanLocalBffFunctions}from"../../core/bff/file-system.js";import{computeFileHash}from"../../core/bff/hash.js";import{createEmptyBffLock,ensureLockScope,readBffLockFile}from"../../core/bff/lock.js";export const bffStatus={service:"bff",command:"status",description:"Check local Backend Function sync status against lock file",risk:"read",flags:[{name:"remote",type:"boolean",description:"Also check for remote-only scripts not present locally"}],async execute(ctx){const config=loadBffProjectConfig(ctx.appCode);const rawLock=await readBffLockFile(config.lockFilePath);const{appLock:appLock}=ensureLockScope(rawLock??createEmptyBffLock(),ctx.appCode,config.scriptsRoot,"status")
|
|
2
|
+
;const localFunctions=await scanLocalBffFunctions(config);const added=[];const modified=[];const unchanged=[];for(const fn of localFunctions){const localHash=await computeFileHash(fn.filePath);const lockEntry=appLock.functions[fn.lockKey];if(!lockEntry){added.push(fn.lockKey)}else if(lockEntry.hash!==localHash){modified.push(fn.lockKey)}else{unchanged.push(fn.lockKey)}}const remoteOnly=[];if(ctx.bool("remote")){const source=resolveApiModelSource(ctx.apiDir,ctx.appCode,ctx.selectedAppName||ctx.mergedCli?.currentApp||ctx.mergedCli?.defaultApp);const aliasEntries=loadAliasMap(ctx.apiDir,undefined,source.filePath,source.profileName);const datasetCodeToAlias=new Map(aliasEntries.map(e=>[e.datasetCode,e.alias]));const[scripts,statistics]=await Promise.all([listBffScripts(ctx.appCode),getBffScriptStatistics(ctx.appCode)]);const hookLocationMap=createHookLocationMap(statistics);const localKeys=new Set(localFunctions.map(fn=>fn.lockKey));for(const script of scripts){
|
|
3
|
+
const target=resolveRemoteScriptTarget(config,script,hookLocationMap,appLock.functions,datasetCodeToAlias);if(target&&!localKeys.has(target.lockKey)){remoteOnly.push(target.lockKey)}}}const synced=added.length===0&&modified.length===0&&remoteOnly.length===0;return{ok:true,data:{added:added,modified:modified,unchanged:unchanged,remoteOnly:remoteOnly},message:synced?"All Backend Function scripts are in sync.":`${added.length} added, ${modified.length} modified, ${unchanged.length} unchanged`+(remoteOnly.length>0?`, ${remoteOnly.length} remote-only`:"")}}};
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{CliErrors}from"../../errors.js";import{installBuiltinSkill}from"../../skills/builtin-skill.js";import{logger}from"../../utils/logger.js";export const cliSkillDefinitions=[{service:"cli-skill",command:"install",description:"Install or refresh the Rabetbase CLI Built-in Skill",risk:"read",requiresAuth:false,requiresAppCode:false,hasFormat:false,flags:[],async execute(ctx){logger.setLogPath(process.cwd());logger.info("cli-skill-install","Installing CLI Built-in Skill from the current package.");const result=installBuiltinSkill({stdio:ctx.nonInteractive?"pipe":"inherit"});if(!result.ok){throw CliErrors.apiError(`Built-in Skill install failed [${result.code}]: ${result.error||"unknown"}`,`Resolve the Skills CLI installation issue and run: ${result.repairCommand}`)}
|
|
2
|
+
console.log(result.changed?`CLI Built-in Skill ${result.skillVersion} installed${result.installedPath?` at ${result.installedPath}`:" via local skills installer"}`:`CLI Built-in Skill ${result.skillVersion} is already current${result.installedPath?` at ${result.installedPath}`:""}`);return{ok:true}}}];
|
|
@@ -1 +1,7 @@
|
|
|
1
|
-
const a47_0x1a2b28=a47_0x4578;(function(_0x4dec69,_0x48492a){const _0xc9318=a47_0x4578,_0x57c875=_0x4dec69();while(!![]){try{const _0x4cd3d4=parseInt(_0xc9318(0x11b))/0x1+-parseInt(_0xc9318(0x148))/0x2+parseInt(_0xc9318(0x10b))/0x3+parseInt(_0xc9318(0x13f))/0x4+parseInt(_0xc9318(0x135))/0x5+parseInt(_0xc9318(0x115))/0x6*(parseInt(_0xc9318(0x105))/0x7)+parseInt(_0xc9318(0x117))/0x8*(-parseInt(_0xc9318(0x140))/0x9);if(_0x4cd3d4===_0x48492a)break;else _0x57c875['push'](_0x57c875['shift']());}catch(_0x572e65){_0x57c875['push'](_0x57c875['shift']());}}}(a47_0x143b,0xa6a99));import a47_0x40414c from'chalk';import a47_0x10471f from'ora';import a47_0x503a18 from'semver';import{execa}from'execa';import{CLI_BIN_NAME,NPM_PACKAGE_NAME}from'../constant/cli.js';import{VERSION,GIT_COMMIT,BUILD_TIME}from'../generated/build-info.js';import{CliErrors}from'../errors.js';import{inspectInstalledBuiltinSkillVersion,installBuiltinSkill}from'../skills/builtin-skill.js';import{resolveNpmBin}from'../utils/platform.js';function a47_0x143b(){const _0x204649=['\x20doctor','error','source','3297534OdejZu','toLowerCase','2565256QqTNTJ','CLI\x20updated\x20to\x20v','read','valid','13827JDAJLs','str','--beta\x20and\x20--version\x20cannot\x20be\x20used\x20together.','current','bool','green','state','repairCommand','validation','Current\x20version\x20v','Update\x20available:\x20','expected\x20','includes','Unable\x20to\x20resolve\x20beta\x20version\x20from\x20npm','Requested\x20version:\x20','/dist-tags','Try\x20manually:\x20',',\x20state\x20','\x20install\x20-g\x20','message','skillVersion','start','succeed','trim','Version\x20comparison\x20failed','latest','247810JlBwbp','yellow','Use\x20a\x20full\x20semver\x20such\x20as\x202.1.6\x20or\x202.1.6-beta.1.','object','json','\x20\x20CLI\x20Built-in\x20Skill\x20','Unable\x20to\x20check\x20for\x20updates\x20(network\x20error)','filter','\x20\x20Restart\x20your\x20terminal\x20to\x20use\x20the\x20new\x20version.','slice','4245256FzsYjV','36sIdpRW','Updating\x20via\x20','log','Updated\x20to\x20v','string','Checking\x20CLI\x20Built-in\x20Skill...','version','unknown','2100064eHjCrJ','Run:\x20','execPath','fromEntries','npm','Install\x20the\x20version\x20from\x20npm\x20beta\x20dist-tag','CLI\x20Built-in\x20Skill\x20repair\x20failed\x20[','entries','\x20is\x20up\x20to\x20date.','\x20→\x20','beta','Update\x20failed:\x20','gray','14vUIXno','info','Update\x20rabetbase\x20CLI\x20to\x20the\x20latest\x20version','apiError','Beta\x20version:\x20','fail','2374284ONZvoY','Update\x20failed','Install\x20a\x20specific\x20CLI\x20version','https://registry.npmjs.org/-/package/','Try\x20manually:\x20npm\x20install\x20-g\x20',',\x20then\x20verify\x20with:\x20','bun'];a47_0x143b=function(){return _0x204649;};return a47_0x143b();}function getCurrentVersion(){const _0x42eaa3=a47_0x4578;return GIT_COMMIT!==_0x42eaa3(0x147)?VERSION+'\x20('+GIT_COMMIT+',\x20'+BUILD_TIME[_0x42eaa3(0x13e)](0x0,0xa)+')':VERSION;}function detectPackageManager(){const _0x8f58d7=a47_0x4578,_0xa4ccfa=process[_0x8f58d7(0x14a)][_0x8f58d7(0x116)]();if(_0xa4ccfa[_0x8f58d7(0x127)](_0x8f58d7(0x111)))return _0x8f58d7(0x111);return _0x8f58d7(0x14c);}const updateFlags=[{'name':'beta','type':'boolean','description':a47_0x1a2b28(0x14d),'default':![]},{'name':a47_0x1a2b28(0x146),'type':a47_0x1a2b28(0x144),'description':a47_0x1a2b28(0x10d)}];function getRequestedVersion(_0x59e010){const _0x454651=a47_0x1a2b28;return _0x59e010[_0x454651(0x11c)](_0x454651(0x146))['trim']();}async function validateUpdateFlags(_0x4df434){const _0x4e21d2=a47_0x1a2b28,_0x1b25a9=_0x4df434[_0x4e21d2(0x11f)](_0x4e21d2(0x152)),_0x3b21aa=getRequestedVersion(_0x4df434);if(_0x1b25a9&&_0x3b21aa)throw CliErrors[_0x4e21d2(0x123)](_0x4e21d2(0x11d),'Choose\x20either\x20npm\x20beta\x20dist-tag\x20or\x20an\x20exact\x20version.');if(_0x3b21aa&&!a47_0x503a18[_0x4e21d2(0x11a)](_0x3b21aa))throw CliErrors[_0x4e21d2(0x123)]('Invalid\x20version:\x20'+_0x3b21aa,_0x4e21d2(0x137));}async function fetchNpmDistTags(){const _0x3806d0=a47_0x1a2b28;try{const _0xefa68=await fetch(_0x3806d0(0x10e)+encodeURIComponent(NPM_PACKAGE_NAME)+_0x3806d0(0x12a),{'signal':AbortSignal['timeout'](0x2710)});if(!_0xefa68['ok'])return null;const _0x43f08b=await _0xefa68[_0x3806d0(0x139)]();if(!_0x43f08b||typeof _0x43f08b!==_0x3806d0(0x138))return null;return Object[_0x3806d0(0x14b)](Object[_0x3806d0(0x14f)](_0x43f08b)[_0x3806d0(0x13c)](([,_0x138201])=>typeof _0x138201===_0x3806d0(0x144)&&_0x138201[_0x3806d0(0x132)]()['length']>0x0)['map'](([_0x5329f9,_0x17d97c])=>[_0x5329f9,String(_0x17d97c)[_0x3806d0(0x132)]()]));}catch{return null;}}async function fetchNpmDistTagVersion(_0x52235d){const _0x340062=await fetchNpmDistTags();return _0x340062?.[_0x52235d]??null;}async function fetchLatestVersion(){const _0x53d089=a47_0x1a2b28;return fetchNpmDistTagVersion(_0x53d089(0x134));}async function resolveTargetVersion(_0x43a70e){const _0xd9fd2d=a47_0x1a2b28,_0x5e80dd=getRequestedVersion(_0x43a70e);if(_0x5e80dd)return{'version':_0x5e80dd,'source':'version'};if(_0x43a70e[_0xd9fd2d(0x11f)](_0xd9fd2d(0x152))){const _0x1782d3=await fetchNpmDistTagVersion(_0xd9fd2d(0x152));if(!_0x1782d3)return null;return{'version':_0x1782d3,'source':'beta'};}const _0x322242=await fetchLatestVersion();if(!_0x322242)return null;return{'version':_0x322242,'source':_0xd9fd2d(0x134)};}function shouldInstallTarget(_0x4e2608,_0x533a3d){const _0x52871c=a47_0x1a2b28;if(_0x533a3d[_0x52871c(0x114)]===_0x52871c(0x146)||_0x533a3d[_0x52871c(0x114)]===_0x52871c(0x152))return!a47_0x503a18['eq'](_0x4e2608,_0x533a3d[_0x52871c(0x146)]);return a47_0x503a18['lt'](_0x4e2608,_0x533a3d[_0x52871c(0x146)]);}function getInstallPlanLabel(_0x1c1ac7,_0x18f1d0){const _0x15d6e9=a47_0x1a2b28;switch(_0x18f1d0['source']){case _0x15d6e9(0x152):return _0x15d6e9(0x109)+a47_0x40414c[_0x15d6e9(0x136)](_0x1c1ac7)+_0x15d6e9(0x151)+a47_0x40414c['green'](_0x18f1d0['version']);case _0x15d6e9(0x146):return _0x15d6e9(0x129)+a47_0x40414c[_0x15d6e9(0x136)](_0x1c1ac7)+'\x20→\x20'+a47_0x40414c[_0x15d6e9(0x120)](_0x18f1d0[_0x15d6e9(0x146)]);case _0x15d6e9(0x134):default:return _0x15d6e9(0x125)+a47_0x40414c['yellow'](_0x1c1ac7)+_0x15d6e9(0x151)+a47_0x40414c[_0x15d6e9(0x120)](_0x18f1d0['version']);}}function repairCurrentBuiltinSkill(){const _0x3cd13b=a47_0x1a2b28;console[_0x3cd13b(0x142)](a47_0x40414c['gray'](_0x3cd13b(0x145)));const _0xf22bdb=installBuiltinSkill();if(_0xf22bdb['ok']){console[_0x3cd13b(0x142)](a47_0x40414c['gray'](_0x3cd13b(0x13a)+_0xf22bdb[_0x3cd13b(0x12f)]+_0x3cd13b(0x150)));return;}throw CliErrors[_0x3cd13b(0x108)](_0x3cd13b(0x14e)+_0xf22bdb['code']+']:\x20'+(_0xf22bdb[_0x3cd13b(0x113)]||'unknown'),'Run:\x20'+_0xf22bdb['repairCommand']+',\x20then\x20verify\x20with:\x20'+CLI_BIN_NAME+_0x3cd13b(0x112));}function verifyUpdatedBuiltinSkill(_0x5eee59){const _0x2fabe2=a47_0x1a2b28,_0x2c3dfb=inspectInstalledBuiltinSkillVersion(_0x5eee59);if(_0x2c3dfb[_0x2fabe2(0x121)]===_0x2fabe2(0x11e)){console[_0x2fabe2(0x142)](a47_0x40414c[_0x2fabe2(0x104)]('\x20\x20CLI\x20Built-in\x20Skill\x20'+_0x5eee59+_0x2fabe2(0x150)));return;}const _0x245509=_0x2c3dfb['skillVersion']?_0x2fabe2(0x126)+_0x5eee59+',\x20found\x20'+_0x2c3dfb[_0x2fabe2(0x12f)]:_0x2fabe2(0x126)+_0x5eee59+_0x2fabe2(0x12c)+_0x2c3dfb[_0x2fabe2(0x121)];throw CliErrors[_0x2fabe2(0x108)](_0x2fabe2(0x118)+_0x5eee59+',\x20but\x20Built-in\x20Skill\x20verification\x20failed:\x20'+_0x245509,_0x2fabe2(0x149)+_0x2c3dfb[_0x2fabe2(0x122)]+_0x2fabe2(0x110)+CLI_BIN_NAME+_0x2fabe2(0x112));}async function execute(_0x1b8dd9){const _0x5595b9=a47_0x1a2b28;await validateUpdateFlags(_0x1b8dd9);const _0x5982bd=getCurrentVersion();console[_0x5595b9(0x142)]('Current\x20version:\x20'+_0x5982bd);const _0x31b4dd=a47_0x10471f('Checking\x20for\x20updates...')[_0x5595b9(0x130)](),_0x3d6fd1=await resolveTargetVersion(_0x1b8dd9);if(!_0x3d6fd1){const _0x30e70a=_0x1b8dd9[_0x5595b9(0x11f)]('beta')?_0x5595b9(0x128):_0x5595b9(0x13b);_0x31b4dd[_0x5595b9(0x10a)](_0x30e70a);throw CliErrors['apiError'](_0x30e70a,_0x5595b9(0x10f)+NPM_PACKAGE_NAME+'@'+(_0x1b8dd9[_0x5595b9(0x11f)](_0x5595b9(0x152))?'beta':_0x5595b9(0x134)));}const _0x530024=a47_0x503a18[_0x5595b9(0x11a)](VERSION),_0x18c890=a47_0x503a18[_0x5595b9(0x11a)](_0x3d6fd1[_0x5595b9(0x146)]);if(!_0x530024||!_0x18c890){_0x31b4dd['fail']('Version\x20comparison\x20failed');throw CliErrors[_0x5595b9(0x108)](_0x5595b9(0x133),'Check\x20the\x20CLI\x20and\x20npm\x20versions,\x20then\x20retry:\x20'+CLI_BIN_NAME+'\x20update\x20--version\x20<version>');}if(!shouldInstallTarget(_0x530024,_0x3d6fd1)){const _0x20e7e7=_0x3d6fd1[_0x5595b9(0x114)]==='version'?'Already\x20on\x20requested\x20version\x20(v'+_0x3d6fd1['version']+')':a47_0x503a18['gt'](_0x530024,_0x18c890)?_0x5595b9(0x124)+_0x5982bd+'\x20is\x20newer\x20than\x20npm\x20latest\x20v'+_0x3d6fd1[_0x5595b9(0x146)]:'Already\x20up\x20to\x20date\x20(v'+_0x3d6fd1['version']+')';return _0x31b4dd[_0x5595b9(0x131)](_0x20e7e7),repairCurrentBuiltinSkill(),{'ok':!![]};}_0x31b4dd[_0x5595b9(0x106)](getInstallPlanLabel(_0x5982bd,_0x3d6fd1));const _0x8e5865=detectPackageManager(),_0x42780d=_0x8e5865===_0x5595b9(0x14c)?resolveNpmBin(_0x5595b9(0x14c)):_0x8e5865,_0x55f543=a47_0x10471f(_0x5595b9(0x141)+_0x8e5865+'...')[_0x5595b9(0x130)]();try{await execa(_0x42780d,['install','-g',NPM_PACKAGE_NAME+'@'+_0x3d6fd1[_0x5595b9(0x146)]],{'stdio':'pipe'}),_0x55f543[_0x5595b9(0x131)](_0x5595b9(0x143)+_0x3d6fd1[_0x5595b9(0x146)]),console[_0x5595b9(0x142)](a47_0x40414c[_0x5595b9(0x104)](_0x5595b9(0x13d)));}catch(_0x1b2a10){_0x55f543[_0x5595b9(0x10a)](_0x5595b9(0x10c));throw CliErrors[_0x5595b9(0x108)](_0x5595b9(0x153)+(_0x1b2a10 instanceof Error?_0x1b2a10[_0x5595b9(0x12e)]:String(_0x1b2a10)),_0x5595b9(0x12b)+_0x8e5865+_0x5595b9(0x12d)+NPM_PACKAGE_NAME+'@'+_0x3d6fd1['version']);}return verifyUpdatedBuiltinSkill(_0x3d6fd1[_0x5595b9(0x146)]),{'ok':!![]};}function a47_0x4578(_0x476dfb,_0x254082){_0x476dfb=_0x476dfb-0x104;const _0x143b2e=a47_0x143b();let _0x457832=_0x143b2e[_0x476dfb];return _0x457832;}export const updateDefinition={'service':'update','command':'run','description':a47_0x1a2b28(0x107),'risk':a47_0x1a2b28(0x119),'requiresAuth':![],'requiresAppCode':![],'hasFormat':![],'flags':updateFlags,'validate':validateUpdateFlags,'execute':execute};
|
|
1
|
+
import chalk from"chalk";import ora from"ora";import semver from"semver";import{execa}from"execa";import{CLI_BIN_NAME,NPM_PACKAGE_NAME}from"../constant/cli.js";import{VERSION,GIT_COMMIT,BUILD_TIME}from"../generated/build-info.js";import{CliErrors}from"../errors.js";import{installBuiltinSkill}from"../skills/builtin-skill.js";import{installUpdatedBuiltinSkill}from"../skills/install-updated-skill.js";import{resolveNpmBin}from"../utils/platform.js";function getCurrentVersion(){return GIT_COMMIT!=="unknown"?`${VERSION} (${GIT_COMMIT}, ${BUILD_TIME.slice(0,10)})`:VERSION}function detectPackageManager(){const execPath=process.execPath.toLowerCase();if(execPath.includes("bun"))return"bun";return"npm"}const updateFlags=[{name:"beta",type:"boolean",description:"Install the version from npm beta dist-tag",default:false},{name:"version",type:"string",description:"Install a specific CLI version"}];function getRequestedVersion(ctx){return ctx.str("version").trim()}
|
|
2
|
+
async function validateUpdateFlags(ctx){const wantsBeta=ctx.bool("beta");const requestedVersion=getRequestedVersion(ctx);if(wantsBeta&&requestedVersion){throw CliErrors.validation("--beta and --version cannot be used together.","Choose either npm beta dist-tag or an exact version.")}if(requestedVersion&&!semver.valid(requestedVersion)){throw CliErrors.validation(`Invalid version: ${requestedVersion}`,"Use a full semver such as 2.1.6 or 2.1.6-beta.1.")}}async function fetchNpmDistTags(){try{const pm=detectPackageManager();const{stdout:stdout}=await execa(pm==="npm"?resolveNpmBin("npm"):pm,[pm==="npm"?"view":"info",NPM_PACKAGE_NAME,"dist-tags","--json","--global"],{timeout:1e4});const parsed=JSON.parse(stdout);const data=Array.isArray(parsed)&&parsed.length===1?parsed[0]:parsed;if(!data||typeof data!=="object"||Array.isArray(data))return null
|
|
3
|
+
;return Object.fromEntries(Object.entries(data).filter(([,value])=>typeof value==="string"&&value.trim().length>0).map(([key,value])=>[key,String(value).trim()]))}catch{return null}}async function fetchNpmDistTagVersion(tag){const tags=await fetchNpmDistTags();return tags?.[tag]??null}async function fetchLatestVersion(){return fetchNpmDistTagVersion("latest")}async function resolveTargetVersion(ctx){const requestedVersion=getRequestedVersion(ctx);if(requestedVersion){return{version:requestedVersion,source:"version"}}if(ctx.bool("beta")){const betaVersion=await fetchNpmDistTagVersion("beta");if(!betaVersion)return null;return{version:betaVersion,source:"beta"}}const latestVersion=await fetchLatestVersion();if(!latestVersion)return null;return{version:latestVersion,source:"latest"}}function shouldInstallTarget(currentVersion,target){if(target.source==="version"||target.source==="beta"){return!semver.eq(currentVersion,target.version)}return semver.lt(currentVersion,target.version)}
|
|
4
|
+
function getInstallPlanLabel(currentVersion,target){switch(target.source){case"beta":return`Beta version: ${chalk.yellow(currentVersion)} → ${chalk.green(target.version)}`;case"version":return`Requested version: ${chalk.yellow(currentVersion)} → ${chalk.green(target.version)}`;case"latest":default:return`Update available: ${chalk.yellow(currentVersion)} → ${chalk.green(target.version)}`}}function repairCurrentBuiltinSkill(){console.log(chalk.gray("Checking CLI Built-in Skill..."));const result=installBuiltinSkill();if(result.ok){console.log(chalk.gray(` CLI Built-in Skill ${result.skillVersion} is up to date.`));return}throw CliErrors.apiError(`CLI Built-in Skill repair failed [${result.code}]: ${result.error||"unknown"}`,`Run: ${result.repairCommand}, then verify with: ${CLI_BIN_NAME} doctor`)}async function execute(ctx){await validateUpdateFlags(ctx);const currentVersion=getCurrentVersion();console.log(`Current version: ${currentVersion}`)
|
|
5
|
+
;const spinner=ora("Checking for updates...").start();const target=await resolveTargetVersion(ctx);if(!target){const failureMessage=ctx.bool("beta")?"Unable to resolve beta version from npm":"Unable to check for updates (network error)";spinner.fail(failureMessage);throw CliErrors.apiError(failureMessage,`Try manually: npm install -g ${NPM_PACKAGE_NAME}@${ctx.bool("beta")?"beta":"latest"}`)}const currentSemver=semver.valid(VERSION);const targetSemver=semver.valid(target.version);if(!currentSemver||!targetSemver){spinner.fail("Version comparison failed");throw CliErrors.apiError("Version comparison failed",`Check the CLI and npm versions, then retry: ${CLI_BIN_NAME} update --version <version>`)}if(!shouldInstallTarget(currentSemver,target)){
|
|
6
|
+
const successMessage=target.source==="version"?`Already on requested version (v${target.version})`:semver.gt(currentSemver,targetSemver)?`Current version v${currentVersion} is newer than npm latest v${target.version}`:`Already up to date (v${target.version})`;repairCurrentBuiltinSkill();spinner.succeed(successMessage);return{ok:true}}spinner.info(getInstallPlanLabel(currentVersion,target));const pm=detectPackageManager();const pmCmd=pm==="npm"?resolveNpmBin("npm"):pm;const installSpinner=ora(`Updating via ${pm}...`).start();try{await execa(pmCmd,["install","-g",`${NPM_PACKAGE_NAME}@${target.version}`],{stdio:"pipe"})}catch(err){installSpinner.fail("Update failed");throw CliErrors.apiError(`Update failed: ${err instanceof Error?err.message:String(err)}`,`Try manually: ${pm} install -g ${NPM_PACKAGE_NAME}@${target.version}`)}try{installUpdatedBuiltinSkill({version:target.version,packageManager:pm,packageManagerCommand:pmCmd})}catch(error){
|
|
7
|
+
installSpinner.fail("CLI installed, but Built-in Skill installation failed");throw CliErrors.apiError(`CLI updated to v${target.version}, but Built-in Skill installation failed: ${error instanceof Error?error.message:String(error)}`,`Run: ${CLI_BIN_NAME} cli-skill install, then verify with: ${CLI_BIN_NAME} doctor`)}installSpinner.succeed(`Updated CLI and Built-in Skill to v${target.version}`);console.log(chalk.gray(" Restart your terminal to use the new version."));return{ok:true}}export const updateDefinition={service:"update",command:"run",description:"Update rabetbase CLI to the latest version",risk:"read",requiresAuth:false,requiresAppCode:false,hasFormat:false,flags:updateFlags,validate:validateUpdateFlags,execute:execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{codegenSdk}from"../../commands/codegen/sdk.js";import{codegenSql}from"../../commands/codegen/sql.js";export const codegenDefinitions=[codegenSdk,codegenSql];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{getOperationDetail,generateSdkCode}from"../../core/api-client.js";import{CODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";export const codegenSdk={service:"codegen",command:"sdk",description:"Generate TypeScript SDK code for a dataset operation",risk:"read",flags:[CODE_FLAG_OPTIONAL,{name:"alias",type:"string",description:"Dataset alias defined in api.ts (e.g. order, coupon)"},{name:"operation",type:"string",required:true,description:"Operation name (e.g. filter, getOne, create, update)"},{name:"skip-imports",type:"boolean",description:"Omit import statements from generated code"}],async execute(ctx){const{dataset:dataset,operation:operation}=await getOperationDetail(ctx.appCode,ctx.str("code"),ctx.str("operation"));const code=generateSdkCode(dataset,operation,{includeImports:!ctx.bool("skip-imports")});return{ok:true,data:{dataset:{name:dataset.name,code:dataset.code,tableName:dataset.tableName},operation:ctx.str("operation"),code:code}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{getSqlQueryInfo,generateSqlCodeTemplate}from"../../core/api-client.js";import{SQLCODE_FLAG}from"../../commands/common/flags.js";export const codegenSql={service:"codegen",command:"sql",description:"Generate TypeScript code for a custom SQL query",risk:"read",flags:[SQLCODE_FLAG,{name:"target",type:"string",description:"Code target: sdk (default) or bff",default:"sdk",enum:["sdk","bff"]},{name:"no-imports",type:"boolean",description:"Omit import statements from generated code"}],async execute(ctx){const sql=await getSqlQueryInfo(ctx.appCode,ctx.str("sqlcode"));const target=ctx.str("target")||"sdk";const code=generateSqlCodeTemplate(sql,{target:target,includeImports:!ctx.bool("no-imports")});return{ok:true,data:{sqlCode:sql.sqlCode,sqlName:sql.sqlName,target:target,code:code}}}};
|
|
@@ -1 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import{CliErrors}from"../../errors.js";import{CLI_BIN_NAME}from"../../constant/cli.js";import{collectAppProfileOverrides,getAppProfileFlagDefs,normalizeStoredDefaultApp}from"../../config/schema.js";import{readRawConfigWithLayers}from"../../context.js";import{readConfig,writeConfig,scopeLabel,resolveAppScopeForWrite,appDefinedIn}from"../../commands/app/shared.js";export function buildAppAddFlags(){return[{name:"appcode",type:"string",description:"App code",required:true},{name:"global",type:"boolean",description:"Use global config scope",default:false},...getAppProfileFlagDefs()]}export function buildAppRemoveFlags(){return[{name:"global",type:"boolean",description:"Use global config scope",default:false}]}export async function validateAppName(ctx,usageCmd){const name=ctx.args[0]?.trim();if(!name){throw CliErrors.validation("Missing app name.",`Usage: ${CLI_BIN_NAME} ${usageCmd} <name>`)}}export async function runAppAdd(ctx,usageCmd){const name=ctx.args[0]?.trim();if(!name){
|
|
2
|
+
throw CliErrors.validation("Missing app name.",`Usage: ${CLI_BIN_NAME} ${usageCmd} <name> --appcode <code>`)}const appcode=ctx.str("appcode");if(!appcode){throw CliErrors.flagMissing("appcode",`Usage: ${CLI_BIN_NAME} ${usageCmd} <name> --appcode <code>`)}const flags={global:ctx.bool("global")};const config=readConfig(flags);if(!config.apps)config.apps={};const profile={appcode:appcode,...collectAppProfileOverrides(flagName=>ctx.str(flagName))};const apps=config.apps;const previousNames=Object.keys(apps);const previousSelection=typeof config.defaultApp==="string"&&apps[config.defaultApp]?config.defaultApp:previousNames.length===1?previousNames[0]:undefined;const isUpdate=!!apps[name];apps[name]=profile;const storedDefault=normalizeStoredDefaultApp(config,previousSelection);writeConfig(config,flags);const extraMsg=!isUpdate&&storedDefault?` Default app is "${storedDefault}".`:""
|
|
3
|
+
;const mainMsg=`${isUpdate?"Updated":"Added"} app "${name}" (appcode: ${appcode})${scopeLabel(flags)}.${extraMsg}`;return{ok:true,message:mainMsg}}export async function runAppRemove(ctx,usageCmd){const name=ctx.args[0]?.trim();if(!name){throw CliErrors.validation("Missing app name.",`Usage: ${CLI_BIN_NAME} ${usageCmd} <name> [--global]`)}const explicitGlobal=ctx.bool("global");const{config:merged,layers:layers}=readRawConfigWithLayers();const mergedApps=merged.apps??{};if(!mergedApps[name]){throw CliErrors.validation(`App "${name}" not found.`)}const globalApps=layers.globalConfig.apps&&typeof layers.globalConfig.apps==="object"?layers.globalConfig.apps:{};const projectApps=layers.projectConfig.apps&&typeof layers.projectConfig.apps==="object"?layers.projectConfig.apps:{};const definedIn=appDefinedIn(name,globalApps,projectApps);const scope=resolveAppScopeForWrite(name,explicitGlobal,layers);const targetFlags={global:scope==="global"};const config=readConfig(targetFlags)
|
|
4
|
+
;const apps=config.apps;if(!apps||!apps[name]){throw CliErrors.validation(`App "${name}" not found.`)}delete apps[name];let extraMsg="";const previousDefault=typeof config.defaultApp==="string"?config.defaultApp:undefined;const remaining=Object.keys(apps);const preferred=previousDefault===name?remaining[0]:previousDefault;const storedDefault=normalizeStoredDefaultApp(config,preferred);if(previousDefault===name&&remaining.length===1){extraMsg=` Remaining app "${remaining[0]}" is selected automatically.`}else if(previousDefault===name&&storedDefault){extraMsg=` Default app changed to "${storedDefault}".`}if(Object.keys(apps).length===0){delete config.apps;delete config.defaultApp}writeConfig(config,targetFlags);const stillExistsNote=definedIn==="both"?` Note: app "${name}" still defined in ${scope==="project"?"global":"project"} config.`:"";return{ok:true,message:`Removed app "${name}"${scopeLabel(targetFlags)}.${extraMsg}${stillExistsNote}`}}
|
|
@@ -1 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import{input,checkbox,select}from"@inquirer/prompts";import chalk from"chalk";import{validateAppcode}from"../../commands/common/validate.js";import{listRemoteApps}from"../../core/api-client.js";import{withActiveCookie}from"../../utils/with-active-cookie.js";import{writeCliSideChannelLine}from"../../utils/write-cli-side-channel.js";export async function promptCustomAppcode(){const code=await input({message:"App Code:",validate:value=>{const v=validateAppcode(value.trim());return v.valid||v.message||"Invalid App Code"}});return code.trim()}export async function promptAppSelection(apps){const choices=[{name:chalk.yellow("✎ Enter appcode manually"),value:-1},...apps.map((app,i)=>({name:`${app.appName} ${chalk.gray(`(${app.appCode})`)}`,value:i}))];const selected=await checkbox({message:`Found ${chalk.cyan(apps.length)} apps. Select with space, a=all, i=invert:`,choices:choices,loop:false});if(selected.includes(-1))return"custom";if(selected.length===0)return"custom"
|
|
2
|
+
;return selected.map(i=>apps[i])}export async function promptSingleAppSelection(apps){const choices=[{name:chalk.gray("(Skip; configure later with config set appcode)"),value:"skip"},{name:chalk.yellow("✎ Enter appcode manually"),value:"custom"},...apps.map(app=>({name:`${app.appName} ${chalk.gray(`(${app.appCode})`)}`,value:app.appCode}))];const selected=await select({message:"Select the app to bind:",choices:choices});if(selected==="skip")return"skip";if(selected==="custom")return"custom";return apps.find(a=>a.appCode===selected)}export async function selectSingleAppcode(cookie){if(!cookie){writeCliSideChannelLine(chalk.gray("(No login session. Enter an App Code manually or skip.)"));return _fallbackOrSkip()}writeCliSideChannelLine("Fetching available apps...");let apps;try{apps=await withActiveCookie(cookie,()=>listRemoteApps())}catch(err){writeCliSideChannelLine(chalk.yellow("Could not fetch the remote app list. Enter an App Code manually."))
|
|
3
|
+
;if(err instanceof Error)writeCliSideChannelLine(chalk.gray(` (${err.message})`));return _fallbackOrSkip()}if(apps.length===0){writeCliSideChannelLine(chalk.yellow("No available apps found."));return _fallbackOrSkip()}const result=await promptSingleAppSelection(apps);if(result==="skip")return"";if(result==="custom")return promptCustomAppcode();return result.appCode}export async function selectMultipleApps(cookie){writeCliSideChannelLine("Fetching available apps...");let apps;try{apps=await withActiveCookie(cookie,()=>listRemoteApps())}catch(err){writeCliSideChannelLine("\nCould not fetch the remote app list. Enter an App Code manually.");if(err instanceof Error)writeCliSideChannelLine(` (${err.message})`);return"custom"}if(apps.length===0){writeCliSideChannelLine("\nNo available apps found.");return"custom"}return promptAppSelection(apps)}async function _fallbackOrSkip(){const choice=await select({message:"App Code:",choices:[{name:chalk.gray("(Skip; configure later)"),value:"skip"
|
|
4
|
+
},{name:chalk.yellow("✎ Enter manually"),value:"manual"}]});if(choice==="skip")return"";return promptCustomAppcode()}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{CLI_BIN_NAME}from"../../constant/cli.js";import{CliErrors}from"../../errors.js";const TERMINAL_STATUSES=new Set(["SUCCESS","FAILED"]);const NON_TERMINAL_STATUSES=new Set(["PENDING","PROCESSING"]);export function normalizeAsyncTask(task){const taskId=typeof task?.taskId==="string"?task.taskId.trim():"";if(!taskId){throw CliErrors.apiError("Async task response did not contain a taskId.")}const status=typeof task.status==="string"?task.status.trim().toUpperCase():"";if(!status){throw CliErrors.apiError(`Async task ${taskId} response did not contain a status.`)}return{taskId:taskId,status:status,errorMessage:typeof task.errorMessage==="string"&&task.errorMessage.trim()?task.errorMessage.trim():null,isTerminal:TERMINAL_STATUSES.has(status),knownStatus:TERMINAL_STATUSES.has(status)||NON_TERMINAL_STATUSES.has(status)}}export function buildAsyncTaskStatusCommand(taskId,appCode){
|
|
2
|
+
return`${CLI_BIN_NAME} task status --task-id ${quoteShellArg(taskId)} --appcode ${quoteShellArg(appCode)} --format compress`}export function asyncTaskMessage(task){switch(task.status){case"PENDING":return`Task ${task.taskId} is pending.`;case"PROCESSING":return`Task ${task.taskId} is processing.`;case"SUCCESS":return`Task ${task.taskId} completed successfully.`;case"FAILED":return task.errorMessage?`Task ${task.taskId} failed: ${task.errorMessage}`:`Task ${task.taskId} failed.`;default:return`Task ${task.taskId} returned unknown status ${task.status}.`}}function quoteShellArg(value){return`'${value.replace(/'/g,`'\\''`)}'`}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export function asDryRunResult(data,backend){return Object.defineProperties(data,{method:{value:backend.method,enumerable:false},url:{value:backend.url,enumerable:false},...backend.description?{description:{value:backend.description,enumerable:false}}:{}})}
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
export const CROSS_RELATION_FROM_DATASET_FLAG={name:"from-datasetcode",type:"string",required:true,description:"Source DB_TABLE dataset code"};export const CROSS_RELATION_FROM_COLUMN_FLAG={name:"from-column",type:"string",required:true,description:"Source field name used to locate the relation"};export const CROSS_RELATION_TO_DATASET_FLAG={name:"to-datasetcode",type:"string",required:true,description:"Target DB_TABLE dataset code"};export const CROSS_RELATION_TO_COLUMN_FLAG={name:"to-column",type:"string",required:true,description:"Target field name"};export const CROSS_RELATION_DBLINK_FLAG={name:"from-dblink-id",type:"number",description:"Source database connection ID; derived from the source dataset when omitted"};export const CROSS_RELATION_LABEL_FLAG={name:"to-label-column",type:"string",description:"Target display field; create defaults to the target field, update keeps the current value"};export const CROSS_RELATION_CARDINALITY_FLAG={name:"cardinality",type:"string",
|
|
2
|
+
enum:["ONE_TO_ONE","ONE_TO_MANY","MANY_TO_ONE","MANY_TO_MANY"],description:"Relation cardinality; create leaves it unset when omitted, update keeps the current value"};export const GLOBAL_SCOPE_FLAG={name:"global",type:"boolean",default:false,description:"Write to the global configuration"};export const DATASET_CODE_PATTERN={regex:/^[a-f0-9]{32}(?:_[^_\s]+_[^_\s]+)?$/i,description:"a 32-character hex code, optionally with `_xx_xx` suffix (e.g. 99a909313f1fa7153186431e1c551588 or 99a909313f1fa7153186431e1c551588_75_3c7120aa)"};export const CODE_FLAG={name:"code",type:"string",required:true,description:"Dataset code (32-char hex, optionally with _xx_xx suffix)",pattern:DATASET_CODE_PATTERN};export const CODE_FLAG_OPTIONAL={...CODE_FLAG,required:false};export const DATASETCODE_FLAG_OPTIONAL={...CODE_FLAG_OPTIONAL,name:"datasetcode",description:"Dataset code (32-char hex, optionally with _xx_xx suffix)"};export const SQLCODE_FLAG={name:"sqlcode",type:"string",required:true,
|
|
3
|
+
description:"SQL code identifier (format: xxxxxxxx-xxxxxxxx, e.g. 2305f915-dd48cd4c)",pattern:{regex:/^[a-f0-9]{8}-[a-f0-9]{8}$/i,description:"SQL code in format xxxxxxxx-xxxxxxxx (e.g. 2305f915-dd48cd4c)"}};export const APPCODE_FLAG_OPTIONAL={name:"appcode",type:"string",required:false,description:"App code (overrides config file, e.g. app-xxxxx)"};export const APPCODE_FLAG={...APPCODE_FLAG_OPTIONAL,required:true,description:"App code (e.g. app-xxxxx)"};export const SQLCODE_FLAG_OPTIONAL={...SQLCODE_FLAG,required:false};export const DBLINK_ID_FLAG={name:"id",type:"number",required:true,description:"Database connection ID (dblink id from db list)"};export const DB_TYPE_FLAG={name:"dbtype",type:"string",required:true,description:"Database product type",enum:["MYSQL","POSTGRESQL"]};export const SKIP_CONNECTION_TEST_FLAG={name:"skip-connection-test",type:"boolean",description:"Skip testing the unsaved database configuration before create/update"};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{existsSync,statSync}from"node:fs";import{CliErrors}from"../../errors.js";const BYTES_PER_MB=1024*1024;export const DEVELOPMENT_UPLOAD_MAX_BYTES=50*BYTES_PER_MB;function formatBytes(bytes){if(bytes>=BYTES_PER_MB){const megabytes=Math.ceil(bytes/BYTES_PER_MB*100)/100;return`${megabytes.toFixed(2)} MB`}return`${bytes} B`}export function requireDevelopmentUploadFile(filePath,label){const normalized=filePath.trim();if(!normalized){throw CliErrors.validation(`${label} path is required.`)}if(!existsSync(normalized)){throw CliErrors.validation(`File not found: ${normalized}`)}const stats=statSync(normalized);if(!stats.isFile()){throw CliErrors.validation(`File is not a regular file: ${normalized}`)}if(stats.size>DEVELOPMENT_UPLOAD_MAX_BYTES){throw CliErrors.validation(`File exceeds the development upload limit of 50 MB: ${normalized} (${formatBytes(stats.size)})`)}return{path:normalized,size:stats.size}}
|