@lovrabet/rabetbase-cli 2.5.13-beta.1 → 2.6.0-beta.1
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
|
@@ -1 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import{createHash}from"node:crypto";import{readFile,stat}from"node:fs/promises";import{resolve}from"node:path";import{TextDecoder}from"node:util";import{CliError}from"../../errors.js";export const APP_RULE_TYPES=["rules","database"];export const MAX_APP_RULE_UNITS=5*1024*1024;export const MAX_APP_RULE_BYTES=MAX_APP_RULE_UNITS*4;const APP_RULE_FILES={rules:"RULES.md",database:"DATABASE.md"};const APP_RULE_CONTEXT_SCOPES={rules:"page-api-development",database:"database-analysis"};export function appRuleError(code,message,hint){return new CliError(code,1,message,hint)}export function readAppRuleType(ctx){const value=ctx.str("type").trim().toLowerCase();if(value!=="rules"&&value!=="database"){throw appRuleError("app_rule_type_invalid","--type must be either rules or database.")}return value}export function appRuleFileName(type){return APP_RULE_FILES[type]}export function appRuleContextScope(type){return APP_RULE_CONTEXT_SCOPES[type]}export function inspectAppRuleContent(content){
|
|
2
|
+
const bytes=Buffer.from(content,"utf8");return{content:content,byteSize:bytes.byteLength,contentHash:`sha256:${createHash("sha256").update(bytes).digest("hex")}`}}export async function readAppRuleFile(filePath){const normalizedPath=filePath.trim();if(!normalizedPath){throw appRuleError("app_rule_file_required","--file is required.","Pass a UTF-8 Markdown file.")}const absolutePath=resolve(normalizedPath);let fileStat;try{fileStat=await stat(absolutePath)}catch(error){throw appRuleError("app_rule_file_unreadable",`Cannot access app rule file: ${normalizedPath}`,error instanceof Error?error.message:String(error))}if(!fileStat.isFile()){throw appRuleError("app_rule_file_invalid",`App rule path is not a regular file: ${normalizedPath}`)}if(fileStat.size>MAX_APP_RULE_BYTES){throw appRuleError("app_rule_content_too_large","App rule content exceeds the bounded UTF-8 file limit.")}let bytes;try{bytes=await readFile(absolutePath)}catch(error){
|
|
3
|
+
throw appRuleError("app_rule_file_unreadable",`Cannot read app rule file: ${normalizedPath}`,error instanceof Error?error.message:String(error))}if(bytes.byteLength>MAX_APP_RULE_BYTES){throw appRuleError("app_rule_content_too_large","App rule content exceeds the bounded UTF-8 file limit.")}let content;try{content=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(bytes)}catch{throw appRuleError("app_rule_content_invalid",`App rule file is not valid UTF-8: ${normalizedPath}`)}if(content.length>MAX_APP_RULE_UNITS){throw appRuleError("app_rule_content_too_large","App rule content exceeds 5242880 UTF-16 units.")}if(!content.trim()){throw appRuleError("app_rule_content_invalid",`App rule file is blank: ${normalizedPath}`)}return inspectAppRuleContent(content)}export function projectAppRule(type,record){if(!record){return{type:type,fileName:appRuleFileName(type),contextScope:appRuleContextScope(type),enabled:false}}const content=inspectAppRuleContent(record.content);return{
|
|
4
|
+
type:type,fileName:appRuleFileName(type),contextScope:appRuleContextScope(type),enabled:true,id:record.id,scope:record.scope,appCode:record.appCode,version:record.version,...record.indexStatus!==undefined?{indexStatus:record.indexStatus}:{},contentByteSize:content.byteSize,contentHash:content.contentHash,...record.createTime!==undefined&&record.createTime!==null?{createTime:record.createTime}:{},...record.updateTime!==undefined&&record.updateTime!==null?{updateTime:record.updateTime}:{}}}export const APP_RULE_TYPE_FLAG={name:"type",type:"string",required:true,description:"Context rule type: rules for page/API development agents (DB Agent excluded), database for DB Agent database analysis",enum:[...APP_RULE_TYPES]};
|
|
@@ -1 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import{readFileSync,existsSync}from"node:fs";import{CLI_BIN_NAME}from"../../constant/cli.js";import{resolve,delimiter,join}from"node:path";import{spawn}from"node:child_process";import{CliErrors}from"../../errors.js";import{findProjectRootDirectory,resolveConfigPath}from"../../context/config-loader.js";import{writeProjectDomainRoutingManifest}from"../../config/project-domain-routing.js";import{checkSdkVersion,printSdkUpgradeWarning}from"../../utils/check-sdk-version.js";import{assertCliVersionSupported,checkCliVersion,printCliUpgradeWarning}from"../../utils/cli-version-check.js";const VERSION_CHECK_SCRIPTS=new Set(["start","dev"]);const DOMAIN_ROUTING_SYNC_SCRIPTS=new Set(["start","dev","build","preview"]);export function syncProjectDomainRoutingBeforeScript(cwd,scriptName){if(!DOMAIN_ROUTING_SYNC_SCRIPTS.has(scriptName))return null;const projectRoot=findProjectRootDirectory(cwd);if(!resolveConfigPath(projectRoot))return null;const result=writeProjectDomainRoutingManifest(projectRoot)
|
|
2
|
+
;return{path:result.path,changed:result.changed}}function readPackageScripts(cwd){const pkgPath=resolve(cwd,"package.json");if(!existsSync(pkgPath))return null;try{const pkg=JSON.parse(readFileSync(pkgPath,"utf-8"));return pkg.scripts??{}}catch{return null}}function detectPackageManager(cwd){if(existsSync(resolve(cwd,"bun.lockb"))||existsSync(resolve(cwd,"bun.lock")))return"bun";if(existsSync(resolve(cwd,"pnpm-lock.yaml")))return"pnpm";if(existsSync(resolve(cwd,"yarn.lock")))return"yarn";return"npm"}async function versionCheck(cwd){const cliCheck=await checkCliVersion();if(cliCheck.needsUpgrade||cliCheck.belowMinimum){printCliUpgradeWarning(cliCheck);assertCliVersionSupported(cliCheck)}const sdkCheck=await checkSdkVersion(cwd);if(sdkCheck.needsUpgrade)printSdkUpgradeWarning(sdkCheck)}function spawnScript(pm,script,extraArgs,cwd){return new Promise((resolve,reject)=>{const args=["run",script,...extraArgs];const child=spawn(pm,args,{cwd:cwd,stdio:"inherit",shell:true,env:{...process.env,
|
|
3
|
+
PATH:`${join(cwd,"node_modules",".bin")}${delimiter}${process.env.PATH}`}});child.on("close",code=>{if(code===0||code===null)resolve();else reject(new Error(`${pm} run ${script} exited with code ${code}`))});child.on("error",reject)})}function spawnViteBuildWatch(cwd){return new Promise((resolve,reject)=>{const child=spawn("vite",["build","--watch"],{cwd:cwd,stdio:"inherit",shell:true,env:{...process.env,PATH:`${join(cwd,"node_modules",".bin")}${delimiter}${process.env.PATH}`}});child.on("close",code=>{if(code===0||code===null)resolve();else reject(new Error(`vite build --watch exited with code ${code}`))});child.on("error",reject)})}function spawnVitePreview(cwd){return new Promise((resolve,reject)=>{const child=spawn("vite",["preview"],{cwd:cwd,stdio:"inherit",shell:true,env:{...process.env,PATH:`${join(cwd,"node_modules",".bin")}${delimiter}${process.env.PATH}`}});child.on("close",code=>{
|
|
4
|
+
if(code===0||code===null)resolve();else reject(new Error(`vite preview exited with code ${code}`))});child.on("error",reject)})}const runFlags=[{name:"watch",type:"boolean",description:"Enable watch mode for preview",default:false}];export const runDefinition={service:"run",command:"run",description:"Run a package.json script",risk:"write",requiresAuth:false,requiresAppCode:false,hasFormat:false,args:[{name:"script",description:"Script name defined in package.json",required:false}],flags:runFlags,helpExtra:()=>{const lines=[];lines.push(` EXAMPLES`);lines.push(` ${CLI_BIN_NAME} run start`);lines.push(` ${CLI_BIN_NAME} run build`);lines.push(` ${CLI_BIN_NAME} run preview`);lines.push(` ${CLI_BIN_NAME} run preview --watch`);return lines.join("\n")},async execute(ctx){const cwd=process.cwd();const scriptName=ctx.args[0];const extraArgs=ctx.args.slice(1);const scripts=readPackageScripts(cwd);if(!scripts){throw CliErrors.validation("No package.json found in current directory.")
|
|
5
|
+
}if(!scriptName){const names=Object.keys(scripts);if(names.length===0){console.log("No scripts defined in package.json.")}else{console.log("\n Available scripts:\n");for(const name of names){console.log(` ${name}`)}console.log(`\n Usage: ${CLI_BIN_NAME} run <script>\n`)}return{ok:true}}if(!scripts[scriptName]){throw CliErrors.validation(`Script "${scriptName}" not found in package.json.`,`Available: ${Object.keys(scripts).join(", ")||"(none)"}`)}const pm=detectPackageManager(cwd);const routingSync=syncProjectDomainRoutingBeforeScript(cwd,scriptName);if(routingSync?.changed){console.error(`Domain routing synchronized: ${routingSync.path}`)}if(VERSION_CHECK_SCRIPTS.has(scriptName)){await versionCheck(cwd)}if(scriptName==="preview"&&ctx.bool("watch")){await Promise.all([spawnViteBuildWatch(cwd),spawnVitePreview(cwd)]);return{ok:true}}await spawnScript(pm,scriptName,extraArgs,cwd);return{ok:true}}};
|
package/lib/commands/schema.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{buildSchemaPayload}from"../framework/schema-export.js";async function execute(_ctx){const data=await buildSchemaPayload();return{ok:true,data:data}}export const schemaDefinition={service:"schema",command:"export",description:"Export machine-readable command schema (JSON)",risk:"read",requiresAuth:false,requiresAppCode:false,hasFormat:true,defaultOutputFormat:"json",flags:[],execute:execute};
|
|
@@ -1 +1,7 @@
|
|
|
1
|
-
const a247_0xb35f96=a247_0x3e63;(function(_0x4a8105,_0x3c5d7c){const _0x2a1894=a247_0x3e63,_0x2b89ed=_0x4a8105();while(!![]){try{const _0x33c79b=parseInt(_0x2a1894(0x1a1))/0x1*(-parseInt(_0x2a1894(0x17a))/0x2)+parseInt(_0x2a1894(0x18d))/0x3*(-parseInt(_0x2a1894(0x1a5))/0x4)+-parseInt(_0x2a1894(0x180))/0x5*(parseInt(_0x2a1894(0x174))/0x6)+-parseInt(_0x2a1894(0x19e))/0x7+parseInt(_0x2a1894(0x190))/0x8*(-parseInt(_0x2a1894(0x192))/0x9)+parseInt(_0x2a1894(0x198))/0xa*(parseInt(_0x2a1894(0x177))/0xb)+parseInt(_0x2a1894(0x1a4))/0xc*(parseInt(_0x2a1894(0x1a0))/0xd);if(_0x33c79b===_0x3c5d7c)break;else _0x2b89ed['push'](_0x2b89ed['shift']());}catch(_0xa03df3){_0x2b89ed['push'](_0x2b89ed['shift']());}}}(a247_0x427d,0xb0453));import{writeFile}from'node:fs/promises';import{input,select}from'@inquirer/prompts';import{createSqlQuery}from'../../core/api-client.js';function a247_0x3e63(_0x50839b,_0x5bb0ae){_0x50839b=_0x50839b-0x16d;const _0x427dbc=a247_0x427d();let _0x3e63f4=_0x427dbc[_0x50839b];return _0x3e63f4;}import{getDbName,listDatabases}from'../../core/db-resolver.js';import{loadSqlProjectConfig}from'../../core/sql-sync/config.js';import{ensureParentDirectory,fileExists}from'../../core/bff/file-system.js';import{computeSqlContentHash}from'../../core/sql-sync/hash.js';import{createEmptySqlLock,ensureSqlLockScope,readSqlLockFile,writeSqlLockFile}from'../../core/sql-sync/lock.js';import{buildSqlRelativePath}from'../../core/sql-sync/utils.js';import{CliErrors}from'../../errors.js';import{buildLocalSqlFileContent,buildSqlLockEntry,ensureRemoteSqlContent}from'./shared.js';function a247_0x427d(){const _0x383374=['464470gGsNbh','SQL\x20query\x20display\x20name','dbName','lastSync','nonInteractive','Plain\x20SQL\x20(sql)','6637519JMduwM','<select\x20id=\x22query\x22\x20resultType=\x22map\x22>','408694gVLOcz','10174ptewCv','Created\x20SQL\x20query\x20','\x20\x20SELECT\x201\x20AS\x20id','1248lDveJB','60132CFIYrP','--db-id\x20is\x20required\x20in\x20non-interactive\x20mode.','/smartapi/custom/saveUserCustomSql','write','join','isFinite','str','dbId\x20must\x20be\x20a\x20positive\x20integer','MyBatis\x20XML\x20(mybatisXml)','__manual__','sqlName','sqlRoot','--name\x20is\x20required\x20in\x20non-interactive\x20mode.','create','name','POST','Select\x20the\x20target\x20database:','Invalid\x20database\x20selection\x20payload:\x20','validation','sqls','flagMissing','mode','stringify','string','426MHkhxO','lockFilePath','File\x20already\x20exists:\x20','319nqNFeb','catch','db-id','250FjNucJ','dbId\x20cannot\x20be\x20empty','SQL\x20name\x20cannot\x20be\x20empty','trim','isInteger','Target\x20database\x20dbId:','55190zHWSwU','mybatisXml','sqlRootDir','--mode\x20is\x20required\x20in\x20non-interactive\x20mode.','sql','appCode','number','For\x20MyBatis\x20XML\x20SQL\x20with\x20dynamic\x20tags','parse','Select\x20the\x20local\x20SQL\x20mode:','dbId','utf8','length','159uyyVQZ','new','toISOString','8lBdVnt','</select>','846882VIvMMS','Local\x20SQL\x20file\x20mode','sqlCode','Target\x20database\x20ID','✎\x20Enter\x20dbId\x20manually','Would\x20create\x20a\x20new\x20SQL\x20query\x20and\x20scaffold\x20it\x20under\x20'];a247_0x427d=function(){return _0x383374;};return a247_0x427d();}function generateSqlTemplate(_0x55ab9a){const _0x2dac4d=a247_0x3e63;if(_0x55ab9a===_0x2dac4d(0x181))return[_0x2dac4d(0x19f),_0x2dac4d(0x1a3),_0x2dac4d(0x191),''][_0x2dac4d(0x1a9)]('\x0a');return['SELECT\x201\x20AS\x20id;',''][_0x2dac4d(0x1a9)]('\x0a');}export const sqlCreate={'service':a247_0xb35f96(0x184),'command':a247_0xb35f96(0x1b2),'description':'Create\x20a\x20new\x20custom\x20SQL\x20and\x20scaffold\x20it\x20locally','risk':a247_0xb35f96(0x1a8),'flags':[{'name':'name','type':'string','description':a247_0xb35f96(0x199)},{'name':a247_0xb35f96(0x179),'type':a247_0xb35f96(0x186),'description':a247_0xb35f96(0x195)},{'name':a247_0xb35f96(0x171),'type':a247_0xb35f96(0x173),'enum':[a247_0xb35f96(0x184),a247_0xb35f96(0x181)],'description':a247_0xb35f96(0x193)}],async 'validate'(_0x442daf){const _0x57a571=a247_0xb35f96;if(!_0x442daf['nonInteractive'])return;if(!_0x442daf[_0x57a571(0x1ab)]('name')['trim']())throw CliErrors['flagMissing'](_0x57a571(0x1b3),'--name\x20is\x20required\x20in\x20non-interactive\x20mode.');const _0x5b4a30=resolveProvidedDbId(_0x442daf);if(typeof _0x5b4a30!==_0x57a571(0x186)||!Number[_0x57a571(0x1aa)](_0x5b4a30)||_0x5b4a30<=0x0)throw CliErrors[_0x57a571(0x170)]('db-id',_0x57a571(0x1a6));if(!_0x442daf['str']('mode')[_0x57a571(0x17d)]())throw CliErrors[_0x57a571(0x170)]('mode',_0x57a571(0x183));},async 'dryRun'(_0x18d6c7){const _0x440a1f=a247_0xb35f96,_0x394303=loadSqlProjectConfig(_0x18d6c7[_0x440a1f(0x185)]),{sqlName:_0x477ed1,dbId:_0x44114b,dbName:_0x5b255c,mode:_0x9412c1}=await resolveSqlNewInputs(_0x18d6c7),_0x1b1ec4=buildSqlRelativePath('<server-generated-sqlCode>',_0x477ed1,_0x5b255c,_0x9412c1,_0x44114b),_0x57fe6a=_0x394303[_0x440a1f(0x182)]+'/'+_0x1b1ec4;return{'method':_0x440a1f(0x1b4),'url':_0x440a1f(0x1a7),'body':{'appCode':_0x18d6c7[_0x440a1f(0x185)],'sqlName':_0x477ed1,'dbId':_0x44114b,'mode':_0x9412c1,'localPath':_0x57fe6a},'description':_0x440a1f(0x197)+_0x394303['sqlRootDir']};},async 'execute'(_0x6a54a0){const _0x443839=a247_0xb35f96,_0x31eabe=loadSqlProjectConfig(_0x6a54a0[_0x443839(0x185)]),{sqlName:_0x3e6649,dbId:_0x28effe,dbName:_0x2830f7,mode:_0x47b615}=await resolveSqlNewInputs(_0x6a54a0),_0x2c2885=generateSqlTemplate(_0x47b615),_0x2980a0=await createSqlQuery({'appCode':_0x6a54a0[_0x443839(0x185)],'sqlName':_0x3e6649,'dbId':_0x28effe,'sqlContent':_0x2c2885}),_0x2962aa=ensureRemoteSqlContent(_0x2980a0),_0x5c6ea8=_0x2830f7||await getDbName(_0x6a54a0[_0x443839(0x185)],_0x28effe)[_0x443839(0x178)](()=>undefined),_0x31a3cd=buildSqlRelativePath(_0x2980a0[_0x443839(0x194)],_0x2980a0['sqlName'],_0x5c6ea8,_0x47b615,_0x28effe),_0x4db938=_0x31eabe[_0x443839(0x182)]+'/'+_0x31a3cd,_0x922c35=buildLocalSqlFileContent({'sqlCode':_0x2980a0[_0x443839(0x194)],'sqlName':_0x2980a0[_0x443839(0x1af)],'dbId':_0x2980a0[_0x443839(0x18a)]},_0x2962aa,{'dbName':_0x5c6ea8,'mode':_0x47b615,'syncedAt':new Date()[_0x443839(0x18f)](),'description':_0x2980a0['description']});if(await fileExists(_0x4db938))throw CliErrors[_0x443839(0x16e)](_0x443839(0x176)+_0x4db938);await ensureParentDirectory(_0x4db938),await writeFile(_0x4db938,_0x922c35,_0x443839(0x18b));const _0x48746f=await readSqlLockFile(_0x31eabe[_0x443839(0x175)]),{lockData:_0x2280ae,appLock:_0x522675}=ensureSqlLockScope(_0x48746f??createEmptySqlLock(),_0x31eabe['appCode'],_0x31eabe[_0x443839(0x1b0)],_0x443839(0x18e));return _0x522675[_0x443839(0x16f)][_0x2980a0[_0x443839(0x194)]]={...buildSqlLockEntry(_0x2980a0,_0x2962aa,computeSqlContentHash(_0x922c35),{'dbName':_0x5c6ea8}),'path':_0x31a3cd,'mode':_0x47b615},_0x522675[_0x443839(0x19b)]=new Date()['toISOString'](),await writeSqlLockFile(_0x31eabe[_0x443839(0x175)],_0x2280ae),{'ok':!![],'data':{'id':_0x2980a0['id'],'sqlCode':_0x2980a0[_0x443839(0x194)],'sqlName':_0x2980a0['sqlName'],'dbId':_0x2980a0[_0x443839(0x18a)],'path':_0x4db938,'mode':_0x47b615},'message':_0x443839(0x1a2)+_0x2980a0[_0x443839(0x194)]};}};async function resolveSqlNewInputs(_0x3a0b93){const _0x347a7a=await resolveSqlNameInput(_0x3a0b93),{dbId:_0xd77f01,dbName:_0x33ce88}=await resolveDbSelection(_0x3a0b93),_0x58d773=await resolveSqlModeInput(_0x3a0b93);return{'sqlName':_0x347a7a,'dbId':_0xd77f01,'dbName':_0x33ce88,'mode':_0x58d773};}async function resolveSqlNameInput(_0x260632){const _0x165ef7=a247_0xb35f96,_0x3df988=_0x260632[_0x165ef7(0x1ab)](_0x165ef7(0x1b3))[_0x165ef7(0x17d)]();if(_0x3df988)return _0x3df988;if(_0x260632['nonInteractive'])throw CliErrors[_0x165ef7(0x170)]('name',_0x165ef7(0x1b1));return(await input({'message':'SQL\x20name:','validate':_0x5099e1=>_0x5099e1[_0x165ef7(0x17d)]()?!![]:_0x165ef7(0x17c)}))['trim']();}async function resolveDbSelection(_0x5a2391){const _0x4be2e9=a247_0xb35f96,_0x1eb985=resolveProvidedDbId(_0x5a2391);if(typeof _0x1eb985==='number'&&Number[_0x4be2e9(0x1aa)](_0x1eb985)&&_0x1eb985>0x0)return{'dbId':_0x1eb985,'dbName':await getDbName(_0x5a2391[_0x4be2e9(0x185)],_0x1eb985)['catch'](()=>undefined)};if(_0x5a2391[_0x4be2e9(0x19c)])throw CliErrors[_0x4be2e9(0x170)](_0x4be2e9(0x179),'--db-id\x20is\x20required\x20in\x20non-interactive\x20mode.');const _0x2894cb=await listDatabases(_0x5a2391[_0x4be2e9(0x185)])['catch'](()=>[]);if(_0x2894cb['length']===0x1)return{'dbId':_0x2894cb[0x0][_0x4be2e9(0x18a)],'dbName':_0x2894cb[0x0][_0x4be2e9(0x19a)]};if(_0x2894cb[_0x4be2e9(0x18c)]>0x1){const _0x522ee0=await select({'message':_0x4be2e9(0x1b5),'choices':[..._0x2894cb['map'](_0x29a04a=>({'name':_0x29a04a[_0x4be2e9(0x19a)]+'\x20('+_0x29a04a[_0x4be2e9(0x18a)]+')','value':serializeDbSelection(_0x29a04a)})),{'name':_0x4be2e9(0x196),'value':_0x4be2e9(0x1ae)}]});if(_0x522ee0!=='__manual__')return deserializeDbSelection(_0x522ee0);}const _0x261edc=await input({'message':_0x4be2e9(0x17f),'validate':_0x51c723=>{const _0xa6e06c=_0x4be2e9,_0x1becde=_0x51c723[_0xa6e06c(0x17d)]();if(!_0x1becde)return _0xa6e06c(0x17b);const _0x348561=Number(_0x1becde);if(!Number[_0xa6e06c(0x17e)](_0x348561)||_0x348561<=0x0)return _0xa6e06c(0x1ac);return!![];}});return{'dbId':Number(_0x261edc[_0x4be2e9(0x17d)]())};}async function resolveSqlModeInput(_0x35b1e4){const _0x649ce0=a247_0xb35f96,_0x542121=_0x35b1e4[_0x649ce0(0x1ab)]('mode')[_0x649ce0(0x17d)]();if(_0x542121==='sql'||_0x542121==='mybatisXml')return _0x542121;if(_0x35b1e4[_0x649ce0(0x19c)])throw CliErrors[_0x649ce0(0x170)](_0x649ce0(0x171),_0x649ce0(0x183));return await select({'message':_0x649ce0(0x189),'choices':[{'name':_0x649ce0(0x19d),'value':_0x649ce0(0x184),'description':'For\x20SELECT\x20/\x20INSERT\x20/\x20UPDATE\x20/\x20DELETE\x20statements\x20that\x20run\x20directly'},{'name':_0x649ce0(0x1ad),'value':_0x649ce0(0x181),'description':_0x649ce0(0x187)}]});}function serializeDbSelection(_0x1b7128){const _0x4e02cb=a247_0xb35f96;return JSON[_0x4e02cb(0x172)]({'dbId':_0x1b7128[_0x4e02cb(0x18a)],'dbName':_0x1b7128[_0x4e02cb(0x19a)]});}function deserializeDbSelection(_0x226f61){const _0x2262eb=a247_0xb35f96;try{const _0x4dd48d=JSON[_0x2262eb(0x188)](_0x226f61);if(typeof _0x4dd48d[_0x2262eb(0x18a)]===_0x2262eb(0x186)&&Number['isFinite'](_0x4dd48d['dbId']))return{'dbId':_0x4dd48d[_0x2262eb(0x18a)],'dbName':_0x4dd48d['dbName']};}catch{}throw CliErrors[_0x2262eb(0x16e)](_0x2262eb(0x16d)+_0x226f61);}function resolveProvidedDbId(_0x4e61ec){const _0x332c64=a247_0xb35f96,_0x1b726c=_0x4e61ec['flag'](_0x332c64(0x179));if(typeof _0x1b726c===_0x332c64(0x186)&&Number[_0x332c64(0x1aa)](_0x1b726c))return _0x1b726c;return undefined;}
|
|
1
|
+
import{writeFile}from"node:fs/promises";import{input,select}from"@inquirer/prompts";import{createSqlQuery}from"../../core/api-client.js";import{getDbName,listDatabases}from"../../core/db-resolver.js";import{loadSqlProjectConfig}from"../../core/sql-sync/config.js";import{ensureParentDirectory,fileExists}from"../../core/bff/file-system.js";import{computeSqlContentHash}from"../../core/sql-sync/hash.js";import{createEmptySqlLock,ensureSqlLockScope,readSqlLockFile,writeSqlLockFile}from"../../core/sql-sync/lock.js";import{buildSqlRelativePath}from"../../core/sql-sync/utils.js";import{CliErrors}from"../../errors.js";import{buildLocalSqlFileContent,buildSqlLockEntry,ensureRemoteSqlContent}from"./shared.js";function generateSqlTemplate(mode){if(mode==="mybatisXml"){return['<select id="query" resultType="map">'," SELECT 1 AS id","</select>",""].join("\n")}return["SELECT 1 AS id;",""].join("\n")}export const sqlCreate={service:"sql",command:"create",
|
|
2
|
+
description:"Create a new custom SQL and scaffold it locally",risk:"write",flags:[{name:"name",type:"string",description:"SQL query display name"},{name:"db-id",type:"number",description:"Target database ID"},{name:"mode",type:"string",enum:["sql","mybatisXml"],description:"Local SQL file mode"}],async validate(ctx){if(!ctx.nonInteractive){return}if(!ctx.str("name").trim()){throw CliErrors.flagMissing("name","--name is required in non-interactive mode.")}const rawDbId=resolveProvidedDbId(ctx);if(typeof rawDbId!=="number"||!Number.isFinite(rawDbId)||rawDbId<=0){throw CliErrors.flagMissing("db-id","--db-id is required in non-interactive mode.")}if(!ctx.str("mode").trim()){throw CliErrors.flagMissing("mode","--mode is required in non-interactive mode.")}},async dryRun(ctx){const config=loadSqlProjectConfig(ctx.appCode);const{sqlName:sqlName,dbId:dbId,dbName:dbName,mode:mode}=await resolveSqlNewInputs(ctx)
|
|
3
|
+
;const fileName=buildSqlRelativePath("<server-generated-sqlCode>",sqlName,dbName,mode,dbId);const targetFilePath=`${config.sqlRootDir}/${fileName}`;return{method:"POST",url:"/smartapi/custom/saveUserCustomSql",body:{appCode:ctx.appCode,sqlName:sqlName,dbId:dbId,mode:mode,localPath:targetFilePath},description:`Would create a new SQL query and scaffold it under ${config.sqlRootDir}`}},async execute(ctx){const config=loadSqlProjectConfig(ctx.appCode);const{sqlName:sqlName,dbId:dbId,dbName:dbName,mode:mode}=await resolveSqlNewInputs(ctx);const template=generateSqlTemplate(mode);const sql=await createSqlQuery({appCode:ctx.appCode,sqlName:sqlName,dbId:dbId,sqlContent:template});const remoteSqlContent=ensureRemoteSqlContent(sql);const resolvedDbName=dbName||await getDbName(ctx.appCode,dbId).catch(()=>undefined);const fileName=buildSqlRelativePath(sql.sqlCode,sql.sqlName,resolvedDbName,mode,dbId);const targetFilePath=`${config.sqlRootDir}/${fileName}`
|
|
4
|
+
;const localFileContent=buildLocalSqlFileContent({sqlCode:sql.sqlCode,sqlName:sql.sqlName,dbId:sql.dbId},remoteSqlContent,{dbName:resolvedDbName,mode:mode,syncedAt:(new Date).toISOString(),description:sql.description});if(await fileExists(targetFilePath)){throw CliErrors.validation(`File already exists: ${targetFilePath}`)}await ensureParentDirectory(targetFilePath);await writeFile(targetFilePath,localFileContent,"utf8");const rawLock=await readSqlLockFile(config.lockFilePath);const{lockData:lockData,appLock:appLock}=ensureSqlLockScope(rawLock??createEmptySqlLock(),config.appCode,config.sqlRoot,"new");appLock.sqls[sql.sqlCode]={...buildSqlLockEntry(sql,remoteSqlContent,computeSqlContentHash(localFileContent),{dbName:resolvedDbName}),path:fileName,mode:mode};appLock.lastSync=(new Date).toISOString();await writeSqlLockFile(config.lockFilePath,lockData);return{ok:true,data:{id:sql.id,sqlCode:sql.sqlCode,sqlName:sql.sqlName,dbId:sql.dbId,path:targetFilePath,mode:mode},
|
|
5
|
+
message:`Created SQL query ${sql.sqlCode}`}}};async function resolveSqlNewInputs(ctx){const sqlName=await resolveSqlNameInput(ctx);const{dbId:dbId,dbName:dbName}=await resolveDbSelection(ctx);const mode=await resolveSqlModeInput(ctx);return{sqlName:sqlName,dbId:dbId,dbName:dbName,mode:mode}}async function resolveSqlNameInput(ctx){const raw=ctx.str("name").trim();if(raw){return raw}if(ctx.nonInteractive){throw CliErrors.flagMissing("name","--name is required in non-interactive mode.")}return(await input({message:"SQL name:",validate:value=>value.trim()?true:"SQL name cannot be empty"})).trim()}async function resolveDbSelection(ctx){const rawDbId=resolveProvidedDbId(ctx);if(typeof rawDbId==="number"&&Number.isFinite(rawDbId)&&rawDbId>0){return{dbId:rawDbId,dbName:await getDbName(ctx.appCode,rawDbId).catch(()=>undefined)}}if(ctx.nonInteractive){throw CliErrors.flagMissing("db-id","--db-id is required in non-interactive mode.")}const databases=await listDatabases(ctx.appCode).catch(()=>[])
|
|
6
|
+
;if(databases.length===1){return{dbId:databases[0].dbId,dbName:databases[0].dbName}}if(databases.length>1){const selected=await select({message:"Select the target database:",choices:[...databases.map(db=>({name:`${db.dbName} (${db.dbId})`,value:serializeDbSelection(db)})),{name:"✎ Enter dbId manually",value:"__manual__"}]});if(selected!=="__manual__"){return deserializeDbSelection(selected)}}const manualDbId=await input({message:"Target database dbId:",validate:value=>{const trimmed=value.trim();if(!trimmed)return"dbId cannot be empty";const numeric=Number(trimmed);if(!Number.isInteger(numeric)||numeric<=0){return"dbId must be a positive integer"}return true}});return{dbId:Number(manualDbId.trim())}}async function resolveSqlModeInput(ctx){const rawMode=ctx.str("mode").trim();if(rawMode==="sql"||rawMode==="mybatisXml"){return rawMode}if(ctx.nonInteractive){throw CliErrors.flagMissing("mode","--mode is required in non-interactive mode.")}return await select({
|
|
7
|
+
message:"Select the local SQL mode:",choices:[{name:"Plain SQL (sql)",value:"sql",description:"For SELECT / INSERT / UPDATE / DELETE statements that run directly"},{name:"MyBatis XML (mybatisXml)",value:"mybatisXml",description:"For MyBatis XML SQL with dynamic tags"}]})}function serializeDbSelection(db){return JSON.stringify({dbId:db.dbId,dbName:db.dbName})}function deserializeDbSelection(raw){try{const parsed=JSON.parse(raw);if(typeof parsed.dbId==="number"&&Number.isFinite(parsed.dbId)){return{dbId:parsed.dbId,dbName:parsed.dbName}}}catch{}throw CliErrors.validation(`Invalid database selection payload: ${raw}`)}function resolveProvidedDbId(ctx){const kebab=ctx.flag("db-id");if(typeof kebab==="number"&&Number.isFinite(kebab)){return kebab}return undefined}
|
|
@@ -1 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import{mkdir,readdir,rename,rmdir}from"node:fs/promises";import{dirname,join,relative,resolve,sep}from"node:path";import{deleteSqlQuery}from"../../core/api-client.js";import{loadSqlProjectConfig}from"../../core/sql-sync/config.js";import{fileExists}from"../../core/bff/file-system.js";import{resolveLocalSqlFilePath}from"../../core/sql-sync/file-system.js";import{ensureSqlLockScope,readSqlLockFile,writeSqlLockFile}from"../../core/sql-sync/lock.js";import{CliErrors}from"../../errors.js";import{SQLCODE_FLAG}from"../../commands/common/flags.js";export const sqlDelete={service:"sql",command:"delete",description:"Delete a SQL query from remote and local",risk:"high-risk-write",flags:[SQLCODE_FLAG],async validate(ctx){const config=loadSqlProjectConfig(ctx.appCode);const lockData=await readSqlLockFile(config.lockFilePath);if(!lockData){throw CliErrors.validation("SQL lock file not found. Run `rabetbase sql create` or `rabetbase sql pull` first.")}},async dryRun(ctx){
|
|
2
|
+
const config=loadSqlProjectConfig(ctx.appCode);const lockData=await readSqlLockFile(config.lockFilePath);if(!lockData){throw CliErrors.validation("SQL lock file not found. Run `rabetbase sql create` or `rabetbase sql pull` first.")}const{appLock:appLock}=ensureSqlLockScope(lockData,ctx.appCode,config.sqlRoot,"delete");const sqlCode=ctx.str("sqlcode");const lockEntry=appLock.sqls[sqlCode];if(!lockEntry){throw CliErrors.validation(`No SQL lock entry found for "${sqlCode}".`)}return{method:"POST",url:"/smartapi/custom/deleteUserCustomSql",body:{sqlCode:sqlCode,id:lockEntry.remoteId,localPath:resolveLocalSqlFilePath(config,sqlCode,lockEntry)},description:`Would delete SQL ${sqlCode} from remote and move local file to ${config.trashDir}`}},async execute(ctx){const config=loadSqlProjectConfig(ctx.appCode);const lockDataFromFile=await readSqlLockFile(config.lockFilePath);if(!lockDataFromFile){throw CliErrors.validation("SQL lock file not found.")}
|
|
3
|
+
const{lockData:lockData,appLock:appLock}=ensureSqlLockScope(lockDataFromFile,ctx.appCode,config.sqlRoot,"delete");const sqlCode=ctx.str("sqlcode");const lockEntry=appLock.sqls[sqlCode];if(!lockEntry){throw CliErrors.validation(`No SQL lock entry found for "${sqlCode}".`)}await deleteSqlQuery({id:lockEntry.remoteId,sqlCode:sqlCode});appLock.sqls=Object.fromEntries(Object.entries(appLock.sqls).filter(([key])=>key!==sqlCode));appLock.lastSync=(new Date).toISOString();await writeSqlLockFile(config.lockFilePath,lockData);const localFilePath=resolveLocalSqlFilePath(config,sqlCode,lockEntry);let trashedPath;if(await fileExists(localFilePath)){trashedPath=await moveToTrash(config.projectRoot,config.trashDir,localFilePath);await cleanupEmptyDirectories(dirname(localFilePath),config.sqlRootDir)}const data={deleted:sqlCode,remoteId:lockEntry.remoteId};if(trashedPath)data["trashedTo"]=trashedPath;return{ok:true,data:data,message:`Deleted ${sqlCode}`+(trashedPath?" (local file moved to trash)":"")}
|
|
4
|
+
}};async function moveToTrash(projectRoot,trashDir,localFilePath){const timestamp=(new Date).toISOString().replace(/[:.]/g,"-");const relativePath=relative(projectRoot,localFilePath);const targetPath=join(trashDir,timestamp,relativePath);await mkdir(dirname(targetPath),{recursive:true});await rename(localFilePath,targetPath);return targetPath}async function cleanupEmptyDirectories(startDir,stopDir){let currentDir=resolve(startDir);const normalizedStop=resolve(stopDir);while(currentDir.startsWith(`${normalizedStop}${sep}`)||currentDir===normalizedStop){if(currentDir===normalizedStop)return;try{const entries=await readdir(currentDir);if(entries.length>0)return;await rmdir(currentDir)}catch{return}currentDir=dirname(currentDir)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{getSqlQueryInfo}from"../../core/api-client.js";import{getDbName}from"../../core/db-resolver.js";import{SQLCODE_FLAG}from"../../commands/common/flags.js";export const sqlDetail={service:"sql",command:"detail",description:"Get custom SQL query details by sqlCode",risk:"read",flags:[SQLCODE_FLAG,{name:"verbose",type:"boolean",description:"Return full raw SQL query object"}],async execute(ctx){const sql=await getSqlQueryInfo(ctx.appCode,ctx.str("sqlcode"));const verbose=ctx.bool("verbose");if(verbose){return{ok:true,data:sql}}const dbName=sql.dbId?await getDbName(ctx.appCode,sql.dbId):undefined;return{ok:true,data:{sqlCode:sql.sqlCode,sqlName:sql.sqlName,db:dbName?`${dbName} (${sql.dbId})`:sql.dbId??"",description:sql.description??"",sqlContent:sql.sqlContent??""}}}};
|
package/lib/commands/sql/exec.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{executeSql}from"../../core/api-client.js";import{SQLCODE_FLAG}from"../../commands/common/flags.js";import{parseJsonParams}from"../../utils/params.js";export const sqlExec={service:"sql",command:"exec",description:"Execute a custom SQL query by sqlCode",risk:"read",flags:[SQLCODE_FLAG,{name:"params",type:"string",description:'SQL parameters as JSON string (e.g. \'{"key":"value"}\')'}],async execute(ctx){const params=parseJsonParams(ctx.str("params"));const startTime=Date.now();const result=await executeSql(ctx.appCode,ctx.str("sqlcode"),params);const elapsed=Date.now()-startTime;const execResult=result?.execResult??result;const execSuccess=result?.execSuccess??true;if(!execSuccess){return{ok:false,data:{error:result?.execError||"SQL execution failed",elapsed:elapsed},message:"SQL execution failed"}}const rows=Array.isArray(execResult)?execResult:[];return{ok:true,data:{rows:rows,rowCount:rows.length,elapsed:elapsed},message:`Returned ${rows.length} row(s) in ${elapsed}ms`}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{sqlList}from"../../commands/sql/list.js";import{sqlDetail}from"../../commands/sql/detail.js";import{sqlValidate}from"../../commands/sql/validate.js";import{sqlExec}from"../../commands/sql/exec.js";import{sqlPull}from"../../commands/sql/pull.js";import{sqlCreate}from"../../commands/sql/create.js";import{sqlStatus}from"../../commands/sql/status.js";import{sqlPush}from"../../commands/sql/push.js";import{sqlDelete}from"../../commands/sql/delete.js";export const sqlDefinitions=[sqlList,sqlDetail,sqlStatus,sqlCreate,sqlPush,sqlValidate,sqlExec,sqlPull,sqlDelete];
|
package/lib/commands/sql/list.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{listSqlQueries}from"../../core/api-client.js";import{getDbName}from"../../core/db-resolver.js";import{SQLCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";export const sqlList={service:"sql",command:"list",description:"List custom SQL queries",risk:"read",flags:[SQLCODE_FLAG_OPTIONAL,{name:"name",type:"string",description:"Filter by SQL name"},{name:"page",type:"number",description:"Page number",default:1},{name:"pagesize",type:"number",description:"Page size"},{name:"verbose",type:"boolean",description:"Return full SQL query objects including parameters and SQL content"}],async execute(ctx){const result=await listSqlQueries(ctx.appCode,{sqlCode:ctx.str("sqlcode")||undefined,sqlName:ctx.str("name")||undefined,currentPage:ctx.num("page"),pageSize:ctx.num("pagesize",50)});const verbose=ctx.bool("verbose");const items=result.tableData??[];const total=result.paging?.totalCount??items.length;let projectedItems;if(verbose){projectedItems=items}else{
|
|
2
|
+
projectedItems=await Promise.all(items.map(async sql=>{let dbName;try{dbName=sql.dbId?await getDbName(ctx.appCode,sql.dbId):undefined}catch{}return{sqlCode:sql.sqlCode,sqlName:sql.sqlName,description:sql.description??"",db:dbName?`${dbName} (${sql.dbId})`:sql.dbId??""}}))}return{ok:true,data:projectedItems,message:items.length===0?"No custom SQL queries found.":`Found ${items.length} SQL queries (total: ${total}).`}}};
|
package/lib/commands/sql/pull.js
CHANGED
|
@@ -1 +1,10 @@
|
|
|
1
|
-
const a253_0x2d48fa=a253_0x5a8d;(function(_0x344d5a,_0x541348){const _0x293840=a253_0x5a8d,_0xf2f294=_0x344d5a();while(!![]){try{const _0x431bb7=parseInt(_0x293840(0xf0))/0x1*(parseInt(_0x293840(0x113))/0x2)+-parseInt(_0x293840(0x11c))/0x3+-parseInt(_0x293840(0x101))/0x4+parseInt(_0x293840(0x125))/0x5+parseInt(_0x293840(0x104))/0x6*(parseInt(_0x293840(0xf4))/0x7)+parseInt(_0x293840(0xd8))/0x8*(parseInt(_0x293840(0xd7))/0x9)+-parseInt(_0x293840(0x112))/0xa;if(_0x431bb7===_0x541348)break;else _0xf2f294['push'](_0xf2f294['shift']());}catch(_0x3d7024){_0xf2f294['push'](_0xf2f294['shift']());}}}(a253_0x4c77,0xc9231));function a253_0x4c77(){const _0x323e3b=['path','217sURoum','all','toISOString','pull','str','join','bool','force','skipped','sqlContent','Would\x20pull\x20','lockFilePath','would_pull','1227240MfHiWn','sqlCode','description','102942tqnVbC','\x20failed','boolean','Force\x20overwrite\x20local\x20unsynced\x20changes','POST','Pull\x20complete:\x20','\x20written,\x20','hash','conflict','unchanged','utf8','file','read','find','22714250MXvwgT','5578OQEAbL','name','No\x20remote\x20SQL\x20queries\x20matched.','\x20skipped,\x20','sql','toLowerCase','push','cancelled','sqlName','752265gplvid','sqlRootDir','test','filePath','sqls','endsWith','some','local\x20differs\x20from\x20remote','sqlRoot','4538865zHfcxY','5837202xoFshO','8obaNjS','trim','sqlcode','length','Force\x20pull\x20will\x20overwrite\x20local\x20SQL\x20that\x20differs\x20from\x20remote.','replace','string','local\x20differs\x20from\x20remote\x20(use\x20--force\x20to\x20overwrite)','split','equivalent','filter','catch','Force\x20pull\x20cancelled.','appCode','Filter\x20by\x20SQL\x20display\x20name','tableData','message','/smartapi/custom/queryUserCustomSqlList\x20+\x20/smartapi/custom/getUserCustomSql','mybatisXml','isCanonical','map','dbId','totalCount','mode','561voOYVS','Pull\x20remote\x20SQL\x20queries\x20to\x20local\x20.rabetbase/sql/','apps'];a253_0x4c77=function(){return _0x323e3b;};return a253_0x4c77();}import{readFile,rm,writeFile}from'node:fs/promises';import{join}from'node:path';import{getSqlQueryDetail,listSqlQueries}from'../../core/api-client.js';import{ensureParentDirectory,fileExists}from'../../core/bff/file-system.js';import{getDbName}from'../../core/db-resolver.js';import{loadSqlProjectConfig}from'../../core/sql-sync/config.js';import{computeSqlContentHash}from'../../core/sql-sync/hash.js';import{createEmptySqlLock,ensureSqlLockScope,readSqlLockFile,writeSqlLockFile}from'../../core/sql-sync/lock.js';import{resolveLocalSqlFilePath}from'../../core/sql-sync/file-system.js';import{detectSqlMode}from'../../core/sql-sync/utils.js';import{CliErrors}from'../../errors.js';import{SQLCODE_FLAG_OPTIONAL}from'../../commands/common/flags.js';import{buildLocalSqlFileContent,buildSqlLockEntry,cloneSqlLockData,confirmForceOverwrite,ensureRemoteSqlContent,stripLocalSqlMetadata}from'./shared.js';const PAGE_SIZE=0x64;async function fetchAllSqlQueries(_0x8f025d,_0x27d162){const _0x3bc423=a253_0x5a8d,_0x413360=[];let _0x36c6f9=0x1;while(!![]){const _0x459c9b=await listSqlQueries(_0x8f025d,{'currentPage':_0x36c6f9,'pageSize':PAGE_SIZE,'sqlCode':_0x27d162[_0x3bc423(0x102)],'sqlName':_0x27d162[_0x3bc423(0x11b)]}),_0x2b71a0=_0x459c9b[_0x3bc423(0xe7)]??[];_0x413360[_0x3bc423(0x119)](..._0x2b71a0);if(_0x2b71a0[_0x3bc423(0xdb)]===0x0)break;const _0x4cc57f=_0x459c9b['paging']?.[_0x3bc423(0xee)];if(_0x4cc57f!=null?_0x413360['length']>=_0x4cc57f:_0x2b71a0['length']<PAGE_SIZE)break;_0x36c6f9++;}return _0x413360;}function a253_0x5a8d(_0x372605,_0x37f8ec){_0x372605=_0x372605-0xd7;const _0x4c77e2=a253_0x4c77();let _0x5a8d27=_0x4c77e2[_0x372605];return _0x5a8d27;}async function ensureSqlContent(_0x41ed39){const _0x494463=a253_0x5a8d;if(_0x41ed39[_0x494463(0xfd)]!=null&&String(_0x41ed39[_0x494463(0xfd)])[_0x494463(0xdb)]>0x0)return _0x41ed39;return getSqlQueryDetail(_0x41ed39[_0x494463(0x102)]);}export const sqlPull={'service':a253_0x2d48fa(0x117),'command':a253_0x2d48fa(0xf7),'description':a253_0x2d48fa(0xf1),'risk':a253_0x2d48fa(0x110),'flags':[SQLCODE_FLAG_OPTIONAL,{'name':a253_0x2d48fa(0x114),'type':a253_0x2d48fa(0xde),'description':a253_0x2d48fa(0xe6)},{'name':a253_0x2d48fa(0xfb),'type':a253_0x2d48fa(0x106),'description':a253_0x2d48fa(0x107)}],async 'dryRun'(_0x25adb1){const _0x4d9cde=a253_0x2d48fa,_0x2fbbe4=loadSqlProjectConfig(_0x25adb1['appCode']),_0x4196ea=await readSqlLockFile(_0x2fbbe4[_0x4d9cde(0xff)]),{appLock:_0x2b46ce}=ensureSqlLockScope(_0x4196ea??createEmptySqlLock(),_0x2fbbe4[_0x4d9cde(0xe5)],_0x2fbbe4[_0x4d9cde(0x124)],'pull'),_0x4e7cfd=await fetchAllSqlQueries(_0x25adb1[_0x4d9cde(0xe5)],{'sqlCode':_0x25adb1[_0x4d9cde(0xf8)](_0x4d9cde(0xda))||undefined,'sqlName':_0x25adb1[_0x4d9cde(0xf8)](_0x4d9cde(0x114))||undefined}),_0x47ece7=[];for(const _0x2e6308 of _0x4e7cfd){const _0x59e4bd=await ensureSqlContent(_0x2e6308),_0x598486=ensureRemoteSqlContent(_0x59e4bd),_0x2eefd5=detectSqlMode(_0x598486),_0x155452=_0x59e4bd[_0x4d9cde(0xed)]?await getDbName(_0x25adb1[_0x4d9cde(0xe5)],Number(_0x59e4bd[_0x4d9cde(0xed)]))[_0x4d9cde(0xe3)](()=>undefined):undefined,_0x45a5e1=buildLocalSqlFileContent({'sqlCode':_0x59e4bd[_0x4d9cde(0x102)],'sqlName':_0x59e4bd[_0x4d9cde(0x11b)],'dbId':_0x59e4bd[_0x4d9cde(0xed)]},_0x598486,{'dbName':_0x155452,'mode':_0x2eefd5,'syncedAt':new Date()[_0x4d9cde(0xf6)](),'description':_0x59e4bd[_0x4d9cde(0x103)]}),_0x166875=buildSqlLockEntry(_0x59e4bd,_0x598486,'',{'dbName':_0x155452}),_0x38e8cd=resolveLocalSqlFilePath(_0x2fbbe4,_0x59e4bd['sqlCode'],_0x166875);let _0x2eb752=_0x4d9cde(0x100),_0x1864af;const _0x1d6f27=await findExistingSqlFiles(_0x2fbbe4,_0x38e8cd,_0x2eefd5,_0x2b46ce[_0x4d9cde(0x120)][_0x59e4bd[_0x4d9cde(0x102)]]);if(_0x1d6f27[_0x4d9cde(0xdb)]>0x0){const _0x598ece=await compareExistingSqlFiles(_0x1d6f27,_0x45a5e1,_0x2eefd5);if(_0x598ece[_0x4d9cde(0x122)](({equivalent:_0x31390d})=>!_0x31390d))_0x2eb752=_0x4d9cde(0x10c),_0x1864af=_0x4d9cde(0xdf);else _0x598ece[_0x4d9cde(0xdb)]===0x1&&_0x598ece[0x0]?.[_0x4d9cde(0x10f)][_0x4d9cde(0xeb)]&&(_0x2eb752=_0x4d9cde(0xfc),_0x1864af='unchanged');}_0x47ece7[_0x4d9cde(0x119)]({'sqlCode':_0x59e4bd['sqlCode'],'sqlName':_0x59e4bd['sqlName'],'filePath':_0x38e8cd,'status':_0x2eb752,'reason':_0x1864af});}return{'method':_0x4d9cde(0x108),'url':_0x4d9cde(0xe9),'body':{'appCode':_0x25adb1[_0x4d9cde(0xe5)],'sqlCode':_0x25adb1[_0x4d9cde(0xf8)](_0x4d9cde(0xda))||null,'sqlName':_0x25adb1[_0x4d9cde(0xf8)](_0x4d9cde(0x114))||null,'files':_0x47ece7},'description':_0x4d9cde(0xfe)+_0x47ece7[_0x4d9cde(0xdb)]+'\x20SQL\x20file(s)\x20into\x20'+_0x2fbbe4[_0x4d9cde(0x11d)]};},async 'execute'(_0x21c30f){const _0x5c3c94=a253_0x2d48fa,_0xf1a3f9=loadSqlProjectConfig(_0x21c30f[_0x5c3c94(0xe5)]),_0x4be849=await readSqlLockFile(_0xf1a3f9[_0x5c3c94(0xff)]),{lockData:_0x33483c,appLock:_0x2d21a3}=ensureSqlLockScope(_0x4be849??createEmptySqlLock(),_0xf1a3f9[_0x5c3c94(0xe5)],_0xf1a3f9[_0x5c3c94(0x124)],_0x5c3c94(0xf7)),_0x263262=_0x21c30f[_0x5c3c94(0xfa)](_0x5c3c94(0xfb)),_0x3fb579=await fetchAllSqlQueries(_0x21c30f[_0x5c3c94(0xe5)],{'sqlCode':_0x21c30f[_0x5c3c94(0xf8)](_0x5c3c94(0xda))||undefined,'sqlName':_0x21c30f[_0x5c3c94(0xf8)](_0x5c3c94(0x114))||undefined});if(_0x3fb579['length']===0x0)return{'ok':!![],'data':{'pulled':[],'skipped':[],'failed':[]},'message':_0x5c3c94(0x115)};const _0x391c87=[],_0x4d4ed3=[];for(const _0x42c2c9 of _0x3fb579){try{_0x391c87['push'](await ensureSqlContent(_0x42c2c9));}catch(_0x5546f6){_0x4d4ed3[_0x5c3c94(0x119)]({'sqlCode':_0x42c2c9[_0x5c3c94(0x102)],'error':_0x5546f6 instanceof Error?_0x5546f6[_0x5c3c94(0xe8)]:String(_0x5546f6)});}}if(_0x263262&&!_0x21c30f['nonInteractive']){let _0x37818d=![];for(const _0x10e8ac of _0x391c87){const _0x403c42=detectSqlMode(ensureRemoteSqlContent(_0x10e8ac)),_0x129df7=_0x10e8ac[_0x5c3c94(0xed)]?await getDbName(_0x21c30f[_0x5c3c94(0xe5)],Number(_0x10e8ac['dbId']))[_0x5c3c94(0xe3)](()=>undefined):undefined,_0x2912f2=buildLocalSqlFileContent({'sqlCode':_0x10e8ac[_0x5c3c94(0x102)],'sqlName':_0x10e8ac[_0x5c3c94(0x11b)],'dbId':_0x10e8ac['dbId']},ensureRemoteSqlContent(_0x10e8ac),{'dbName':_0x129df7,'mode':_0x403c42,'syncedAt':new Date()['toISOString'](),'description':_0x10e8ac[_0x5c3c94(0x103)]}),_0x1cccca=resolveLocalSqlFilePath(_0xf1a3f9,_0x10e8ac['sqlCode'],buildSqlLockEntry(_0x10e8ac,ensureRemoteSqlContent(_0x10e8ac),'',{'dbName':_0x129df7})),_0x54e678=await findExistingSqlFiles(_0xf1a3f9,_0x1cccca,_0x403c42,_0x2d21a3[_0x5c3c94(0x120)][_0x10e8ac[_0x5c3c94(0x102)]]),_0xd05d9c=await compareExistingSqlFiles(_0x54e678,_0x2912f2,_0x403c42);if(_0xd05d9c[_0x5c3c94(0x122)](({equivalent:_0x4f14f3})=>!_0x4f14f3)){_0x37818d=!![];break;}}if(_0x37818d){const _0x147fa9=await confirmForceOverwrite(_0x5c3c94(0xdc));if(!_0x147fa9)throw CliErrors[_0x5c3c94(0x11a)](_0x5c3c94(0xe4));}}const _0x4cb0bf=cloneSqlLockData(_0x33483c),_0x88ef93=_0x4cb0bf[_0x5c3c94(0xf2)][_0xf1a3f9['appCode']],_0x2bcd40=[],_0x91d8a8=[];for(const _0x503c02 of _0x391c87){const _0x3de8d1=_0x88ef93[_0x5c3c94(0x120)][_0x503c02['sqlCode']],_0x22ad53=ensureRemoteSqlContent(_0x503c02),_0x5746fd=detectSqlMode(_0x22ad53),_0x332784=_0x503c02[_0x5c3c94(0xed)]?await getDbName(_0x21c30f[_0x5c3c94(0xe5)],Number(_0x503c02['dbId']))[_0x5c3c94(0xe3)](()=>undefined):undefined,_0x3ea262=buildLocalSqlFileContent({'sqlCode':_0x503c02['sqlCode'],'sqlName':_0x503c02[_0x5c3c94(0x11b)],'dbId':_0x503c02[_0x5c3c94(0xed)]},_0x22ad53,{'dbName':_0x332784,'mode':_0x5746fd,'syncedAt':new Date()[_0x5c3c94(0xf6)](),'description':_0x503c02['description']}),_0x5bd619=buildSqlLockEntry(_0x503c02,_0x22ad53,computeSqlContentHash(_0x3ea262),{'dbName':_0x332784}),_0x37bd4b=_0x5bd619[_0x5c3c94(0xf3)],_0x16818e=join(_0xf1a3f9['sqlRootDir'],_0x37bd4b);try{const _0x51d801=await findExistingSqlFiles(_0xf1a3f9,_0x16818e,_0x5746fd,_0x3de8d1),_0x11ceef=await compareExistingSqlFiles(_0x51d801,_0x3ea262,_0x5746fd);if(!_0x263262&&_0x11ceef[_0x5c3c94(0x122)](({equivalent:_0x307299})=>!_0x307299)){_0x91d8a8[_0x5c3c94(0x119)]({'sqlCode':_0x503c02[_0x5c3c94(0x102)],'reason':_0x5c3c94(0x123)});continue;}const _0x22c122=_0x11ceef[_0x5c3c94(0x111)](({file:_0x311fae})=>_0x311fae[_0x5c3c94(0xeb)]),_0xe3dd04=_0x11ceef[_0x5c3c94(0x111)](({file:_0x47b952})=>!_0x47b952[_0x5c3c94(0xeb)]);if(_0x22c122?.[_0x5c3c94(0xe1)]&&!_0xe3dd04){_0x91d8a8[_0x5c3c94(0x119)]({'sqlCode':_0x503c02[_0x5c3c94(0x102)],'reason':_0x5c3c94(0x10d)}),_0x88ef93[_0x5c3c94(0x120)][_0x503c02['sqlCode']]={..._0x5bd619,'hash':computeSqlContentHash(_0x22c122['content']),'path':_0x37bd4b};continue;}!_0x22c122?.['equivalent']&&(await ensureParentDirectory(_0x16818e),await writeFile(_0x16818e,_0x3ea262,'utf8')),_0xe3dd04&&await rm(_0xe3dd04[_0x5c3c94(0x10f)][_0x5c3c94(0x11f)],{'force':!![]}),_0x88ef93['sqls'][_0x503c02[_0x5c3c94(0x102)]]={..._0x5bd619,'hash':_0x22c122?.[_0x5c3c94(0xe1)]?computeSqlContentHash(_0x22c122['content']):_0x5bd619[_0x5c3c94(0x10b)],'path':_0x37bd4b},_0x2bcd40[_0x5c3c94(0x119)]({'sqlCode':_0x503c02[_0x5c3c94(0x102)],'filePath':_0x16818e});}catch(_0x18fd7a){_0x4d4ed3[_0x5c3c94(0x119)]({'sqlCode':_0x503c02[_0x5c3c94(0x102)],'error':_0x18fd7a instanceof Error?_0x18fd7a[_0x5c3c94(0xe8)]:String(_0x18fd7a)});}}return _0x88ef93['lastSync']=new Date()[_0x5c3c94(0xf6)](),await writeSqlLockFile(_0xf1a3f9[_0x5c3c94(0xff)],_0x4cb0bf),{'ok':_0x4d4ed3['length']===0x0,'data':{'pulled':_0x2bcd40,'skipped':_0x91d8a8,'failed':_0x4d4ed3},'message':_0x5c3c94(0x109)+_0x2bcd40['length']+_0x5c3c94(0x10a)+_0x91d8a8[_0x5c3c94(0xdb)]+_0x5c3c94(0x116)+_0x4d4ed3[_0x5c3c94(0xdb)]+_0x5c3c94(0x105)};}};function isEquivalentPulledSqlFile(_0x5cf53a,_0x517541,_0x2d4620,_0x395474){if(_0x2d4620!==_0x395474)return normalizePulledSqlBody(_0x5cf53a,_0x2d4620)===normalizePulledSqlBody(_0x517541,_0x395474);return normalizePullComparableContent(_0x5cf53a,_0x2d4620)===normalizePullComparableContent(_0x517541,_0x395474);}async function findExistingSqlFiles(_0x4b546f,_0x3bb64b,_0xf6aa29,_0xc4e467){const _0x5ddd01=a253_0x2d48fa,_0x2d821d=[];await fileExists(_0x3bb64b)&&_0x2d821d[_0x5ddd01(0x119)]({'filePath':_0x3bb64b,'mode':_0xf6aa29,'isCanonical':!![]});if(!_0xc4e467?.[_0x5ddd01(0xf3)])return _0x2d821d;const _0x22e20d=join(_0x4b546f[_0x5ddd01(0x11d)],_0xc4e467[_0x5ddd01(0xf3)]);if(_0x22e20d===_0x3bb64b)return _0x2d821d;return await fileExists(_0x22e20d)&&_0x2d821d['push']({'filePath':_0x22e20d,'mode':_0xc4e467[_0x5ddd01(0xef)]??modeFromFilePath(_0x22e20d),'isCanonical':![]}),_0x2d821d;}async function compareExistingSqlFiles(_0x23ce1d,_0x1f83f4,_0x27fa07){const _0x32560d=a253_0x2d48fa;return Promise[_0x32560d(0xf5)](_0x23ce1d[_0x32560d(0xec)](async _0x2736b6=>{const _0x5eeb51=_0x32560d,_0x1f8f55=await readFile(_0x2736b6['filePath'],_0x5eeb51(0x10e));return{'file':_0x2736b6,'content':_0x1f8f55,'equivalent':isEquivalentPulledSqlFile(_0x1f8f55,_0x1f83f4,_0x2736b6[_0x5eeb51(0xef)],_0x27fa07)};}));}function modeFromFilePath(_0x50565b){const _0x281439=a253_0x2d48fa;return _0x50565b[_0x281439(0x118)]()[_0x281439(0x121)]('.xml')?_0x281439(0xea):_0x281439(0x117);}function normalizePulledSqlBody(_0x5108ee,_0x7d628d){const _0x2f7db1=a253_0x2d48fa;return stripLocalSqlMetadata(_0x5108ee,_0x7d628d)[_0x2f7db1(0xdd)](/\r\n/g,'\x0a')[_0x2f7db1(0xd9)]();}function normalizePullComparableContent(_0x2ba3a1,_0x36ce3d){const _0x202c40=a253_0x2d48fa,_0x52df18=_0x2ba3a1['replace'](/\r\n/g,'\x0a')[_0x202c40(0xe0)]('\x0a'),_0x1eccfe=_0x52df18[_0x202c40(0xe2)](_0xe44f06=>!isSyncedAtMetadataLine(_0xe44f06,_0x36ce3d));return _0x1eccfe[_0x202c40(0xf9)]('\x0a');}function isSyncedAtMetadataLine(_0x251aed,_0x3c4243){const _0xb37b96=a253_0x2d48fa;if(_0x3c4243===_0xb37b96(0xea))return/^\s*<!--\s*@lovrabet\.syncedAt:/[_0xb37b96(0x11e)](_0x251aed);return/^\s*--\s*@lovrabet\.syncedAt:/[_0xb37b96(0x11e)](_0x251aed);}
|
|
1
|
+
import{readFile,rm,writeFile}from"node:fs/promises";import{join}from"node:path";import{getSqlQueryDetail,listSqlQueries}from"../../core/api-client.js";import{ensureParentDirectory,fileExists}from"../../core/bff/file-system.js";import{getDbName}from"../../core/db-resolver.js";import{loadSqlProjectConfig}from"../../core/sql-sync/config.js";import{computeSqlContentHash}from"../../core/sql-sync/hash.js";import{createEmptySqlLock,ensureSqlLockScope,readSqlLockFile,writeSqlLockFile}from"../../core/sql-sync/lock.js";import{resolveLocalSqlFilePath}from"../../core/sql-sync/file-system.js";import{detectSqlMode}from"../../core/sql-sync/utils.js";import{CliErrors}from"../../errors.js";import{SQLCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{buildLocalSqlFileContent,buildSqlLockEntry,cloneSqlLockData,confirmForceOverwrite,ensureRemoteSqlContent,stripLocalSqlMetadata}from"./shared.js";const PAGE_SIZE=100;async function fetchAllSqlQueries(appCode,filters){const out=[];let page=1
|
|
2
|
+
;while(true){const r=await listSqlQueries(appCode,{currentPage:page,pageSize:PAGE_SIZE,sqlCode:filters.sqlCode,sqlName:filters.sqlName});const batch=r.tableData??[];out.push(...batch);if(batch.length===0)break;const total=r.paging?.totalCount;if(total!=null?out.length>=total:batch.length<PAGE_SIZE){break}page++}return out}async function ensureSqlContent(sql){if(sql.sqlContent!=null&&String(sql.sqlContent).length>0){return sql}return getSqlQueryDetail(sql.sqlCode)}export const sqlPull={service:"sql",command:"pull",description:"Pull remote SQL queries to local .rabetbase/sql/",risk:"read",flags:[SQLCODE_FLAG_OPTIONAL,{name:"name",type:"string",description:"Filter by SQL display name"},{name:"force",type:"boolean",description:"Force overwrite local unsynced changes"}],async dryRun(ctx){const config=loadSqlProjectConfig(ctx.appCode);const rawLock=await readSqlLockFile(config.lockFilePath)
|
|
3
|
+
;const{appLock:appLock}=ensureSqlLockScope(rawLock??createEmptySqlLock(),config.appCode,config.sqlRoot,"pull");const sqls=await fetchAllSqlQueries(ctx.appCode,{sqlCode:ctx.str("sqlcode")||undefined,sqlName:ctx.str("name")||undefined});const files=[];for(const row of sqls){const sql=await ensureSqlContent(row);const content=ensureRemoteSqlContent(sql);const mode=detectSqlMode(content);const dbName=sql.dbId?await getDbName(ctx.appCode,Number(sql.dbId)).catch(()=>undefined):undefined;const localFileContent=buildLocalSqlFileContent({sqlCode:sql.sqlCode,sqlName:sql.sqlName,dbId:sql.dbId},content,{dbName:dbName,mode:mode,syncedAt:(new Date).toISOString(),description:sql.description});const canonicalEntry=buildSqlLockEntry(sql,content,"",{dbName:dbName});const filePath=resolveLocalSqlFilePath(config,sql.sqlCode,canonicalEntry);let status="would_pull";let reason;const existingFiles=await findExistingSqlFiles(config,filePath,mode,appLock.sqls[sql.sqlCode]);if(existingFiles.length>0){
|
|
4
|
+
const comparisons=await compareExistingSqlFiles(existingFiles,localFileContent,mode);if(comparisons.some(({equivalent:equivalent})=>!equivalent)){status="conflict";reason="local differs from remote (use --force to overwrite)"}else if(comparisons.length===1&&comparisons[0]?.file.isCanonical){status="skipped";reason="unchanged"}}files.push({sqlCode:sql.sqlCode,sqlName:sql.sqlName,filePath:filePath,status:status,reason:reason})}return{method:"POST",url:"/smartapi/custom/queryUserCustomSqlList + /smartapi/custom/getUserCustomSql",body:{appCode:ctx.appCode,sqlCode:ctx.str("sqlcode")||null,sqlName:ctx.str("name")||null,files:files},description:`Would pull ${files.length} SQL file(s) into ${config.sqlRootDir}`}},async execute(ctx){const config=loadSqlProjectConfig(ctx.appCode);const rawLock=await readSqlLockFile(config.lockFilePath);const{lockData:lockData,appLock:appLock}=ensureSqlLockScope(rawLock??createEmptySqlLock(),config.appCode,config.sqlRoot,"pull");const force=ctx.bool("force")
|
|
5
|
+
;const sqls=await fetchAllSqlQueries(ctx.appCode,{sqlCode:ctx.str("sqlcode")||undefined,sqlName:ctx.str("name")||undefined});if(sqls.length===0){return{ok:true,data:{pulled:[],skipped:[],failed:[]},message:"No remote SQL queries matched."}}const detailedSqls=[];const failed=[];for(const row of sqls){try{detailedSqls.push(await ensureSqlContent(row))}catch(error){failed.push({sqlCode:row.sqlCode,error:error instanceof Error?error.message:String(error)})}}if(force&&!ctx.nonInteractive){let hasOverwrite=false;for(const sql of detailedSqls){const mode=detectSqlMode(ensureRemoteSqlContent(sql));const dbName=sql.dbId?await getDbName(ctx.appCode,Number(sql.dbId)).catch(()=>undefined):undefined;const localFileContent=buildLocalSqlFileContent({sqlCode:sql.sqlCode,sqlName:sql.sqlName,dbId:sql.dbId},ensureRemoteSqlContent(sql),{dbName:dbName,mode:mode,syncedAt:(new Date).toISOString(),description:sql.description})
|
|
6
|
+
;const filePath=resolveLocalSqlFilePath(config,sql.sqlCode,buildSqlLockEntry(sql,ensureRemoteSqlContent(sql),"",{dbName:dbName}));const existingFiles=await findExistingSqlFiles(config,filePath,mode,appLock.sqls[sql.sqlCode]);const comparisons=await compareExistingSqlFiles(existingFiles,localFileContent,mode);if(comparisons.some(({equivalent:equivalent})=>!equivalent)){hasOverwrite=true;break}}if(hasOverwrite){const confirmed=await confirmForceOverwrite("Force pull will overwrite local SQL that differs from remote.");if(!confirmed){throw CliErrors.cancelled("Force pull cancelled.")}}}const nextLockData=cloneSqlLockData(lockData);const nextAppLock=nextLockData.apps[config.appCode];const pulled=[];const skipped=[];for(const sql of detailedSqls){const lockEntry=nextAppLock.sqls[sql.sqlCode];const sqlContent=ensureRemoteSqlContent(sql);const mode=detectSqlMode(sqlContent);const dbName=sql.dbId?await getDbName(ctx.appCode,Number(sql.dbId)).catch(()=>undefined):undefined
|
|
7
|
+
;const localFileContent=buildLocalSqlFileContent({sqlCode:sql.sqlCode,sqlName:sql.sqlName,dbId:sql.dbId},sqlContent,{dbName:dbName,mode:mode,syncedAt:(new Date).toISOString(),description:sql.description});const canonicalEntry=buildSqlLockEntry(sql,sqlContent,computeSqlContentHash(localFileContent),{dbName:dbName});const fileName=canonicalEntry.path;const filePath=join(config.sqlRootDir,fileName);try{const existingFiles=await findExistingSqlFiles(config,filePath,mode,lockEntry);const comparisons=await compareExistingSqlFiles(existingFiles,localFileContent,mode);if(!force&&comparisons.some(({equivalent:equivalent})=>!equivalent)){skipped.push({sqlCode:sql.sqlCode,reason:"local differs from remote"});continue}const canonicalComparison=comparisons.find(({file:file})=>file.isCanonical);const previousComparison=comparisons.find(({file:file})=>!file.isCanonical);if(canonicalComparison?.equivalent&&!previousComparison){skipped.push({sqlCode:sql.sqlCode,reason:"unchanged"})
|
|
8
|
+
;nextAppLock.sqls[sql.sqlCode]={...canonicalEntry,hash:computeSqlContentHash(canonicalComparison.content),path:fileName};continue}if(!canonicalComparison?.equivalent){await ensureParentDirectory(filePath);await writeFile(filePath,localFileContent,"utf8")}if(previousComparison){await rm(previousComparison.file.filePath,{force:true})}nextAppLock.sqls[sql.sqlCode]={...canonicalEntry,hash:canonicalComparison?.equivalent?computeSqlContentHash(canonicalComparison.content):canonicalEntry.hash,path:fileName};pulled.push({sqlCode:sql.sqlCode,filePath:filePath})}catch(error){failed.push({sqlCode:sql.sqlCode,error:error instanceof Error?error.message:String(error)})}}nextAppLock.lastSync=(new Date).toISOString();await writeSqlLockFile(config.lockFilePath,nextLockData);return{ok:failed.length===0,data:{pulled:pulled,skipped:skipped,failed:failed},message:`Pull complete: ${pulled.length} written, ${skipped.length} skipped, ${failed.length} failed`}}}
|
|
9
|
+
;function isEquivalentPulledSqlFile(localContent,generatedContent,localMode,generatedMode){if(localMode!==generatedMode){return normalizePulledSqlBody(localContent,localMode)===normalizePulledSqlBody(generatedContent,generatedMode)}return normalizePullComparableContent(localContent,localMode)===normalizePullComparableContent(generatedContent,generatedMode)}async function findExistingSqlFiles(config,canonicalFilePath,canonicalMode,lockEntry){const files=[];if(await fileExists(canonicalFilePath)){files.push({filePath:canonicalFilePath,mode:canonicalMode,isCanonical:true})}if(!lockEntry?.path){return files}const previousFilePath=join(config.sqlRootDir,lockEntry.path);if(previousFilePath===canonicalFilePath){return files}if(await fileExists(previousFilePath)){files.push({filePath:previousFilePath,mode:lockEntry.mode??modeFromFilePath(previousFilePath),isCanonical:false})}return files}async function compareExistingSqlFiles(files,generatedContent,generatedMode){
|
|
10
|
+
return Promise.all(files.map(async file=>{const content=await readFile(file.filePath,"utf8");return{file:file,content:content,equivalent:isEquivalentPulledSqlFile(content,generatedContent,file.mode,generatedMode)}}))}function modeFromFilePath(filePath){return filePath.toLowerCase().endsWith(".xml")?"mybatisXml":"sql"}function normalizePulledSqlBody(content,mode){return stripLocalSqlMetadata(content,mode).replace(/\r\n/g,"\n").trim()}function normalizePullComparableContent(content,mode){const lines=content.replace(/\r\n/g,"\n").split("\n");const filtered=lines.filter(line=>!isSyncedAtMetadataLine(line,mode));return filtered.join("\n")}function isSyncedAtMetadataLine(line,mode){if(mode==="mybatisXml"){return/^\s*<!--\s*@lovrabet\.syncedAt:/.test(line)}return/^\s*--\s*@lovrabet\.syncedAt:/.test(line)}
|
package/lib/commands/sql/push.js
CHANGED
|
@@ -1 +1,9 @@
|
|
|
1
|
-
const a254_0x11d5d5=a254_0x2cd4;(function(_0x218ebf,_0x341f9f){const _0x3b61ca=a254_0x2cd4,_0x77cd07=_0x218ebf();while(!![]){try{const _0x3c1dec=-parseInt(_0x3b61ca(0x192))/0x1*(-parseInt(_0x3b61ca(0x178))/0x2)+-parseInt(_0x3b61ca(0x1a0))/0x3*(-parseInt(_0x3b61ca(0x160))/0x4)+parseInt(_0x3b61ca(0x189))/0x5+parseInt(_0x3b61ca(0x19f))/0x6*(-parseInt(_0x3b61ca(0x188))/0x7)+parseInt(_0x3b61ca(0x16c))/0x8*(parseInt(_0x3b61ca(0x1aa))/0x9)+parseInt(_0x3b61ca(0x186))/0xa+-parseInt(_0x3b61ca(0x163))/0xb*(parseInt(_0x3b61ca(0x199))/0xc);if(_0x3c1dec===_0x341f9f)break;else _0x77cd07['push'](_0x77cd07['shift']());}catch(_0x5a0711){_0x77cd07['push'](_0x77cd07['shift']());}}}(a254_0x3f1e,0x7de0c));import{mkdir,readFile,readdir,rename,rmdir}from'node:fs/promises';function a254_0x3f1e(){const _0x421c26=['No\x20database\x20matches\x20local\x20directory\x20\x22','appCode','path','hash','\x22\x20matches\x20multiple\x20databases\x20for\x20sqlCode\x20','3778644OpiqdS','Would\x20push\x20','toISOString','version','dbName','filePath','2676846sUkWpm','18npccdU',':\x20local\x20SQL\x20is\x20not\x20tracked;\x20run\x20sql\x20create\x20or\x20sql\x20pull\x20first.','sqlcode','Multiple\x20local\x20SQL\x20files\x20found\x20for\x20sqlCode\x20','remoteId','replace','Local\x20directory\x20\x22','POST','local\x20SQL\x20is\x20not\x20tracked\x20by\x20sql.lock.json;\x20use\x20`rabetbase\x20sql\x20create`\x20or\x20`rabetbase\x20sql\x20pull`\x20first','dbId','72rWnyDM','startsWith','115516VCfluR','sqls','\x20SQL\x20file(s)','44xZyAtd','bool','unchanged','join','projectRoot','length','dbDirectory','exec','lockFilePath','1013768GGtyRD','/smartapi/custom/updateUserCustomSql','sql',':\x20SQL\x20content\x20is\x20empty.','\x20pushed,\x20','utf8','\x20failed','filter','set','catch','.\x20Keep\x20only\x20one\x20file\x20under\x20its\x20sqlCode\x20directory\x20before\x20pushing.','\x20skipped,\x20','2KVlYBP','Local\x20SQL\x20not\x20found:\x20','sqlConfig','force','Push\x20local\x20SQL\x20files\x20to\x20remote','map',':\x20missing\x20remote\x20version;\x20run\x20sql\x20pull\x20first.','write','relativePath','missing\x20remote\x20version;\x20run\x20`rabetbase\x20sql\x20pull`\x20to\x20refresh\x20version\x20info\x20first','isFinite','push','validation','sqlName','1581670WspzhV','str','7krZnUJ','1079795nAHAef','Force\x20push\x20even\x20if\x20local\x20hash\x20matches\x20lock','sqlCode','boolean','sqlRoot','Push\x20complete:\x20','has','mode','trashDir','660117CzhkXk','sqlRootDir'];a254_0x3f1e=function(){return _0x421c26;};return a254_0x3f1e();}import{dirname,join,relative,resolve,sep}from'node:path';import{updateSqlQuery}from'../../core/api-client.js';import{loadSqlProjectConfig}from'../../core/sql-sync/config.js';import{getDbName,listDatabases}from'../../core/db-resolver.js';import{scanLocalSqlQueries}from'../../core/sql-sync/file-system.js';import{computeSqlFileHash}from'../../core/sql-sync/hash.js';import{createEmptySqlLock,ensureSqlLockScope,readSqlLockFile,writeSqlLockFile}from'../../core/sql-sync/lock.js';import{fileExists}from'../../core/bff/file-system.js';import{CliErrors}from'../../errors.js';import{SQLCODE_FLAG_OPTIONAL}from'../../commands/common/flags.js';import{buildSqlLockEntry,stripLocalSqlMetadata}from'./shared.js';import{buildDbDirectoryName}from'../../core/sql-sync/utils.js';async function readSqlUploadContent(_0xc92804){const _0x3ae132=a254_0x2cd4,_0x2578f8=stripLocalSqlMetadata(await readFile(_0xc92804[_0x3ae132(0x19e)],_0x3ae132(0x171)),_0xc92804['mode']);if(!_0x2578f8['trim']())throw CliErrors[_0x3ae132(0x184)](_0xc92804[_0x3ae132(0x18b)]+_0x3ae132(0x16f));return _0x2578f8;}async function getTargetSqlQueries(_0x57fd09,_0x88aa74,_0x194f93){const _0x4a5659=a254_0x2cd4,_0x2a1835=await scanLocalSqlQueries(_0x57fd09),_0xe9f35e=new Map();for(const _0x46c963 of _0x2a1835){if(_0x194f93&&_0x46c963[_0x4a5659(0x18b)]!==_0x194f93)continue;const _0x3ce757=_0xe9f35e['get'](_0x46c963[_0x4a5659(0x18b)])??[];_0x3ce757[_0x4a5659(0x183)](_0x46c963),_0xe9f35e[_0x4a5659(0x174)](_0x46c963['sqlCode'],_0x3ce757);}if(_0x194f93&&!_0xe9f35e[_0x4a5659(0x18f)](_0x194f93))throw CliErrors[_0x4a5659(0x184)](_0x4a5659(0x179)+_0x194f93);const _0x3f8ac1=[];for(const [_0x14f865,_0x257ffc]of _0xe9f35e['entries']()){if(_0x257ffc[_0x4a5659(0x168)]===0x1){_0x3f8ac1[_0x4a5659(0x183)](_0x257ffc[0x0]);continue;}const _0x25b5b8=_0x88aa74[_0x4a5659(0x161)][_0x14f865],_0x43e003=_0x25b5b8?.[_0x4a5659(0x196)],_0x26198b=_0x43e003?_0x257ffc[_0x4a5659(0x173)](_0x106220=>_0x106220[_0x4a5659(0x180)]!==_0x43e003):_0x257ffc;if(_0x25b5b8&&_0x26198b[_0x4a5659(0x168)]===0x1){_0x3f8ac1[_0x4a5659(0x183)](_0x26198b[0x0]);continue;}throw CliErrors[_0x4a5659(0x184)](_0x4a5659(0x1a3)+_0x14f865+_0x4a5659(0x176));}return _0x3f8ac1;}function a254_0x2cd4(_0x3d092c,_0x3fef53){_0x3d092c=_0x3d092c-0x160;const _0x3f1e41=a254_0x3f1e();let _0x2cd402=_0x3f1e41[_0x3d092c];return _0x2cd402;}export const sqlPush={'service':a254_0x11d5d5(0x16e),'command':a254_0x11d5d5(0x183),'description':a254_0x11d5d5(0x17c),'risk':a254_0x11d5d5(0x17f),'flags':[SQLCODE_FLAG_OPTIONAL,{'name':a254_0x11d5d5(0x17b),'type':a254_0x11d5d5(0x18c),'description':a254_0x11d5d5(0x18a)}],async 'dryRun'(_0x4d1180){const _0xa12430=a254_0x11d5d5,_0x45e692=loadSqlProjectConfig(_0x4d1180[_0xa12430(0x195)]),_0x29802c=await readSqlLockFile(_0x45e692[_0xa12430(0x16b)]),{appLock:_0x2aa239}=ensureSqlLockScope(_0x29802c??createEmptySqlLock(),_0x4d1180['appCode'],_0x45e692['sqlRoot'],_0xa12430(0x183)),_0x5154f8=await getTargetSqlQueries(_0x45e692,_0x2aa239,_0x4d1180[_0xa12430(0x187)](_0xa12430(0x1a2))||undefined),_0xc48430=[];for(const _0x3f17ad of _0x5154f8){const _0x175e0c=await computeSqlFileHash(_0x3f17ad['filePath']),_0x15becd=_0x2aa239[_0xa12430(0x161)][_0x3f17ad[_0xa12430(0x18b)]],_0x25e031=!!_0x15becd&&(_0x15becd[_0xa12430(0x196)]!==_0x3f17ad[_0xa12430(0x180)]||!!_0x3f17ad['sqlName']&&_0x15becd['sqlName']!==_0x3f17ad[_0xa12430(0x185)]||_0x15becd[_0xa12430(0x190)]!==_0x3f17ad[_0xa12430(0x190)]);if(!_0x4d1180[_0xa12430(0x164)](_0xa12430(0x17b))&&_0x15becd&&_0x15becd['hash']===_0x175e0c&&!_0x25e031)continue;if(!_0x15becd)throw CliErrors[_0xa12430(0x184)](_0x3f17ad[_0xa12430(0x18b)]+_0xa12430(0x1a1));if(_0x15becd[_0xa12430(0x19c)]==null)throw CliErrors[_0xa12430(0x184)](_0x3f17ad[_0xa12430(0x18b)]+_0xa12430(0x17e));await resolveTargetDbBinding(_0x4d1180[_0xa12430(0x195)],_0x3f17ad,_0x15becd),await readSqlUploadContent(_0x3f17ad),_0xc48430[_0xa12430(0x183)](_0x3f17ad[_0xa12430(0x18b)]);}return{'method':_0xa12430(0x1a7),'url':_0xa12430(0x16d),'body':{'sqlCodes':_0xc48430,'appCode':_0x4d1180[_0xa12430(0x195)]},'description':_0xa12430(0x19a)+_0xc48430[_0xa12430(0x168)]+_0xa12430(0x162)};},async 'execute'(_0x18c61e){const _0x276003=a254_0x11d5d5,_0x369c46=loadSqlProjectConfig(_0x18c61e['appCode']),_0x5bdcb7=await readSqlLockFile(_0x369c46['lockFilePath']),{lockData:_0x2be724,appLock:_0x50075d}=ensureSqlLockScope(_0x5bdcb7??createEmptySqlLock(),_0x18c61e['appCode'],_0x369c46[_0x276003(0x18d)],_0x276003(0x183)),_0xaf62fc=await getTargetSqlQueries(_0x369c46,_0x50075d,_0x18c61e[_0x276003(0x187)](_0x276003(0x1a2))||undefined);if(_0xaf62fc['length']===0x0)return{'ok':!![],'data':{'pushed':[],'skipped':[],'failed':[]},'message':'No\x20local\x20SQL\x20files\x20found.'};const _0x1e8c1c=[],_0x4eee12=[],_0x583f0d=[];let _0x247c7f=![];for(const _0x10da79 of _0xaf62fc){const _0xa95907=_0x50075d[_0x276003(0x161)][_0x10da79[_0x276003(0x18b)]];if(!_0xa95907){_0x583f0d['push']({'sqlCode':_0x10da79['sqlCode'],'error':_0x276003(0x1a8)});continue;}try{const _0x3b9cbe=await computeSqlFileHash(_0x10da79[_0x276003(0x19e)]),_0x992681=_0xa95907['path']!==_0x10da79[_0x276003(0x180)]||!!_0x10da79['sqlName']&&_0xa95907[_0x276003(0x185)]!==_0x10da79[_0x276003(0x185)]||_0xa95907[_0x276003(0x190)]!==_0x10da79[_0x276003(0x190)];if(!_0x18c61e[_0x276003(0x164)]('force')&&_0xa95907[_0x276003(0x197)]===_0x3b9cbe&&!_0x992681){_0x4eee12[_0x276003(0x183)]({'sqlCode':_0x10da79[_0x276003(0x18b)],'reason':_0x276003(0x165)});continue;}if(_0xa95907['version']==null){_0x583f0d[_0x276003(0x183)]({'sqlCode':_0x10da79[_0x276003(0x18b)],'error':_0x276003(0x181)});continue;}const _0x2f338b=_0x10da79[_0x276003(0x185)]||_0xa95907[_0x276003(0x185)],_0x3ab178=await resolveTargetDbBinding(_0x18c61e[_0x276003(0x195)],_0x10da79,_0xa95907),_0x45d995=await readSqlUploadContent(_0x10da79),_0x35557f=await updateSqlQuery({'id':_0xa95907['remoteId'],'appCode':_0x18c61e[_0x276003(0x195)],'sqlCode':_0x10da79[_0x276003(0x18b)],'sqlName':_0x2f338b,'dbId':_0x3ab178[_0x276003(0x1a9)],'version':_0xa95907[_0x276003(0x19c)],'sqlContent':_0x45d995,'sqlConfig':_0xa95907[_0x276003(0x17a)]??undefined}),_0x13c10f=_0x35557f['dbId']?await getDbName(_0x18c61e[_0x276003(0x195)],Number(_0x35557f[_0x276003(0x1a9)]))['catch'](()=>_0x3ab178[_0x276003(0x19d)]):_0x3ab178[_0x276003(0x19d)];_0x50075d[_0x276003(0x161)][_0x10da79[_0x276003(0x18b)]]={...buildSqlLockEntry(_0x35557f,_0x45d995,_0x3b9cbe,{'dbName':_0x13c10f}),'path':_0x10da79['relativePath'],'mode':_0x10da79['mode']},_0x247c7f=!![],await archivePreviousSqlFileIfNeeded(_0x369c46,_0xa95907['path'],_0x10da79[_0x276003(0x180)]),_0x1e8c1c['push']({'sqlCode':_0x10da79[_0x276003(0x18b)],'remoteId':_0xa95907[_0x276003(0x1a4)]});}catch(_0x4b4948){_0x583f0d[_0x276003(0x183)]({'sqlCode':_0x10da79[_0x276003(0x18b)],'error':_0x4b4948 instanceof Error?_0x4b4948['message']:String(_0x4b4948)});}}(_0x247c7f||_0x583f0d[_0x276003(0x168)]===0x0)&&(_0x50075d['lastSync']=new Date()[_0x276003(0x19b)](),await writeSqlLockFile(_0x369c46[_0x276003(0x16b)],_0x2be724));const _0x268548=_0x583f0d[_0x276003(0x168)]===0x0;return{'ok':_0x268548,'data':{'pushed':_0x1e8c1c,'skipped':_0x4eee12,'failed':_0x583f0d},'message':_0x276003(0x18e)+_0x1e8c1c['length']+_0x276003(0x170)+_0x4eee12[_0x276003(0x168)]+_0x276003(0x177)+_0x583f0d[_0x276003(0x168)]+_0x276003(0x172)};}};async function archivePreviousSqlFileIfNeeded(_0x4d9279,_0x5d7a3f,_0x1d2601){const _0x32b108=a254_0x11d5d5;if(!_0x5d7a3f||_0x5d7a3f===_0x1d2601)return;const _0xfef873=join(_0x4d9279[_0x32b108(0x193)],_0x5d7a3f);if(!await fileExists(_0xfef873))return;const _0x188281=await moveToTrash(_0x4d9279[_0x32b108(0x167)],_0x4d9279[_0x32b108(0x191)],_0xfef873);await cleanupEmptyDirectories(dirname(_0xfef873),_0x4d9279['sqlRootDir']),void _0x188281;}async function moveToTrash(_0x1ec3bc,_0xe1557d,_0x225ad8){const _0x51532d=a254_0x11d5d5,_0x21bd28=new Date()['toISOString']()[_0x51532d(0x1a5)](/[:.]/g,'-'),_0x4861dc=relative(_0x1ec3bc,_0x225ad8),_0x297fb8=join(_0xe1557d,_0x21bd28,_0x4861dc);return await mkdir(dirname(_0x297fb8),{'recursive':!![]}),await rename(_0x225ad8,_0x297fb8),_0x297fb8;}async function cleanupEmptyDirectories(_0x1689cb,_0x2f5270){const _0x34d2d9=a254_0x11d5d5;let _0x42d6d2=resolve(_0x1689cb);const _0x5e2b45=resolve(_0x2f5270);while(_0x42d6d2[_0x34d2d9(0x1ab)](''+_0x5e2b45+sep)||_0x42d6d2===_0x5e2b45){if(_0x42d6d2===_0x5e2b45)return;try{const _0x970d0b=await readdir(_0x42d6d2);if(_0x970d0b[_0x34d2d9(0x168)]>0x0)return;await rmdir(_0x42d6d2);}catch{return;}_0x42d6d2=dirname(_0x42d6d2);}}async function resolveTargetDbBinding(_0x3cd2b3,_0x33ca71,_0x5c01f5){const _0x3afb2f=a254_0x11d5d5,_0x2e6eb6=_0x33ca71[_0x3afb2f(0x169)];if(!_0x2e6eb6)return{'dbId':_0x5c01f5[_0x3afb2f(0x1a9)],'dbName':_0x5c01f5[_0x3afb2f(0x19d)]};const _0x2458ec=buildDbDirectoryName(_0x5c01f5['dbName'],_0x5c01f5['dbId']);if(_0x2e6eb6===_0x2458ec)return{'dbId':_0x5c01f5[_0x3afb2f(0x1a9)],'dbName':_0x5c01f5[_0x3afb2f(0x19d)]};const _0x554b76=parseExplicitDbDirectory(_0x2e6eb6);if(_0x554b76!=null)return{'dbId':_0x554b76,'dbName':await getDbName(_0x3cd2b3,_0x554b76)[_0x3afb2f(0x175)](()=>undefined)};const _0x3fe788=await listDatabases(_0x3cd2b3),_0x24a6d0=_0x3fe788[_0x3afb2f(0x173)](_0x5227a9=>buildDbDirectoryName(_0x5227a9['dbName'],_0x5227a9[_0x3afb2f(0x1a9)])===_0x2e6eb6);if(_0x24a6d0['length']===0x1)return{'dbId':_0x24a6d0[0x0][_0x3afb2f(0x1a9)],'dbName':_0x24a6d0[0x0]['dbName']};if(_0x24a6d0['length']===0x0)throw CliErrors[_0x3afb2f(0x184)](_0x3afb2f(0x194)+_0x2e6eb6+'\x22\x20for\x20sqlCode\x20'+_0x33ca71['sqlCode']+'.');const _0x5e433d=_0x24a6d0[_0x3afb2f(0x17d)](_0x13be37=>_0x13be37[_0x3afb2f(0x19d)]+'\x20('+_0x13be37['dbId']+')')[_0x3afb2f(0x166)](',\x20');throw CliErrors['validation'](_0x3afb2f(0x1a6)+_0x2e6eb6+_0x3afb2f(0x198)+_0x33ca71[_0x3afb2f(0x18b)]+':\x20'+_0x5e433d);}function parseExplicitDbDirectory(_0x2bed38){const _0x5db10c=a254_0x11d5d5,_0x41b482=/^db-(\d+)$/[_0x5db10c(0x16a)](_0x2bed38);if(!_0x41b482)return null;const _0x13c4ac=Number(_0x41b482[0x1]);return Number[_0x5db10c(0x182)](_0x13c4ac)&&_0x13c4ac>0x0?_0x13c4ac:null;}
|
|
1
|
+
import{mkdir,readFile,readdir,rename,rmdir}from"node:fs/promises";import{dirname,join,relative,resolve,sep}from"node:path";import{updateSqlQuery}from"../../core/api-client.js";import{loadSqlProjectConfig}from"../../core/sql-sync/config.js";import{getDbName,listDatabases}from"../../core/db-resolver.js";import{scanLocalSqlQueries}from"../../core/sql-sync/file-system.js";import{computeSqlFileHash}from"../../core/sql-sync/hash.js";import{createEmptySqlLock,ensureSqlLockScope,readSqlLockFile,writeSqlLockFile}from"../../core/sql-sync/lock.js";import{fileExists}from"../../core/bff/file-system.js";import{CliErrors}from"../../errors.js";import{SQLCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{buildSqlLockEntry,stripLocalSqlMetadata}from"./shared.js";import{buildDbDirectoryName}from"../../core/sql-sync/utils.js";async function readSqlUploadContent(item){const content=stripLocalSqlMetadata(await readFile(item.filePath,"utf8"),item.mode)
|
|
2
|
+
;if(!content.trim())throw CliErrors.validation(`${item.sqlCode}: SQL content is empty.`);return content}async function getTargetSqlQueries(config,appLock,sqlCode){const localSqls=await scanLocalSqlQueries(config);const grouped=new Map;for(const item of localSqls){if(sqlCode&&item.sqlCode!==sqlCode)continue;const existing=grouped.get(item.sqlCode)??[];existing.push(item);grouped.set(item.sqlCode,existing)}if(sqlCode&&!grouped.has(sqlCode)){throw CliErrors.validation(`Local SQL not found: ${sqlCode}`)}const resolved=[];for(const[currentSqlCode,items]of grouped.entries()){if(items.length===1){resolved.push(items[0]);continue}const lockEntry=appLock.sqls[currentSqlCode];const currentPath=lockEntry?.path;const renameCandidates=currentPath?items.filter(item=>item.relativePath!==currentPath):items;if(lockEntry&&renameCandidates.length===1){resolved.push(renameCandidates[0]);continue}
|
|
3
|
+
throw CliErrors.validation(`Multiple local SQL files found for sqlCode ${currentSqlCode}. Keep only one file under its sqlCode directory before pushing.`)}return resolved}export const sqlPush={service:"sql",command:"push",description:"Push local SQL files to remote",risk:"write",flags:[SQLCODE_FLAG_OPTIONAL,{name:"force",type:"boolean",description:"Force push even if local hash matches lock"}],async dryRun(ctx){const config=loadSqlProjectConfig(ctx.appCode);const rawLock=await readSqlLockFile(config.lockFilePath);const{appLock:appLock}=ensureSqlLockScope(rawLock??createEmptySqlLock(),ctx.appCode,config.sqlRoot,"push");const localSqls=await getTargetSqlQueries(config,appLock,ctx.str("sqlcode")||undefined);const preview=[];for(const item of localSqls){const hash=await computeSqlFileHash(item.filePath);const lockEntry=appLock.sqls[item.sqlCode]
|
|
4
|
+
;const renameDetected=!!lockEntry&&(lockEntry.path!==item.relativePath||!!item.sqlName&&lockEntry.sqlName!==item.sqlName||lockEntry.mode!==item.mode);if(!ctx.bool("force")&&lockEntry&&lockEntry.hash===hash&&!renameDetected)continue;if(!lockEntry)throw CliErrors.validation(`${item.sqlCode}: local SQL is not tracked; run sql create or sql pull first.`);if(lockEntry.version==null)throw CliErrors.validation(`${item.sqlCode}: missing remote version; run sql pull first.`);await resolveTargetDbBinding(ctx.appCode,item,lockEntry);await readSqlUploadContent(item);preview.push(item.sqlCode)}return{method:"POST",url:"/smartapi/custom/updateUserCustomSql",body:{sqlCodes:preview,appCode:ctx.appCode},description:`Would push ${preview.length} SQL file(s)`}},async execute(ctx){const config=loadSqlProjectConfig(ctx.appCode);const rawLock=await readSqlLockFile(config.lockFilePath);const{lockData:lockData,appLock:appLock}=ensureSqlLockScope(rawLock??createEmptySqlLock(),ctx.appCode,config.sqlRoot,"push")
|
|
5
|
+
;const localSqls=await getTargetSqlQueries(config,appLock,ctx.str("sqlcode")||undefined);if(localSqls.length===0){return{ok:true,data:{pushed:[],skipped:[],failed:[]},message:"No local SQL files found."}}const pushed=[];const skipped=[];const failed=[];let lockChanged=false;for(const item of localSqls){const lockEntry=appLock.sqls[item.sqlCode];if(!lockEntry){failed.push({sqlCode:item.sqlCode,error:"local SQL is not tracked by sql.lock.json; use `rabetbase sql create` or `rabetbase sql pull` first"});continue}try{const localHash=await computeSqlFileHash(item.filePath);const renameDetected=lockEntry.path!==item.relativePath||!!item.sqlName&&lockEntry.sqlName!==item.sqlName||lockEntry.mode!==item.mode;if(!ctx.bool("force")&&lockEntry.hash===localHash&&!renameDetected){skipped.push({sqlCode:item.sqlCode,reason:"unchanged"});continue}if(lockEntry.version==null){failed.push({sqlCode:item.sqlCode,error:"missing remote version; run `rabetbase sql pull` to refresh version info first"})
|
|
6
|
+
;continue}const effectiveSqlName=item.sqlName||lockEntry.sqlName;const targetBinding=await resolveTargetDbBinding(ctx.appCode,item,lockEntry);const sqlContent=await readSqlUploadContent(item);const latest=await updateSqlQuery({id:lockEntry.remoteId,appCode:ctx.appCode,sqlCode:item.sqlCode,sqlName:effectiveSqlName,dbId:targetBinding.dbId,version:lockEntry.version,sqlContent:sqlContent,sqlConfig:lockEntry.sqlConfig??undefined});const dbName=latest.dbId?await getDbName(ctx.appCode,Number(latest.dbId)).catch(()=>targetBinding.dbName):targetBinding.dbName;appLock.sqls[item.sqlCode]={...buildSqlLockEntry(latest,sqlContent,localHash,{dbName:dbName}),path:item.relativePath,mode:item.mode};lockChanged=true;await archivePreviousSqlFileIfNeeded(config,lockEntry.path,item.relativePath);pushed.push({sqlCode:item.sqlCode,remoteId:lockEntry.remoteId})}catch(error){failed.push({sqlCode:item.sqlCode,error:error instanceof Error?error.message:String(error)})}}if(lockChanged||failed.length===0){
|
|
7
|
+
appLock.lastSync=(new Date).toISOString();await writeSqlLockFile(config.lockFilePath,lockData)}const ok=failed.length===0;return{ok:ok,data:{pushed:pushed,skipped:skipped,failed:failed},message:`Push complete: ${pushed.length} pushed, ${skipped.length} skipped, ${failed.length} failed`}}};async function archivePreviousSqlFileIfNeeded(config,previousRelativePath,nextRelativePath){if(!previousRelativePath||previousRelativePath===nextRelativePath){return}const previousAbsolutePath=join(config.sqlRootDir,previousRelativePath);if(!await fileExists(previousAbsolutePath)){return}const trashedPath=await moveToTrash(config.projectRoot,config.trashDir,previousAbsolutePath);await cleanupEmptyDirectories(dirname(previousAbsolutePath),config.sqlRootDir);void trashedPath}async function moveToTrash(projectRoot,trashDir,localFilePath){const timestamp=(new Date).toISOString().replace(/[:.]/g,"-");const relativePath=relative(projectRoot,localFilePath)
|
|
8
|
+
;const targetPath=join(trashDir,timestamp,relativePath);await mkdir(dirname(targetPath),{recursive:true});await rename(localFilePath,targetPath);return targetPath}async function cleanupEmptyDirectories(startDir,stopDir){let currentDir=resolve(startDir);const normalizedStop=resolve(stopDir);while(currentDir.startsWith(`${normalizedStop}${sep}`)||currentDir===normalizedStop){if(currentDir===normalizedStop)return;try{const entries=await readdir(currentDir);if(entries.length>0)return;await rmdir(currentDir)}catch{return}currentDir=dirname(currentDir)}}async function resolveTargetDbBinding(appCode,item,lockEntry){const dbDirectory=item.dbDirectory;if(!dbDirectory){return{dbId:lockEntry.dbId,dbName:lockEntry.dbName}}const currentLockDir=buildDbDirectoryName(lockEntry.dbName,lockEntry.dbId);if(dbDirectory===currentLockDir){return{dbId:lockEntry.dbId,dbName:lockEntry.dbName}}const explicitDbId=parseExplicitDbDirectory(dbDirectory);if(explicitDbId!=null){return{dbId:explicitDbId,
|
|
9
|
+
dbName:await getDbName(appCode,explicitDbId).catch(()=>undefined)}}const databases=await listDatabases(appCode);const matched=databases.filter(db=>buildDbDirectoryName(db.dbName,db.dbId)===dbDirectory);if(matched.length===1){return{dbId:matched[0].dbId,dbName:matched[0].dbName}}if(matched.length===0){throw CliErrors.validation(`No database matches local directory "${dbDirectory}" for sqlCode ${item.sqlCode}.`)}const available=matched.map(db=>`${db.dbName} (${db.dbId})`).join(", ");throw CliErrors.validation(`Local directory "${dbDirectory}" matches multiple databases for sqlCode ${item.sqlCode}: ${available}`)}function parseExplicitDbDirectory(dbDirectory){const match=/^db-(\d+)$/.exec(dbDirectory);if(!match){return null}const dbId=Number(match[1]);return Number.isFinite(dbId)&&dbId>0?dbId:null}
|
|
@@ -1 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import{createInterface}from"node:readline";import{join}from"node:path";import{buildDefaultSqlFileName,buildSqlRelativePath,detectSqlMode}from"../../core/sql-sync/utils.js";export const SQL_LOCAL_REL_DIR=".rabetbase/sql";export function buildSqlLockEntry(sql,sqlContent,hash,options){const mode=detectSqlMode(sqlContent);return{path:buildSqlRelativePath(sql.sqlCode,sql.sqlName,options?.dbName,mode,sql.dbId),hash:hash,remoteId:sql.id,version:sql.version,dbId:Number(sql.dbId),dbName:options?.dbName,sqlName:sql.sqlName,sqlConfig:sql.sqlConfig??undefined,mode:mode}}export function cloneSqlLockData(lockData){return{apps:Object.fromEntries(Object.entries(lockData.apps).map(([appCode,scope])=>[appCode,{sqlRoot:scope.sqlRoot,lastSync:scope.lastSync,sqls:{...scope.sqls}}]))}}export function ensureRemoteSqlContent(sql){return sql.sqlContent??""}export function buildLocalSqlFileContent(sql,rawContent,options){const mode=options?.mode??detectSqlMode(rawContent)
|
|
2
|
+
;const normalizedBody=stripLocalSqlMetadata(rawContent,mode).trim();const metadataHeaderLines=buildMetadataHeaderLines({sqlCode:sql.sqlCode,sqlName:sql.sqlName,dbId:sql.dbId,dbName:options?.dbName,mode:mode,syncedAt:options?.syncedAt,description:options?.description},mode);const xmlParts=mode==="mybatisXml"?splitXmlDeclaration(normalizedBody):{body:normalizedBody};const lines=[...xmlParts.declaration?[xmlParts.declaration]:[],...metadataHeaderLines,"",xmlParts.body.trimStart()];const text=lines.join("\n");return text.endsWith("\n")?text:`${text}\n`}export function stripLocalSqlMetadata(content,mode){if(mode==="mybatisXml"){const{declaration:declaration,body:body}=splitXmlDeclaration(content.replace(/\r\n/g,"\n"));const strippedBody=stripLeadingMetadataLines(body,/^\s*<!--\s*@lovrabet\./);return declaration?`${declaration}${strippedBody?`\n${strippedBody}`:""}`:strippedBody}return stripLeadingMetadataLines(content.replace(/\r\n/g,"\n"),/^\s*--\s*@lovrabet\./)}
|
|
3
|
+
export function resolveSqlMode(sqlContent,lockEntry){if(lockEntry?.mode)return lockEntry.mode;return detectSqlMode(sqlContent)}export function resolveSqlFileName(sqlCode,sqlContent,lockEntry){if(lockEntry?.path)return lockEntry.path;if(lockEntry?.sqlName||lockEntry?.dbName){return buildSqlRelativePath(sqlCode,lockEntry?.sqlName,lockEntry?.dbName,resolveSqlMode(sqlContent,lockEntry),lockEntry?.dbId)}return buildDefaultSqlFileName(sqlCode,resolveSqlMode(sqlContent,lockEntry))}export function resolveSqlLocalDir(projectRoot,appCode){return join(projectRoot,SQL_LOCAL_REL_DIR,appCode)}export async function confirmForceOverwrite(message){const rl=createInterface({input:process.stdin,output:process.stderr});const answer=await new Promise(resolve=>{rl.question(`${message} [y/N] `,resolve)});rl.close();return["y","yes"].includes(answer.trim().toLowerCase())}export function findSqlLockScope(lockData,appCode){return lockData.apps[appCode]}function buildMetadataHeaderLines(meta,mode){
|
|
4
|
+
const rows=[["sqlCode",meta.sqlCode],["sqlName",meta.sqlName],["dbId",meta.dbId],["dbName",meta.dbName],["mode",meta.mode],["syncedAt",meta.syncedAt],["description",meta.description]];if(mode==="mybatisXml"){return rows.filter(([,value])=>value!==undefined&&value!==null&&String(value).trim()!=="").map(([key,value])=>`\x3c!-- @lovrabet.${key}: ${String(value)} --\x3e`)}return rows.filter(([,value])=>value!==undefined&&value!==null&&String(value).trim()!=="").map(([key,value])=>`-- @lovrabet.${key}: ${String(value)}`)}function splitXmlDeclaration(content){const trimmed=content.trimStart();const match=/^<\?xml(?=\s|\?>)[\s\S]*?\?>/i.exec(trimmed);if(!match){return{body:content}}return{declaration:match[0],body:trimmed.slice(match[0].length)}}function stripLeadingMetadataLines(content,metadataPattern){const lines=content.split("\n");let index=0;while(index<lines.length){const line=lines[index]??"";if(metadataPattern.test(line)||line.trim()===""){index++;continue}break}
|
|
5
|
+
return lines.slice(index).join("\n").trimStart()}
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import{listSqlQueries}from"../../core/api-client.js";import{loadSqlProjectConfig}from"../../core/sql-sync/config.js";import{scanLocalSqlQueries}from"../../core/sql-sync/file-system.js";import{computeSqlFileHash}from"../../core/sql-sync/hash.js";import{createEmptySqlLock,ensureSqlLockScope,readSqlLockFile}from"../../core/sql-sync/lock.js";const PAGE_SIZE=100;async function fetchAllSqlCodes(appCode){const out=[];let page=1;while(true){const r=await listSqlQueries(appCode,{currentPage:page,pageSize:PAGE_SIZE});const batch=r.tableData??[];out.push(...batch.map(item=>item.sqlCode));if(batch.length===0)break;const total=r.paging?.totalCount;if(total!=null?out.length>=total:batch.length<PAGE_SIZE){break}page++}return out}export const sqlStatus={service:"sql",command:"status",description:"Check local SQL sync status against lock file",risk:"read",flags:[{name:"remote",type:"boolean",description:"Also check for remote-only SQL queries not present locally"}],async execute(ctx){
|
|
2
|
+
const config=loadSqlProjectConfig(ctx.appCode);const rawLock=await readSqlLockFile(config.lockFilePath);const{appLock:appLock}=ensureSqlLockScope(rawLock??createEmptySqlLock(),config.appCode,config.sqlRoot,"status");const localSqls=await scanLocalSqlQueries(config);const added=[];const modified=[];const unchanged=[];const missing=[];const localKeys=new Set(localSqls.map(item=>item.lockKey));for(const sql of localSqls){const localHash=await computeSqlFileHash(sql.filePath);const lockEntry=appLock.sqls[sql.lockKey];const pathChanged=!!lockEntry&&lockEntry.path!==sql.relativePath;const sqlNameChanged=!!lockEntry&&!!sql.sqlName&&lockEntry.sqlName!==sql.sqlName;if(!lockEntry){added.push(sql.lockKey)}else if(lockEntry.hash!==localHash||pathChanged||sqlNameChanged){modified.push(sql.lockKey)}else{unchanged.push(sql.lockKey)}}for(const sqlCode of Object.keys(appLock.sqls)){if(!localKeys.has(sqlCode)){missing.push(sqlCode)}}const remoteOnly=[];if(ctx.bool("remote")){
|
|
3
|
+
const remoteSqlCodes=await fetchAllSqlCodes(ctx.appCode);for(const sqlCode of remoteSqlCodes){if(!localKeys.has(sqlCode)&&!appLock.sqls[sqlCode]){remoteOnly.push(sqlCode)}}}const synced=added.length===0&&modified.length===0&&missing.length===0&&remoteOnly.length===0;return{ok:true,data:{added:added,modified:modified,missing:missing,unchanged:unchanged,remoteOnly:remoteOnly},message:synced?"All SQL queries are in sync.":`${added.length} added, ${modified.length} modified, ${missing.length} missing, ${unchanged.length} unchanged`+(remoteOnly.length>0?`, ${remoteOnly.length} remote-only`:"")}}};
|
|
@@ -1 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import{readFileSync,existsSync}from"node:fs";import{resolve}from"node:path";import{validateSql}from"../../core/sql-validator.js";import{auditSqlJoinIndexes}from"../../core/sql-index-auditor.js";import{getDatasetDetail,listDatasets}from"../../core/api-client.js";import{CliErrors}from"../../errors.js";import{assertDatasetIsDbTableBacked,filterDbTableBackedDatasets}from"../../commands/dataset/capability.js";export const sqlValidate={service:"sql",command:"validate",description:"Validate SQL content without saving (type detection, parameter extraction, optional schema check)",risk:"read",flags:[{name:"file",type:"string",description:"Path to the SQL file to validate"},{name:"sql",type:"string",description:"Inline SQL content to validate (alternative to --file)"},{name:"schemas",type:"string",description:"Comma-separated dataset codes to cross-check table/column names against"},{name:"check-indexes",type:"boolean",
|
|
2
|
+
description:"Audit top-level JOIN equality predicates against dataset index metadata"}],async execute(ctx){const filePath=ctx.str("file");const inlineSql=ctx.str("sql");const schemasFlag=ctx.str("schemas");const checkIndexes=ctx.bool("check-indexes");if(!filePath&&!inlineSql){throw CliErrors.flagMissing("file","Provide --file or --sql")}if(checkIndexes&&!schemasFlag){throw CliErrors.validation("--check-indexes requires --schemas.")}let sqlContent;if(filePath){const absPath=resolve(process.cwd(),filePath);if(!existsSync(absPath)){throw CliErrors.validation(`File not found: ${absPath}`)}sqlContent=readFileSync(absPath,"utf-8")}else{sqlContent=inlineSql}const validation=validateSql(sqlContent);const result={valid:validation.valid,sqlType:validation.sqlType.type,isSelectOnly:validation.sqlType.isSelectOnly,isLockingRead:validation.sqlType.isLockingRead??false,isDangerous:validation.sqlType.isDangerous,tables:validation.tables,parameters:validation.parameters,message:validation.message}
|
|
3
|
+
;if(validation.sqlType.reason){result.reason=validation.sqlType.reason}if(schemasFlag&&validation.valid){const codes=schemasFlag.split(",").map(s=>s.trim()).filter(Boolean);const schemaErrors=[];const indexTables=[];const allDatasets=filterDbTableBackedDatasets(await listDatasets(ctx.appCode));const datasetMap=new Map(allDatasets.map(d=>[d.dbtableConfig?.tableName?.toLowerCase(),d]));for(const table of validation.tables){const ds=datasetMap.get(table.toLowerCase());if(!ds){schemaErrors.push(`Table "${table}" not found in any dataset`)}}for(const code of codes){let detail;try{detail=await getDatasetDetail(code)}catch{schemaErrors.push(`Dataset "${code}" not found or not accessible`);continue}assertDatasetIsDbTableBacked(detail,"SQL schema validation");const fields=Array.isArray(detail.fields)?detail.fields:[];const fieldNames=new Set(fields.map(f=>f.name?.toLowerCase()));const tableName=detail.dbtableConfig?.tableName||detail.tableName||code;result[`schema:${tableName}`]={code:code,
|
|
4
|
+
tableName:tableName,fieldCount:fieldNames.size,fields:Array.from(fieldNames)};if(checkIndexes){const indexMetadata=normalizeDatasetIndexes(detail);indexTables.push({tableName:tableName,...indexMetadata})}}if(schemaErrors.length>0){result.schemaWarnings=schemaErrors}if(checkIndexes){result.joinAudit=auditSqlJoinIndexes(sqlContent,indexTables)}}return{ok:validation.valid,data:result,message:validation.message}}};function normalizeDatasetIndexes(detail){const rawIndexes=Array.isArray(detail?.dataset?.indexes)?detail.dataset.indexes:Array.isArray(detail?.indexes)?detail.indexes:[];const reportedIndexes=rawIndexes.flatMap(raw=>{const columns=Array.isArray(raw?.index_columns)?raw.index_columns:Array.isArray(raw?.columnNames)?raw.columnNames:Array.isArray(raw?.columns)?raw.columns:[];const normalizedColumns=columns.filter(column=>typeof column==="string").map(column=>column.trim()).filter(Boolean);if(normalizedColumns.length===0)return[]
|
|
5
|
+
;const name=[raw?.indexName,raw?.index_name,raw?.name].find(value=>typeof value==="string"&&value.trim());const type=[raw?.index_type,raw?.type].find(value=>typeof value==="string"&&value.trim());return[{...name?{name:name.trim()}:{},...type?{type:type.trim()}:{},columns:normalizedColumns}]});const indexes=[...reportedIndexes];const primaryColumns=typeof detail?.dbtableConfig?.pkField==="string"?detail.dbtableConfig.pkField.split(",").map(column=>column.trim()).filter(Boolean):[];if(primaryColumns.length>0){indexes.unshift({type:"primary",columns:primaryColumns})}return{indexes:indexes,metadataAvailable:reportedIndexes.length>0}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{taskStatus}from"../../commands/task/status.js";export const taskDefinitions=[taskStatus];
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{APPCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{asyncTaskMessage,buildAsyncTaskStatusCommand,normalizeAsyncTask}from"../../commands/common/async-task.js";import{getAsyncTaskStatus}from"../../core/api-client.js";import{CliErrors}from"../../errors.js";export const taskStatus={service:"task",command:"status",description:"Query an asynchronous task; repeat for PENDING or PROCESSING until SUCCESS or FAILED",risk:"read",defaultOutputFormat:"compress",structuredErrors:true,flags:[{name:"task-id",type:"string",required:true,description:"Task id returned by an asynchronous platform command"},APPCODE_FLAG_OPTIONAL],async validate(ctx){if(!ctx.str("task-id").trim()){throw CliErrors.flagMissing("task-id")}},async execute(ctx){const requestedTaskId=ctx.str("task-id").trim();const task=normalizeAsyncTask(await getAsyncTaskStatus(requestedTaskId,ctx.appCode,ctx.cookie));if(task.taskId!==requestedTaskId){
|
|
2
|
+
throw CliErrors.apiError(`Task status response id mismatch: requested ${requestedTaskId}, received ${task.taskId}.`)}const queryCommand=buildAsyncTaskStatusCommand(task.taskId,ctx.appCode);return{ok:true,message:asyncTaskMessage(task),data:{appCode:ctx.appCode,...task,query:task.isTerminal?null:{command:queryCommand}}}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{tenantMembersListDefinition}from"../../commands/tenant/members-list.js";export const tenantDefinitions=[tenantMembersListDefinition];
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{listCurrentUserTenantMemberships,listTenantDirectoryMembers}from"../../core/api-client.js";import{CliErrors}from"../../errors.js";import{assertTenantAccessible,projectTenantMembers}from"../../commands/tenant/shared.js";export const tenantMembersListDefinition={service:"tenant",command:"members-list",description:"List members of a tenant available to the current account",risk:"read",requiresAuth:true,requiresAppCode:false,structuredErrors:true,flags:[{name:"tenant-code",type:"string",required:true,description:"Exact tenant code"}],async validate(ctx){if(!ctx.str("tenant-code").trim()){throw CliErrors.flagMissing("tenant-code","Pass --tenant-code <code>.")}},async execute(ctx){const tenantCode=ctx.str("tenant-code").trim();const memberships=await listCurrentUserTenantMemberships();assertTenantAccessible(tenantCode,memberships);const items=projectTenantMembers(await listTenantDirectoryMembers(tenantCode));return{ok:true,data:{tenantCode:tenantCode,items:items,
|
|
2
|
+
totalCount:items.length},message:`Found ${items.length} tenant member(s)`}}};
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{CliErrors}from"../../errors.js";function textOrNull(value){const normalized=value?.trim();return normalized?normalized:null}export function projectTenantMembers(members){const projected=new Map;for(const member of members){const userId=Number(member.userId);if(!Number.isFinite(userId)||userId<=0)continue;const next={userId:userId,username:textOrNull(member.username),displayName:textOrNull(member.nickname),role:member.adminFlag===true?"ADMIN":"MEMBER",status:textOrNull(member.status)};const existing=projected.get(userId);if(!existing){projected.set(userId,next);continue}existing.username??=next.username;existing.displayName??=next.displayName;existing.status??=next.status;if(next.role==="ADMIN")existing.role="ADMIN"}return[...projected.values()].sort((left,right)=>left.userId-right.userId)}export function assertTenantAccessible(tenantCode,memberships){if(memberships.some(membership=>membership.tenantCode===tenantCode)){return}
|
|
2
|
+
throw CliErrors.validation(`Tenant "${tenantCode}" is not available to the current account.`,"Check --tenant-code or login with an account that belongs to this tenant.")}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{asDryRunResult}from"../../commands/common/dry-run.js";import{bindDingTalkSandboxAccount,DING_TALK_SANDBOX_BIND_PATH}from"../../core/api-client.js";import{CliErrors}from"../../errors.js";const PROVIDER_ID="dingtalk";const CURRENT_BINDING_WARNING="The current binding is not exposed by the server; before is unavailable.";function readDingTalkUserId(ctx){const dingTalkUserId=ctx.str("ding-talk-user-id").trim();if(!dingTalkUserId){throw CliErrors.validation("--ding-talk-user-id cannot be empty.","Pass the DingTalk user id returned by the sandbox.")}return dingTalkUserId}function buildBindingData(dingTalkUserId,dryRun){return{operation:"bind",selector:{providerId:PROVIDER_ID,dingTalkUserId:dingTalkUserId},before:null,after:{providerId:PROVIDER_ID,dingTalkUserId:dingTalkUserId,bound:true},dryRun:dryRun,backend:{method:"POST",path:DING_TALK_SANDBOX_BIND_PATH},warnings:[CURRENT_BINDING_WARNING]}}export const dingTalkSandboxBind={service:"user-account",command:"dingding-sandbox-bind",
|
|
2
|
+
description:"Bind the current platform user to a DingTalk sandbox account",risk:"write",requiresAuth:true,requiresAppCode:false,structuredErrors:true,flags:[{name:"ding-talk-user-id",type:"string",required:true,description:"DingTalk user id returned by the sandbox"}],async validate(ctx){readDingTalkUserId(ctx)},async dryRun(ctx){const dingTalkUserId=readDingTalkUserId(ctx);return asDryRunResult(buildBindingData(dingTalkUserId,true),{method:"POST",url:DING_TALK_SANDBOX_BIND_PATH})},async execute(ctx){const dingTalkUserId=readDingTalkUserId(ctx);const confirmed=await bindDingTalkSandboxAccount(dingTalkUserId);if(confirmed!==true){throw CliErrors.apiError("DingTalk sandbox account binding was not confirmed.","Retry with the same --ding-talk-user-id only after checking the current platform session.")}return{ok:true,data:buildBindingData(dingTalkUserId,false),message:"Bound current user to DingTalk sandbox account."}}};
|