@lovrabet/rabetbase-cli 2.5.13 → 2.6.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -17
- package/lib/api/api-doc.js +3 -1
- package/lib/api/api-group.js +3 -1
- package/lib/api/fetch-model-list.js +1 -1
- package/lib/api/generate-api-file.js +8 -1
- package/lib/api/generate-sdk-config-file.js +1 -1
- package/lib/api/legacy-api-file.js +2 -1
- package/lib/api/model-registry-file.js +11 -1
- package/lib/api/model-registry-scaffold.js +2 -1
- package/lib/api/model-source.js +3 -1
- package/lib/auth/auth-server-ui.js +2 -1
- package/lib/auth/auth-server.js +5 -1
- package/lib/auth/constant.js +1 -1
- package/lib/auth/get-cookie.js +1 -1
- package/lib/auth/get-session-user.js +1 -1
- package/lib/auth/is-session-valid.js +1 -1
- package/lib/auth/login-success-html.js +3 -1
- package/lib/auth/logout.js +1 -1
- package/lib/cli-flags.js +1 -1
- package/lib/cli.js +5 -1
- package/lib/commands/api/generate.js +4 -1
- package/lib/commands/api/index.js +1 -1
- package/lib/commands/api/list.js +2 -1
- package/lib/commands/api/pull.js +10 -1
- package/lib/commands/api/shared.js +1 -1
- package/lib/commands/app/detail.js +1 -1
- package/lib/commands/app/index.js +1 -1
- package/lib/commands/app/list.js +5 -1
- package/lib/commands/app/members-list.js +1 -1
- package/lib/commands/app/remote-directory.js +1 -1
- package/lib/commands/app/shared.js +4 -1
- package/lib/commands/app-config/delete.js +2 -1
- package/lib/commands/app-config/get.js +2 -1
- package/lib/commands/app-config/index.js +1 -1
- package/lib/commands/app-config/list.js +2 -1
- package/lib/commands/app-config/set.js +3 -1
- package/lib/commands/app-config/shared.d.ts +9 -2
- package/lib/commands/app-config/shared.js +6 -1
- package/lib/commands/auth/index.js +1 -1
- package/lib/commands/bff/create.js +11 -1
- package/lib/commands/bff/delete.js +6 -1
- package/lib/commands/bff/detail.js +1 -1
- package/lib/commands/bff/index.js +1 -1
- package/lib/commands/bff/list.js +1 -1
- package/lib/commands/bff/logs.js +4 -1
- package/lib/commands/bff/pull.js +22 -1
- package/lib/commands/bff/push.js +16 -1
- package/lib/commands/bff/status.js +3 -1
- package/lib/commands/cli-skill/index.js +2 -1
- package/lib/commands/cli-update.js +7 -1
- package/lib/commands/codegen/index.js +1 -1
- package/lib/commands/codegen/sdk.js +1 -1
- package/lib/commands/codegen/sql.js +1 -1
- package/lib/commands/common/app-registry.js +4 -1
- package/lib/commands/common/app-selector.js +4 -1
- package/lib/commands/common/async-task.js +2 -1
- package/lib/commands/common/dry-run.js +1 -1
- package/lib/commands/common/flags.js +3 -1
- package/lib/commands/common/local-file.js +1 -1
- package/lib/commands/common/validate.js +1 -1
- package/lib/commands/config/delete.js +2 -1
- package/lib/commands/config/get.js +1 -1
- package/lib/commands/config/index.js +1 -1
- package/lib/commands/config/init.js +5 -1
- package/lib/commands/config/list.js +1 -1
- package/lib/commands/config/set.js +4 -1
- package/lib/commands/config/shared.js +2 -1
- package/lib/commands/dataset/batch-design.js +9 -1
- package/lib/commands/dataset/business-group-update.js +10 -1
- package/lib/commands/dataset/business-groups.js +1 -1
- package/lib/commands/dataset/capability.js +3 -1
- package/lib/commands/dataset/cross-relation-create.js +2 -1
- package/lib/commands/dataset/cross-relation-delete.js +1 -1
- package/lib/commands/dataset/cross-relation-list.js +2 -1
- package/lib/commands/dataset/cross-relation-shared.js +10 -1
- package/lib/commands/dataset/cross-relation-update.js +2 -1
- package/lib/commands/dataset/delete.js +6 -1
- package/lib/commands/dataset/design-context.js +1 -1
- package/lib/commands/dataset/design-start.js +1 -1
- package/lib/commands/dataset/design-status.js +1 -1
- package/lib/commands/dataset/design-sync-retry.js +1 -1
- package/lib/commands/dataset/design-sync-status.js +1 -1
- package/lib/commands/dataset/design-validate.js +1 -1
- package/lib/commands/dataset/detail.js +5 -1
- package/lib/commands/dataset/extend-update.js +7 -1
- package/lib/commands/dataset/field-restore.js +7 -1
- package/lib/commands/dataset/field-update.js +7 -1
- package/lib/commands/dataset/generate.js +19 -1
- package/lib/commands/dataset/index.js +3 -1
- package/lib/commands/dataset/list.js +2 -1
- package/lib/commands/dataset/operations.js +2 -1
- package/lib/commands/dataset/relation-audit.js +7 -1
- package/lib/commands/dataset/relation-create.js +3 -1
- package/lib/commands/dataset/relation-delete.js +3 -1
- package/lib/commands/dataset/relation-shared.js +21 -1
- package/lib/commands/dataset/relation-update.js +4 -1
- package/lib/commands/dataset/relations.js +7 -1
- package/lib/commands/dataset/rename.js +4 -1
- package/lib/commands/dataset/restore.js +7 -1
- package/lib/commands/dataset/user-deleted-field-list.js +3 -1
- package/lib/commands/db/analysis-batching.js +3 -1
- package/lib/commands/db/analyze-batch-plan.js +2 -1
- package/lib/commands/db/analyze-cancel.js +1 -1
- package/lib/commands/db/analyze-start.js +3 -1
- package/lib/commands/db/analyze-status.js +6 -1
- package/lib/commands/db/create.js +4 -1
- package/lib/commands/db/cross-db-analysis-shared.js +3 -1
- package/lib/commands/db/cross-db-analyze-latest.js +1 -1
- package/lib/commands/db/cross-db-analyze-start.js +2 -1
- package/lib/commands/db/cross-db-analyze-status.js +1 -1
- package/lib/commands/db/delete.js +3 -1
- package/lib/commands/db/detail.js +1 -1
- package/lib/commands/db/diff-refresh-start.js +1 -1
- package/lib/commands/db/diff-refresh-status.js +2 -1
- package/lib/commands/db/diff.js +3 -1
- package/lib/commands/db/index.js +2 -1
- package/lib/commands/db/list.js +2 -1
- package/lib/commands/db/shared.js +3 -1
- package/lib/commands/db/table-diff-shared.js +2 -1
- package/lib/commands/db/tables.js +2 -1
- package/lib/commands/db/test.js +2 -1
- package/lib/commands/db/update.js +4 -1
- package/lib/commands/deployment/index.js +1 -1
- package/lib/commands/deployment/sync-all.js +3 -1
- package/lib/commands/deployment/sync-jobs.js +2 -1
- package/lib/commands/deployment/sync-status.js +2 -1
- package/lib/commands/doctor.js +12 -1
- package/lib/commands/file/index.js +3 -1
- package/lib/commands/flow/create.js +2 -1
- package/lib/commands/flow/detail.js +3 -1
- package/lib/commands/flow/index.js +1 -1
- package/lib/commands/flow/list.js +2 -1
- package/lib/commands/flow/page-list.js +2 -1
- package/lib/commands/flow/publish.js +2 -1
- package/lib/commands/flow/runtime-resources-shared.js +3 -1
- package/lib/commands/flow/runtime-role-list.js +2 -1
- package/lib/commands/flow/runtime-role-user-list.js +2 -1
- package/lib/commands/flow/runtime-user-search.js +2 -1
- package/lib/commands/flow/shared.js +6 -1
- package/lib/commands/flow/update.js +4 -1
- package/lib/commands/flow/validate.js +2 -1
- package/lib/commands/instant-api-policy/current.js +1 -1
- package/lib/commands/instant-api-policy/index.js +1 -1
- package/lib/commands/instant-api-policy/init.js +2 -1
- package/lib/commands/instant-api-policy/publish.js +5 -1
- package/lib/commands/instant-api-policy/pull.js +2 -1
- package/lib/commands/instant-api-policy/revision.js +1 -1
- package/lib/commands/instant-api-policy/revisions.js +1 -1
- package/lib/commands/instant-api-policy/rollback.js +5 -1
- package/lib/commands/instant-api-policy/shared.js +5 -1
- package/lib/commands/instant-api-policy/validate.js +1 -1
- package/lib/commands/issue/context.js +1 -1
- package/lib/commands/issue/index.js +1 -1
- package/lib/commands/issue/nudge.js +2 -1
- package/lib/commands/issue/report.js +5 -1
- package/lib/commands/kb/create.js +5 -1
- package/lib/commands/kb/delete.js +5 -1
- package/lib/commands/kb/detail.js +1 -1
- package/lib/commands/kb/import-api.d.ts +3 -0
- package/lib/commands/kb/import-api.js +1 -0
- package/lib/commands/kb/import-resume.d.ts +2 -0
- package/lib/commands/kb/import-resume.js +2 -0
- package/lib/commands/kb/import-shared.d.ts +69 -0
- package/lib/commands/kb/import-shared.js +9 -0
- package/lib/commands/kb/import-status.d.ts +2 -0
- package/lib/commands/kb/import-status.js +1 -0
- package/lib/commands/kb/import.d.ts +2 -0
- package/lib/commands/kb/import.js +3 -0
- package/lib/commands/kb/index.js +1 -1
- package/lib/commands/kb/list.js +1 -1
- package/lib/commands/kb/search.js +3 -1
- package/lib/commands/kb/shared.js +9 -1
- package/lib/commands/kb/update.js +7 -1
- package/lib/commands/logs/index.js +2 -1
- package/lib/commands/menu/asset-update.js +8 -1
- package/lib/commands/menu/delete.js +15 -1
- package/lib/commands/menu/external-link-create.js +16 -1
- package/lib/commands/menu/external-link-update.js +10 -1
- package/lib/commands/menu/group-create.js +8 -1
- package/lib/commands/menu/group-update.js +6 -1
- package/lib/commands/menu/index.js +2 -1
- package/lib/commands/menu/list.js +1 -1
- package/lib/commands/menu/move.js +6 -1
- package/lib/commands/menu/regroup-start.js +11 -1
- package/lib/commands/menu/rename.js +9 -1
- package/lib/commands/menu/shared/compare-table.js +2 -1
- package/lib/commands/menu/shared/delete-plan.js +13 -1
- package/lib/commands/menu/shared/facts.js +5 -1
- package/lib/commands/menu/shared/index.js +1 -1
- package/lib/commands/menu/shared/inquirer.js +4 -1
- package/lib/commands/menu/shared/local-pages.js +5 -1
- package/lib/commands/menu/shared/logic.js +3 -1
- package/lib/commands/menu/shared/mutations.js +9 -1
- package/lib/commands/menu/shared/path.js +1 -1
- package/lib/commands/menu/shared/service.js +4 -1
- package/lib/commands/menu/shared/subapp-assets.js +4 -1
- package/lib/commands/menu/shared/sync-core.js +7 -1
- package/lib/commands/menu/shared/types.js +1 -1
- package/lib/commands/menu/shared/update-core.js +8 -1
- package/lib/commands/menu/shared/valid-url.js +1 -1
- package/lib/commands/menu/subapp-assets-status.js +1 -1
- package/lib/commands/menu/subapp-assets-update.js +7 -1
- package/lib/commands/menu/sync.js +7 -1
- package/lib/commands/menu/visibility-update.js +13 -1
- package/lib/commands/metric/contract.d.ts +8 -0
- package/lib/commands/metric/contract.js +5 -0
- package/lib/commands/metric/definition.d.ts +43 -0
- package/lib/commands/metric/definition.js +4 -0
- package/lib/commands/metric/delete.d.ts +2 -0
- package/lib/commands/metric/delete.js +3 -0
- package/lib/commands/metric/detail.d.ts +2 -0
- package/lib/commands/metric/detail.js +1 -0
- package/lib/commands/metric/example.d.ts +2 -0
- package/lib/commands/metric/example.js +1 -0
- package/lib/commands/metric/index.d.ts +2 -0
- package/lib/commands/metric/index.js +1 -0
- package/lib/commands/metric/list.d.ts +2 -0
- package/lib/commands/metric/list.js +2 -0
- package/lib/commands/metric/publication-diff.d.ts +8 -0
- package/lib/commands/metric/publication-diff.js +1 -0
- package/lib/commands/metric/publish.d.ts +2 -0
- package/lib/commands/metric/publish.js +4 -0
- package/lib/commands/metric/schema.d.ts +2 -0
- package/lib/commands/metric/schema.js +1 -0
- package/lib/commands/metric/shared.d.ts +14 -0
- package/lib/commands/metric/shared.js +2 -0
- package/lib/commands/metric/validate.d.ts +2 -0
- package/lib/commands/metric/validate.js +1 -0
- package/lib/commands/notification/config-create.js +4 -1
- package/lib/commands/notification/config-delete.js +4 -1
- package/lib/commands/notification/config-list.js +2 -1
- package/lib/commands/notification/config-update.js +4 -1
- package/lib/commands/notification/index.js +1 -1
- package/lib/commands/notification/shared.js +18 -1
- package/lib/commands/ocr/index.js +4 -1
- package/lib/commands/page/create.js +6 -1
- package/lib/commands/page/custom/detail.js +2 -1
- package/lib/commands/page/custom/list.js +2 -1
- package/lib/commands/page/custom/publish.js +3 -1
- package/lib/commands/page/custom/shared.js +3 -1
- package/lib/commands/page/custom/syntax.js +2 -1
- package/lib/commands/page/custom/update.js +3 -1
- package/lib/commands/page/data-list-status.js +2 -1
- package/lib/commands/page/generate-start.js +5 -1
- package/lib/commands/page/generate-status.js +4 -1
- package/lib/commands/page/index.js +2 -1
- package/lib/commands/page/pull.js +6 -1
- package/lib/commands/page/push.js +11 -1
- package/lib/commands/page/relation-audit.js +15 -1
- package/lib/commands/page/restore.js +5 -1
- package/lib/commands/page/shared.js +16 -1
- package/lib/commands/page/sync.js +2 -1
- package/lib/commands/project/api-architecture-upgrade.js +11 -1
- package/lib/commands/project/create/enhanced-guided-create.js +2 -1
- package/lib/commands/project/create/format-elapsed.js +1 -1
- package/lib/commands/project/create/main.js +13 -1
- package/lib/commands/project/create/materialize-project-template.js +12 -1
- package/lib/commands/project/create/project-name.js +1 -1
- package/lib/commands/project/create/project-template-archive.js +5 -1
- package/lib/commands/project/create/project-template-path.js +1 -1
- package/lib/commands/project/create/use-copy-project-template.js +2 -1
- package/lib/commands/project/create/use-format-code.js +1 -1
- package/lib/commands/project/create/use-install-dependencies.js +1 -1
- package/lib/commands/project/domain-routing-sync.js +1 -1
- package/lib/commands/project/index.js +4 -1
- package/lib/commands/project/upgrade.js +7 -1
- package/lib/commands/registry.js +10 -1
- package/lib/commands/role/delete.js +2 -1
- package/lib/commands/role/detail.js +1 -1
- package/lib/commands/role/index.js +1 -1
- package/lib/commands/role/list.js +2 -1
- package/lib/commands/role/shared.js +8 -1
- package/lib/commands/role/update.js +3 -1
- package/lib/commands/role/user-add.js +2 -1
- package/lib/commands/role/user-remove.js +2 -1
- package/lib/commands/role/user-resolve.js +1 -1
- package/lib/commands/rule/get.js +1 -1
- package/lib/commands/rule/index.js +1 -1
- package/lib/commands/rule/list.js +1 -1
- package/lib/commands/rule/set.js +7 -1
- package/lib/commands/rule/shared.js +4 -1
- package/lib/commands/run/index.js +5 -1
- package/lib/commands/schema.js +1 -1
- package/lib/commands/sql/create.js +7 -1
- package/lib/commands/sql/delete.js +4 -1
- package/lib/commands/sql/detail.js +1 -1
- package/lib/commands/sql/exec.js +1 -1
- package/lib/commands/sql/index.js +1 -1
- package/lib/commands/sql/list.js +2 -1
- package/lib/commands/sql/pull.js +10 -1
- package/lib/commands/sql/push.js +9 -1
- package/lib/commands/sql/shared.js +5 -1
- package/lib/commands/sql/status.js +3 -1
- package/lib/commands/sql/validate.js +5 -1
- package/lib/commands/task/index.js +1 -1
- package/lib/commands/task/status.js +2 -1
- package/lib/commands/tenant/index.js +1 -1
- package/lib/commands/tenant/members-list.js +2 -1
- package/lib/commands/tenant/shared.js +2 -1
- package/lib/commands/user-account/dingding-sandbox-bind.js +2 -1
- package/lib/commands/user-account/feishu-bind.js +2 -1
- package/lib/commands/user-account/index.js +1 -1
- package/lib/commands/workspace/add.js +1 -1
- package/lib/commands/workspace/index.js +7 -1
- package/lib/commands/workspace/remove.js +1 -1
- package/lib/config/domain-config.js +8 -1
- package/lib/config/project-domain-routing.js +3 -1
- package/lib/config/region-config.js +2 -1
- package/lib/config/schema.js +7 -1
- package/lib/constant/cdn.js +2 -1
- package/lib/constant/cli.js +8 -1
- package/lib/constant/defaults.js +1 -1
- package/lib/constant/domain.js +4 -1
- package/lib/constant/env.js +1 -1
- package/lib/constant/output.js +1 -1
- package/lib/constant/paths.js +1 -1
- package/lib/constant/region.js +1 -1
- package/lib/constant/risk.js +1 -1
- package/lib/constant/routing-profile.js +1 -1
- package/lib/context/app-resolver.js +7 -1
- package/lib/context/auth-resolver.js +1 -1
- package/lib/context/config-loader.js +7 -1
- package/lib/context.js +9 -1
- package/lib/core/alias-resolver.js +5 -1
- package/lib/core/api-client.d.ts +14 -7
- package/lib/core/api-client.js +69 -1
- package/lib/core/bff/config.js +1 -1
- package/lib/core/bff/file-system.js +6 -1
- package/lib/core/bff/hash.js +1 -1
- package/lib/core/bff/hook-directory.js +9 -1
- package/lib/core/bff/lock.js +2 -1
- package/lib/core/bff/types.js +1 -1
- package/lib/core/bff/utils.js +3 -1
- package/lib/core/cross-db-analysis.js +1 -1
- package/lib/core/cross-db-relation.js +1 -1
- package/lib/core/db-resolver.js +2 -1
- package/lib/core/flow-config.js +49 -1
- package/lib/core/instant-api-policy/config.js +7 -1
- package/lib/core/instant-api-policy/endpoints.js +1 -1
- package/lib/core/kb-management-client.d.ts +11 -0
- package/lib/core/kb-management-client.js +4 -1
- package/lib/core/kb-search-client.js +3 -1
- package/lib/core/page/file-system.js +2 -1
- package/lib/core/page/hash.js +1 -1
- package/lib/core/page/lock.js +2 -1
- package/lib/core/page/lr-smart-jsx.js +4 -1
- package/lib/core/page/types.js +1 -1
- package/lib/core/sql-index-auditor.js +14 -1
- package/lib/core/sql-sync/config.js +1 -1
- package/lib/core/sql-sync/file-system.js +3 -1
- package/lib/core/sql-sync/hash.js +1 -1
- package/lib/core/sql-sync/lock.js +2 -1
- package/lib/core/sql-sync/types.js +1 -1
- package/lib/core/sql-sync/utils.js +2 -1
- package/lib/core/sql-validator.js +15 -1
- package/lib/errors.js +3 -1
- package/lib/framework/build-all-flags.js +1 -1
- package/lib/framework/error-output.js +1 -1
- package/lib/framework/explicit-yes.js +1 -1
- package/lib/framework/flags.js +1 -1
- package/lib/framework/help.js +2 -1
- package/lib/framework/index.js +1 -1
- package/lib/framework/output.js +2 -1
- package/lib/framework/response.js +1 -1
- package/lib/framework/runner-alias.js +2 -1
- package/lib/framework/runner.js +9 -1
- package/lib/framework/schema-export.js +1 -1
- package/lib/framework/supported-flags.js +2 -1
- package/lib/framework/types.js +1 -1
- package/lib/generated/build-info.d.ts +4 -4
- package/lib/generated/build-info.js +1 -1
- package/lib/generated/official-routing.js +3 -1
- package/lib/generated/routing-contract.js +1 -1
- package/lib/help.js +1 -1
- package/lib/runtime/confirmation.js +2 -1
- package/lib/runtime/event.js +1 -1
- package/lib/runtime/index.js +4 -1
- package/lib/runtime/queue.js +1 -1
- package/lib/runtime/resolve.js +2 -1
- package/lib/runtime/types.js +1 -1
- package/lib/services/dataset-design/checkpoint.js +2 -1
- package/lib/services/dataset-design/commands.js +14 -1
- package/lib/services/dataset-design/contract.js +8 -1
- package/lib/skills/builtin-skill.js +8 -1
- package/lib/skills/install-updated-skill.d.ts +8 -0
- package/lib/skills/install-updated-skill.js +3 -0
- package/lib/skills/local-skills-installer.d.ts +2 -0
- package/lib/skills/local-skills-installer.js +1 -0
- package/lib/skills/main.js +2 -1
- package/lib/skills/npx-skills-add.d.ts +6 -6
- package/lib/skills/npx-skills-add.js +5 -1
- package/lib/skills/skill-presence.d.ts +1 -30
- package/lib/skills/skill-presence.js +2 -1
- package/lib/telemetry/cli-command-trace.js +2 -1
- package/lib/telemetry/cli-help-trace.js +1 -1
- package/lib/telemetry/ensure-cli-otel-config.js +1 -1
- package/lib/telemetry/register-otel-exit-shutdown.js +1 -1
- package/lib/telemetry/send-cli-trace-log.js +1 -1
- package/lib/types/index.js +1 -1
- package/lib/utils/ai_config.js +3 -1
- package/lib/utils/apply-jq-filter.js +1 -1
- package/lib/utils/cdn-config.js +1 -1
- package/lib/utils/check-sdk-version.js +5 -1
- package/lib/utils/cli-version-check.js +4 -1
- package/lib/utils/cli-version-policy.js +3 -1
- package/lib/utils/config.js +1 -1
- package/lib/utils/entity-with-id.js +1 -1
- package/lib/utils/file-utils.js +1 -1
- package/lib/utils/guides-cdn.js +3 -1
- package/lib/utils/http-client.js +2 -1
- package/lib/utils/is-non-interactive.js +1 -1
- package/lib/utils/logger.js +3 -1
- package/lib/utils/params.js +1 -1
- package/lib/utils/platform.js +1 -1
- package/lib/utils/sleep.js +1 -1
- package/lib/utils/template-replacer.js +5 -1
- package/lib/utils/update-notice.js +3 -1
- package/lib/utils/version.js +1 -1
- package/lib/utils/with-active-cookie.js +1 -1
- package/lib/utils/write-cli-side-channel.js +1 -1
- package/package.json +10 -7
- package/skills/rabetbase/SKILL.md +11 -7
- package/skills/rabetbase/guides/backend-function.md +3 -1
- package/skills/rabetbase/guides/data-api-guidelines.md +1 -1
- package/skills/rabetbase/guides/frontend-development.md +1 -0
- package/skills/rabetbase/guides/metric-development.md +185 -0
- package/skills/rabetbase/references/rabetbase-app-config.md +4 -3
- package/skills/rabetbase/references/rabetbase-cli-skill-install.md +5 -5
- package/skills/rabetbase/references/rabetbase-dataset-design.md +1 -1
- package/skills/rabetbase/references/rabetbase-kb.md +16 -0
- package/skills/rabetbase/references/rabetbase-metric.md +119 -0
- package/skills/rabetbase/references/rabetbase-update.md +7 -5
- package/skills/rabetbase-dataset-generation/SKILL.md +1 -1
- package/skills/rabetbase-dataset-generation/references/workflow.md +1 -1
- package/skills/rabetbase-metrics-generation/SKILL.md +22 -0
- package/skills/rabetbase-metrics-generation/references/verification.md +19 -0
- package/skills/rabetbase-metrics-generation/references/workflow.md +41 -0
- package/skills/rabetbase-metrics-generation/templates/statistics-delivery.md +11 -0
- package/skills/rabetbase-page-generation/SKILL.md +1 -1
- package/skills/rabetbase-page-generation/references/generation.md +1 -1
- package/skills/rabetbase.manifest.json +5 -3
- package/templates/metrics/definition.json +78 -0
- package/templates/metrics/metric-definition.schema.json +136 -0
- package/lib/postinstall.d.ts +0 -3
- package/lib/postinstall.js +0 -1
- package/scripts/postinstall.mjs +0 -24
- package/templates/README.md +0 -130
package/README.md
CHANGED
|
@@ -21,23 +21,34 @@ business Skills, use the Lovrabet runtime CLI (`@lovrabet/lovrabet-cli`).
|
|
|
21
21
|
|
|
22
22
|
## Install
|
|
23
23
|
|
|
24
|
+
Install the CLI, then explicitly install its matching Built-in Skill:
|
|
25
|
+
|
|
24
26
|
```bash
|
|
25
|
-
npm install -g @lovrabet/rabetbase-cli@latest
|
|
27
|
+
npm install -g @lovrabet/rabetbase-cli@latest --ignore-scripts
|
|
28
|
+
rabetbase cli-skill install
|
|
26
29
|
rabetbase --version
|
|
27
|
-
rabetbase
|
|
30
|
+
rabetbase doctor
|
|
28
31
|
```
|
|
29
32
|
|
|
30
|
-
|
|
33
|
+
Use `@beta` for a beta preview, or pin an exact published version for a container
|
|
34
|
+
image. Run the Skill command as the user whose HOME the agent will use.
|
|
35
|
+
The npm package has no install lifecycle hooks. Help, version, and ordinary
|
|
36
|
+
commands do not install Skills automatically.
|
|
31
37
|
|
|
32
|
-
|
|
33
|
-
npm
|
|
34
|
-
|
|
38
|
+
The CLI uses its exact-version local `skills` dependency to install the Built-in
|
|
39
|
+
Skill shipped in the same npm package. Once npm has installed the dependencies,
|
|
40
|
+
Skill installation needs no installer or Skill-content download. No npm script
|
|
41
|
+
approval is needed for this flow.
|
|
35
42
|
|
|
36
|
-
|
|
43
|
+
Treat installation as complete only when the explicit Skill command succeeds
|
|
44
|
+
and `doctor` reports the Built-in Skill as `current`. If the Skill step fails,
|
|
45
|
+
the CLI may already be installed; fix the reported cause and rerun
|
|
46
|
+
`rabetbase cli-skill install`. Do not substitute a remote repository's Skill.
|
|
37
47
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
48
|
+
`rabetbase update` installs the target CLI and invokes that new package's explicit
|
|
49
|
+
Skill installer before reporting success. A failed Skill step returns failure
|
|
50
|
+
without claiming that the CLI package was rolled back. With older updaters,
|
|
51
|
+
finish the transition by running `rabetbase cli-skill install` explicitly.
|
|
41
52
|
|
|
42
53
|
## Update and Verify
|
|
43
54
|
|
|
@@ -185,28 +196,38 @@ The generated project file always contains the two complete final URLs.
|
|
|
185
196
|
|
|
186
197
|
## AI Agent Skill
|
|
187
198
|
|
|
188
|
-
|
|
189
|
-
Rabetbase CLI Built-in Skill
|
|
190
|
-
|
|
199
|
+
After installing the npm package, explicitly install the same-version main
|
|
200
|
+
Rabetbase CLI Built-in Skill with the command below. It uses the package-local
|
|
201
|
+
source and the exact-version local official Skills CLI dependency.
|
|
202
|
+
`rabetbase update` installs the new CLI and invokes its Skill installer; the same
|
|
203
|
+
command also repairs the current installation:
|
|
191
204
|
|
|
192
205
|
```bash
|
|
193
206
|
rabetbase cli-skill install
|
|
194
207
|
```
|
|
195
208
|
|
|
196
|
-
The package also includes the independent `rabetbase-page-generation
|
|
197
|
-
`rabetbase-dataset-generation` Skills. Install each one explicitly from the
|
|
209
|
+
The package also includes the independent `rabetbase-page-generation`,
|
|
210
|
+
`rabetbase-dataset-generation`, and `rabetbase-metrics-generation` Skills. Install each one explicitly from the
|
|
198
211
|
installed CLI package directory:
|
|
199
212
|
|
|
200
213
|
```sh
|
|
201
214
|
npx skills add /path/to/rabetbase-cli/skills/rabetbase-page-generation -g -y
|
|
202
215
|
npx skills add /path/to/rabetbase-cli/skills/rabetbase-dataset-generation -g -y
|
|
216
|
+
npx skills add /path/to/rabetbase-cli/skills/rabetbase-metrics-generation -g -y
|
|
203
217
|
```
|
|
204
218
|
|
|
205
|
-
Replace the paths with the actual package location. `
|
|
206
|
-
`rabetbase cli-skill install`, and `rabetbase doctor` manage only the main
|
|
219
|
+
Replace the paths with the actual package location. `rabetbase cli-skill install`, and `rabetbase doctor` manage only the main
|
|
207
220
|
`rabetbase` Built-in Skill; reinstall independent Skills explicitly after a CLI
|
|
208
221
|
update when needed.
|
|
209
222
|
|
|
223
|
+
The metrics companion handles explicitly authorized development requests and
|
|
224
|
+
accepted report gaps. It reuses existing cloud metrics, verifies each delivery
|
|
225
|
+
stage, and returns references to the original report task. Local source files
|
|
226
|
+
are optional development aids. Operators do not need the developer CLI to ask
|
|
227
|
+
for reports; their environment administrator provisions `lovrabet-report-generation`.
|
|
228
|
+
Verify each companion's installed name, version and references in the intended
|
|
229
|
+
Agent host; a current main Skill does not certify companion installation.
|
|
230
|
+
|
|
210
231
|
Runtime business Skills are installed with the Lovrabet runtime CLI after
|
|
211
232
|
selecting the target runtime app:
|
|
212
233
|
|
|
@@ -314,3 +335,7 @@ rabetbase issue report --title "Page push failed" --description-file ./issue.md
|
|
|
314
335
|
|
|
315
336
|
Preview the redacted content before submitting. On success, the command displays
|
|
316
337
|
`Issue log submitted`.
|
|
338
|
+
|
|
339
|
+
### 指标目录与本地校验
|
|
340
|
+
|
|
341
|
+
`rabetbase metric schema` 读取指标 JSON Schema;`rabetbase metric example` 返回单个自包含定义;`rabetbase metric validate --file <metric.json>` 检查定义、内嵌 JSON contract 及示例;`metric schema --kind contract` 读取 contract 结构。计算继续复用已有 SQL/BFF,运行态 `lovrabet metric exec` 负责调用前后校验。详见 [命令参考](skills/rabetbase/references/rabetbase-metric.md)、[定义结构](templates/metrics/metric-definition.schema.json)、[内置示例](templates/metrics/definition.json) 和 [操作指引](https://qizhiyuntu.feishu.cn/wiki/PY4DwJ2a8iyaf9koETicamgEnAf)。
|
package/lib/api/api-doc.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import{mkdirSync,writeFileSync}from"node:fs";import path from"node:path";import{fetchDatasetDoc}from"../core/api-client.js";import{logger}from"../utils/logger.js";export{fetchDatasetDoc}from"../core/api-client.js";function delay(ms){return new Promise(resolve=>setTimeout(resolve,ms))}export async function generateDatasetDocs(datasets,appCode,cookie,outputDir="./docs",onProgress,extraParams){mkdirSync(outputDir,{recursive:true});const results=[];const totalCount=datasets.length;console.log(`\n${totalCount} datasets to generate docs for\n`);for(let i=0;i<datasets.length;i++){const dataset=datasets[i];const currentIndex=i+1;const fileName=dataset.tableName;try{console.log(`[${currentIndex}/${totalCount}] Generating: ${fileName}.md (${dataset.name})`);if(onProgress)onProgress(currentIndex,totalCount,fileName);const markdown=await fetchDatasetDoc({appCode:appCode,cookie:cookie,datasetCode:dataset.datasetCode,datasetId:dataset.id,enableAI:false,extraParams:extraParams})
|
|
2
|
+
;const filePath=path.join(outputDir,`${fileName}.md`);writeFileSync(filePath,markdown,{encoding:"utf8"});console.log(`✓ Generated: ${fileName}.md`);logger.success("api-doc",`Generated docs successfully: ${fileName}`,undefined,{datasetCode:dataset.datasetCode,datasetName:dataset.name,filePath:filePath,progress:`${currentIndex}/${totalCount}`});results.push({datasetCode:dataset.datasetCode,datasetName:dataset.name,filePath:filePath,success:true});if(currentIndex<totalCount)await delay(5e3)}catch(err){const errorMessage=err instanceof Error?err.message:String(err);console.log(`✗ Failed: ${fileName}.md - ${errorMessage}`);logger.error("api-doc",`Failed to generate docs: ${dataset.datasetCode}`,{datasetCode:dataset.datasetCode,datasetName:dataset.name,error:errorMessage,progress:`${currentIndex}/${totalCount}`});results.push({datasetCode:dataset.datasetCode,datasetName:dataset.name,filePath:"",success:false,error:errorMessage});if(currentIndex<totalCount){
|
|
3
|
+
console.log("Waiting 3 seconds...\n");await delay(3e3)}}}return results}
|
package/lib/api/api-group.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import path from"node:path";import{CliErrors}from"../errors.js";export function normalizeApiDir(apiDir,baseDir=process.cwd()){return path.resolve(baseDir,apiDir)}function normalizedApiGroup(value){const normalized=value?.trim();return normalized||undefined}export function resolveApiProfileLayouts(apps,resolveOutputDir,baseDir=process.cwd()){const layouts=apps.map(app=>{const outputDir=resolveOutputDir(app);return{app:app,outputDir:outputDir,normalizedApiDir:normalizeApiDir(outputDir,baseDir),apiGroup:normalizedApiGroup(app.apiGroup)}});const directoriesByGroup=new Map;for(const layout of layouts){if(!layout.apiGroup)continue;const directories=directoriesByGroup.get(layout.apiGroup)??new Set;directories.add(layout.normalizedApiDir);directoriesByGroup.set(layout.apiGroup,directories)}for(const[apiGroup,directories]of directoriesByGroup){if(directories.size>1){
|
|
2
|
+
throw CliErrors.validation(`API group "${apiGroup}" resolves to multiple API directories.`,"Profiles in the same API group must use the same apiDir.")}}const layoutsByDirectory=new Map;for(const layout of layouts){const peers=layoutsByDirectory.get(layout.normalizedApiDir)??[];peers.push(layout);layoutsByDirectory.set(layout.normalizedApiDir,peers)}for(const peers of layoutsByDirectory.values()){const explicitGroups=new Set(peers.flatMap(layout=>layout.apiGroup?[layout.apiGroup]:[]));if(explicitGroups.size===0)continue;if(explicitGroups.size>1||peers.some(layout=>!layout.apiGroup)){const names=peers.map(layout=>layout.app.name).join(", ");throw CliErrors.validation(`API directory "${peers[0].outputDir}" is assigned to incompatible API groups.`,`Profiles sharing one apiDir must use the same explicit apiGroup. Conflicting profiles: ${names}. Use a different apiDir for a separate API.`)}}return layouts}export function getRegistryGroup(layouts,selected){if(selected.apiGroup){
|
|
3
|
+
return layouts.filter(layout=>layout.apiGroup===selected.apiGroup)}const directoryPeers=layouts.filter(layout=>layout.normalizedApiDir===selected.normalizedApiDir);return directoryPeers.length===1?directoryPeers:undefined}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export{fetchModelList}from"../core/api-client.js";
|
|
@@ -1 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
import prettier from"prettier";import{existsSync,mkdirSync,writeFileSync,readFileSync}from"node:fs";import path from"node:path";import{fileURLToPath}from"node:url";import{TemplateReplacer}from"../utils/template-replacer.js";import{CLI_BIN_NAME}from"../constant/cli.js";import{logger}from"../utils/logger.js";import{isProduction}from"../constant/env.js";import{generateSdkConfigFile}from"../api/generate-sdk-config-file.js";import{MODEL_REGISTRY_FILE_NAME,MODEL_RUNTIME_FILE_NAME,updateModelRegistry}from"../api/model-registry-file.js";import{renderModelRegistryScaffold}from"../api/model-registry-scaffold.js";function fileAction(existed,wrote){if(!wrote)return existed?"preserved":"missing";return existed?"overwritten":"created"}export async function generateApiFile(configArray,filePrefix,appCode,isFromDefaultConfig,env,outputDir,appName,sdkRouting={},options={}){if(!appCode){throw new Error(`Please configure app code first via \`${CLI_BIN_NAME} config set app <value>\``)}
|
|
2
|
+
const isDefaultConfig=isFromDefaultConfig&&!appName;const profileAware=!!options.modelProfile;const effectiveIsDefaultConfig=profileAware||isDefaultConfig;const effectiveName=appName||appCode;const publicConfigName=profileAware||isDefaultConfig?"default":effectiveName;const configNameExpression=profileAware||isDefaultConfig?"CONFIG_NAMES.DEFAULT":JSON.stringify(effectiveName);const needsEnvParam=!isProduction(env);const envPart=needsEnvParam?`, env: ${JSON.stringify(env)}`:"";const clientConfigParam=`{ apiConfigName: ${configNameExpression}${envPart}, ...LOVRABET_SDK_CONFIG }`;const effectiveFilePrefix=profileAware?"":filePrefix;const apiFileName=effectiveFilePrefix?`${effectiveFilePrefix}-api`:"api";const clientFileName=effectiveFilePrefix?`${effectiveFilePrefix}-client`:"client";const normalizedVarPrefix=effectiveFilePrefix&&!/^app-[a-f0-9]+$/i.test(effectiveFilePrefix)?effectiveFilePrefix.replace(/-/g,"_").toUpperCase():"LOVRABET"
|
|
3
|
+
;const varPrefix=/^\d/.test(normalizedVarPrefix)?`APP_${normalizedVarPrefix}`:normalizedVarPrefix;const modelConfigs=configArray.map(item=>({datasetCode:item.datasetCode,tableName:item.tableName,name:item.name||"",alias:item.alias||item.key}));const currentFilePath=fileURLToPath(import.meta.url);const cliRootDir=path.resolve(path.dirname(currentFilePath),"../..");const templateDir=path.join(cliRootDir,"templates/generate-api");const apiTemplatePath=path.join(templateDir,"api.ts.tpl");const clientTemplatePath=path.join(templateDir,"client.ts.tpl");const normalizedOutputDir=outputDir;mkdirSync(normalizedOutputDir,{recursive:true});const generatedSdkRouting=profileAware?{}:sdkRouting;const sdkConfigPath=await generateSdkConfigFile(normalizedOutputDir,generatedSdkRouting,effectiveFilePrefix);const sdkConfigFileName=path.basename(sdkConfigPath,".ts");const apiFilePath=path.join(normalizedOutputDir,`${apiFileName}.ts`)
|
|
4
|
+
;const clientFilePath=path.join(normalizedOutputDir,`${clientFileName}.ts`);const overwriteTypescript=options.overwriteTypescript===true;const apiExisted=existsSync(apiFilePath);const clientExisted=existsSync(clientFilePath);const scaffoldMode=options.scaffoldMode??(overwriteTypescript?"replace":"missing");const writeApi=scaffoldMode==="replace"||scaffoldMode==="missing"&&!apiExisted;const writeClient=scaffoldMode==="replace"||scaffoldMode==="missing"&&!clientExisted;const modelRegistry=options.modelProfile?updateModelRegistry({outputDir:normalizedOutputDir,profileName:options.modelProfile.name,defaultProfile:options.modelProfile.defaultName,appCode:appCode,runtimeDomain:options.modelProfile.runtimeDomain,models:modelConfigs,allowEmptyReplacement:options.allowEmptyModelReplacement===true}):undefined;const modelRuntimePath=modelRegistry?path.join(normalizedOutputDir,MODEL_RUNTIME_FILE_NAME):undefined;const modelRuntimeExisted=modelRuntimePath?existsSync(modelRuntimePath):false
|
|
5
|
+
;const profileScaffold=profileAware&&scaffoldMode!=="none"?await renderModelRegistryScaffold(normalizedOutputDir):undefined;if(modelRuntimePath&&profileScaffold){writeFileSync(modelRuntimePath,profileScaffold.modelRuntime,"utf8")}const exampleModelName=modelConfigs[0]?.alias;if(writeApi){const apiTemplate=profileScaffold?.api??readFileSync(apiTemplatePath,"utf8");const apiContent=profileAware?apiTemplate:TemplateReplacer.replaceApiContent(apiTemplate,appCode,modelConfigs,exampleModelName,apiFileName,configNameExpression,undefined,varPrefix);writeFileSync(apiFilePath,await prettier.format(apiContent,{parser:"typescript"}),{encoding:"utf8"})}if(writeClient){const clientTemplate=profileScaffold?.client??readFileSync(clientTemplatePath,"utf8");const clientContent=profileAware?clientTemplate:TemplateReplacer.replaceApiContent(clientTemplate,appCode,modelConfigs,exampleModelName,apiFileName,configNameExpression,clientConfigParam,varPrefix,sdkConfigFileName)
|
|
6
|
+
;writeFileSync(clientFilePath,await prettier.format(clientContent,{parser:"typescript"}),{encoding:"utf8"})}const modelCount=modelConfigs.length;const files={api:{path:apiFilePath,action:fileAction(apiExisted,writeApi)},client:{path:clientFilePath,action:fileAction(clientExisted,writeClient)},sdkConfig:{path:sdkConfigPath,action:"refreshed"},...modelRegistry?{modelRegistry:{path:modelRegistry.path,action:modelRegistry.existed?"refreshed":"created"},modelRuntime:{path:modelRuntimePath,action:profileScaffold?modelRuntimeExisted?"refreshed":"created":modelRuntimeExisted?"preserved":"missing"}}:{}};const apiUsesRegistry=existsSync(apiFilePath)&&readFileSync(apiFilePath,"utf8").includes(MODEL_REGISTRY_FILE_NAME.replace(".ts",""));const clientUsesRegistry=existsSync(clientFilePath)&&readFileSync(clientFilePath,"utf8").includes("LOVRABET_RUNTIME_DOMAIN");const needsProjectUpgrade=profileAware?!apiUsesRegistry||!clientUsesRegistry||!existsSync(modelRuntimePath):false
|
|
7
|
+
;const needsAgentMerge=profileAware?needsProjectUpgrade:files.api.action==="preserved"||files.client.action==="preserved";logger.success("init-api",needsAgentMerge?`${path.basename(sdkConfigPath)} refreshed; existing TypeScript left unchanged.`:profileAware?"Model facts refreshed.":"API scaffold written.",undefined,{apiFile:apiFilePath,clientFile:clientFilePath,sdkConfig:sdkConfigPath,modelCount:modelCount,configName:publicConfigName,isDefaultConfig:effectiveIsDefaultConfig,needsAgentMerge:needsAgentMerge,needsProjectUpgrade:needsProjectUpgrade,files:files});return{appCode:appCode,modelCount:modelCount,models:modelConfigs,apiFilePath:apiFilePath,clientFilePath:clientFilePath,sdkConfigPath:sdkConfigPath,modelRegistryPath:modelRegistry?.path,modelRuntimePath:modelRuntimePath,modelProfile:options.modelProfile?.name,configName:publicConfigName,isDefaultConfig:effectiveIsDefaultConfig,sdkRouting:generatedSdkRouting,files:files,needsAgentMerge:needsAgentMerge,
|
|
8
|
+
needsProjectUpgrade:needsProjectUpgrade}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{mkdirSync,writeFileSync}from"node:fs";import path from"node:path";import prettier from"prettier";export const SDK_CONFIG_FILE_NAME="sdk-config.ts";export function getSdkConfigFileName(filePrefix=""){return filePrefix?`${filePrefix}-sdk-config.ts`:SDK_CONFIG_FILE_NAME}export async function generateSdkConfigFile(outputDir,config={},filePrefix=""){const entries=[];if(config.runtimeDomain){entries.push(`runtimeDomain: ${JSON.stringify(config.runtimeDomain)}`)}const objectBody=entries.length>0?`{\n ${entries.join(",\n ")},\n}`:"{}";const content=`/**\n * Lovrabet SDK runtime routing.\n * Generated by Rabetbase CLI. Do not add credentials to this file.\n */\nexport const LOVRABET_SDK_CONFIG = ${objectBody} as const;\n`;mkdirSync(outputDir,{recursive:true});const filePath=path.join(outputDir,getSdkConfigFileName(filePrefix));writeFileSync(filePath,await prettier.format(content,{parser:"typescript"}),"utf8");return filePath}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
export function parseLegacyApiModels(content){const models=[];const modelRe=/\{\s*datasetCode:\s*"([^"]+)"\s*,\s*tableName:\s*"([^"]+)"\s*,\s*name:\s*"([^"]*?)"\s*,\s*alias:\s*"([^"]+)"\s*,?\s*\}/g;let match;while((match=modelRe.exec(content))!==null){models.push({datasetCode:match[1],tableName:match[2],name:match[3],alias:match[4]})}return models}export function parseLegacyApiAppCode(content){return content.match(/export\s+const\s+[A-Z0-9_]*APP_CODE(?:\s*:\s*string)?\s*=\s*["']([^"']+)["']/)?.[1]}function stripComments(content){return content.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"")}export function isLegacyGeneratedApiScaffold(content){if(!content.includes("Generated by Rabetbase CLI"))return false;const source=stripComments(content);const imports=[...source.matchAll(/^import[\s\S]*?from\s+["']([^"']+)["'];?$/gm)].map(match=>match[1]);if(imports.length!==1||imports[0]!=="@lovrabet/sdk")return false
|
|
2
|
+
;const variables=[...source.matchAll(/^(?:export\s+)?const\s+([A-Za-z_$][\w$]*)/gm)].map(match=>match[1]);if(variables.length!==2||!variables.some(name=>name.endsWith("APP_CODE"))||!variables.some(name=>name.endsWith("MODELS_CONFIG"))){return false}const topLevelCalls=[...source.matchAll(/^([A-Za-z_$][\w$]*)\s*\(/gm)].map(match=>match[1]);return topLevelCalls.length===1&&topLevelCalls[0]==="registerModels"}export function isLegacyGeneratedClientScaffold(content){if(!content.includes("Generated by Rabetbase CLI"))return false;const source=stripComments(content);const imports=[...source.matchAll(/^(?:import[\s\S]*?from\s+|import\s+)["']([^"']+)["'];?$/gm)].map(match=>match[1]);if(imports.some(moduleName=>moduleName!=="@lovrabet/sdk"&&!/^\.\/(?:[\w-]+-)?(?:api|sdk-config)$/.test(moduleName??""))){return false}const variables=[...source.matchAll(/^(?:export\s+)?const\s+([A-Za-z_$][\w$]*)/gm)].map(match=>match[1]);return variables.length===1&&variables[0]==="lovrabetClient"}
|
|
@@ -1 +1,11 @@
|
|
|
1
|
-
const a6_0x60e9b6=a6_0x4831;(function(_0x3bbfd5,_0x96e26c){const _0x4e6b5d=a6_0x4831,_0x24b7cd=_0x3bbfd5();while(!![]){try{const _0x259f3d=parseInt(_0x4e6b5d(0x107))/0x1+-parseInt(_0x4e6b5d(0x104))/0x2*(-parseInt(_0x4e6b5d(0xe3))/0x3)+-parseInt(_0x4e6b5d(0x105))/0x4*(-parseInt(_0x4e6b5d(0xe0))/0x5)+-parseInt(_0x4e6b5d(0xd6))/0x6*(parseInt(_0x4e6b5d(0xfe))/0x7)+-parseInt(_0x4e6b5d(0xe8))/0x8+parseInt(_0x4e6b5d(0xd8))/0x9+-parseInt(_0x4e6b5d(0xc9))/0xa;if(_0x259f3d===_0x96e26c)break;else _0x24b7cd['push'](_0x24b7cd['shift']());}catch(_0x1cdfc4){_0x24b7cd['push'](_0x24b7cd['shift']());}}}(a6_0x58ae,0x3beb4));function a6_0x58ae(){const _0x340d10=['split','find','test','2085328MpAEmJ','includes','protocol','.tmp','string','\x22\x20maps\x20to\x20both\x20aliases\x20\x22','datasetCode','object','Refusing\x20to\x20replace\x20','alias','join','\x22\x20maps\x20to\x20both\x20\x22','defaultProfile','profiles','every','models','push','utf8','map','set','now','tableName','301cvcEgI','length','value','indexOf','\x20model(s)\x20in\x20profile\x20\x22','lovrabet-model-registry/v1','26ZMPzHx','68muhtAH','entries','373642NpkvIa','stringify','pid','appCode','filter','outputDir','\x22\x20with\x20an\x20empty\x20result.\x20','name','5091100tlCKzS','\x0aexport\x20const\x20LOVRABET_MODEL_REGISTRY\x20=\x0a\x20\x20','flatMap','Model\x20alias\x20\x22','parse','profileName','\x22\x20and\x20\x22','/*\x20rabetbase-model-registry:start\x20*/','keys','NOT-SET','model-runtime.ts','/**\x0a\x20*\x20Dataset\x20model\x20facts\x20generated\x20by\x20Rabetbase\x20CLI.\x0a\x20*\x0a\x20*\x20This\x20file\x20is\x20safe\x20to\x20commit.\x20Do\x20not\x20edit\x20it\x20manually\x20and\x20never\x20add\x20credentials.\x0a\x20*/\x0a\x0aexport\x20interface\x20LovrabetModelProfile\x20{\x0a\x20\x20appCode:\x20string;\x0a\x20\x20runtimeDomain:\x20string;\x0a}\x0a\x0aexport\x20interface\x20LovrabetModelEntryMetadata\x20{\x0a\x20\x20alias:\x20string;\x0a\x20\x20tableName:\x20string;\x0a\x20\x20name:\x20string;\x0a}\x0a\x0aexport\x20type\x20LovrabetModelEntry\x20=\x20LovrabetModelEntryMetadata\x20&\x20(\x0a\x20\x20|\x20{\x20datasetCode:\x20string;\x20datasetCodes?:\x20never\x20}\x0a\x20\x20|\x20{\x20datasetCode?:\x20never;\x20datasetCodes:\x20Record<string,\x20string>\x20}\x0a);\x0a\x0aexport\x20interface\x20LovrabetModelRegistry\x20{\x0a\x20\x20defaultProfile:\x20string;\x0a\x20\x20profiles:\x20Record<string,\x20LovrabetModelProfile>;\x0a\x20\x20models:\x20LovrabetModelEntry[];\x0a}\x0a\x0a','\x22\x20in\x20the\x20registry\x20but\x20\x22','6krmimZ','replace','4319766YAJGGq','models.generated.ts','Table\x20\x22','get','datasetCodes','isArray','slice','\x22\x20maps\x20to\x20alias\x20\x22','38320GorXGn','\x20is\x20not\x20a\x20valid\x20Rabetbase\x20generated\x20file.\x20Move\x20or\x20repair\x20it\x20before\x20pulling\x20models\x20again.','runtimeDomain','7233rbAXYG','\x22\x20in\x20profile\x20\x22'];a6_0x58ae=function(){return _0x340d10;};return a6_0x58ae();}import{existsSync,mkdirSync,readFileSync,renameSync,unlinkSync,writeFileSync}from'node:fs';import a6_0x5ec771 from'node:path';export const MODEL_REGISTRY_FILE_NAME=a6_0x60e9b6(0xd9);export const MODEL_RUNTIME_FILE_NAME=a6_0x60e9b6(0xd3);export const MODEL_REGISTRY_VERSION_MARKER='/*\x20rabetbase-model-registry:v2\x20*/';const LEGACY_MODEL_REGISTRY_V2_PROTOCOL='lovrabet-model-registry/v2',REGISTRY_START=a6_0x60e9b6(0xd0),REGISTRY_END='/*\x20rabetbase-model-registry:end\x20*/';function emptyRegistry(_0x2f070e){return{'defaultProfile':_0x2f070e,'profiles':{},'models':[]};}function extractRegistryJson(_0x38b8af){const _0x34d787=a6_0x60e9b6,_0x345900=_0x38b8af[_0x34d787(0x101)](REGISTRY_START),_0xf7a373=_0x38b8af[_0x34d787(0x101)](REGISTRY_END);if(_0x345900<0x0||_0xf7a373<=_0x345900)return undefined;return _0x38b8af[_0x34d787(0xde)](_0x345900+REGISTRY_START[_0x34d787(0xff)],_0xf7a373)['trim']()[_0x34d787(0xd7)](/\s+as const satisfies LovrabetModelRegistry;?$/,'')['replace'](/;$/,'');}function migrateLegacyRegistry(_0x3fff9e){const _0xe0d59a=a6_0x60e9b6,_0x4d0877=emptyRegistry(_0x3fff9e[_0xe0d59a(0xf4)]);for(const [_0x457ec0,_0x22722a]of Object[_0xe0d59a(0x106)](_0x3fff9e[_0xe0d59a(0xf5)])){_0x4d0877['profiles'][_0x457ec0]={'appCode':_0x22722a[_0xe0d59a(0x10a)],'runtimeDomain':_0x22722a[_0xe0d59a(0xe2)]},mergeProfileModels(_0x4d0877,_0x457ec0,_0x22722a[_0xe0d59a(0xf7)]);}return _0x4d0877;}function generatedObjectLiteralToJson(_0x3bda03){const _0x5e7734=a6_0x60e9b6;let _0x2aac74='',_0x19197,_0x1670ce=![],_0x5b282b;for(let _0x36d81e=0x0;_0x36d81e<_0x3bda03['length'];_0x36d81e++){const _0xaff153=_0x3bda03[_0x36d81e];if(_0x19197){_0x2aac74+=_0xaff153;if(_0x1670ce)_0x1670ce=![];else{if(_0xaff153==='\x5c')_0x1670ce=!![];else{if(_0xaff153===_0x19197)_0x19197=undefined;}}continue;}if(_0xaff153==='\x22'){_0x19197=_0xaff153,_0x2aac74+=_0xaff153,_0x5b282b=_0x5e7734(0x100);continue;}if(_0xaff153===','){let _0x5ac4ab=_0x36d81e+0x1;while(/\s/[_0x5e7734(0xe7)](_0x3bda03[_0x5ac4ab]??''))_0x5ac4ab++;if(_0x3bda03[_0x5ac4ab]==='}'||_0x3bda03[_0x5ac4ab]===']')continue;_0x2aac74+=_0xaff153,_0x5b282b=',';continue;}if(_0xaff153==='{'||_0xaff153==='['){_0x2aac74+=_0xaff153,_0x5b282b=_0xaff153;continue;}if(_0xaff153==='}'||_0xaff153===']'){_0x2aac74+=_0xaff153,_0x5b282b=_0xaff153;continue;}if((_0x5b282b==='{'||_0x5b282b===',')&&/[A-Za-z_$]/['test'](_0xaff153)){let _0x1ad8fc=_0x36d81e+0x1;while(/[A-Za-z0-9_$]/[_0x5e7734(0xe7)](_0x3bda03[_0x1ad8fc]??''))_0x1ad8fc++;let _0x2fc84b=_0x1ad8fc;while(/\s/[_0x5e7734(0xe7)](_0x3bda03[_0x2fc84b]??''))_0x2fc84b++;if(_0x3bda03[_0x2fc84b]===':'){_0x2aac74+=JSON[_0x5e7734(0x108)](_0x3bda03[_0x5e7734(0xde)](_0x36d81e,_0x1ad8fc)),_0x36d81e=_0x1ad8fc-0x1,_0x5b282b='key';continue;}}_0x2aac74+=_0xaff153;if(!/\s/[_0x5e7734(0xe7)](_0xaff153)&&_0xaff153!==':')_0x5b282b=_0x5e7734(0x100);}return _0x2aac74;}function parseGeneratedRegistryJson(_0x2bcdd2){const _0x94d045=a6_0x60e9b6;try{return JSON[_0x94d045(0xcd)](_0x2bcdd2);}catch{return JSON['parse'](generatedObjectLiteralToJson(_0x2bcdd2));}}function normalizeModelEntries(_0x42fa6d,_0xe8f4f6){const _0xf69f12=a6_0x60e9b6,_0x5c9a26=Object['keys'](_0x42fa6d),_0x488db3=[];for(const _0xff9b88 of _0xe8f4f6){if(!_0xff9b88||typeof _0xff9b88!=='object'||Array['isArray'](_0xff9b88))return undefined;const _0x5e8bca=_0xff9b88;if(typeof _0x5e8bca[_0xf69f12(0xf1)]!==_0xf69f12(0xec)||typeof _0x5e8bca[_0xf69f12(0xfd)]!==_0xf69f12(0xec)||typeof _0x5e8bca[_0xf69f12(0xc8)]!=='string')return undefined;let _0xf91122;if(typeof _0x5e8bca['datasetCode']===_0xf69f12(0xec)&&_0x5e8bca['datasetCodes']===undefined)_0xf91122=Object['fromEntries'](_0x5c9a26['map'](_0x50ba61=>[_0x50ba61,_0x5e8bca[_0xf69f12(0xee)]]));else{if(_0x5e8bca[_0xf69f12(0xee)]===undefined&&_0x5e8bca[_0xf69f12(0xdc)]&&typeof _0x5e8bca[_0xf69f12(0xdc)]===_0xf69f12(0xef)&&!Array[_0xf69f12(0xdd)](_0x5e8bca['datasetCodes'])&&Object['values'](_0x5e8bca[_0xf69f12(0xdc)])[_0xf69f12(0xf6)](_0x2d415d=>typeof _0x2d415d===_0xf69f12(0xec)))_0xf91122={..._0x5e8bca[_0xf69f12(0xdc)]};else return undefined;}_0x488db3[_0xf69f12(0xf8)]({'alias':_0x5e8bca[_0xf69f12(0xf1)],'tableName':_0x5e8bca[_0xf69f12(0xfd)],'name':_0x5e8bca[_0xf69f12(0xc8)],'datasetCodes':_0xf91122});}return _0x488db3;}export function parseModelRegistry(_0x232871){const _0x4aa111=a6_0x60e9b6,_0x18f59d=extractRegistryJson(_0x232871);if(!_0x18f59d)return undefined;try{const _0x4137bc=parseGeneratedRegistryJson(_0x18f59d);if(typeof _0x4137bc[_0x4aa111(0xf4)]!=='string'||!_0x4137bc[_0x4aa111(0xf5)]||typeof _0x4137bc[_0x4aa111(0xf5)]!==_0x4aa111(0xef))return undefined;if(_0x4137bc[_0x4aa111(0xea)]===_0x4aa111(0x103))return migrateLegacyRegistry(_0x4137bc);if(!(_0x4137bc[_0x4aa111(0xea)]===LEGACY_MODEL_REGISTRY_V2_PROTOCOL||_0x4137bc[_0x4aa111(0xea)]===undefined&&_0x232871[_0x4aa111(0xe9)](MODEL_REGISTRY_VERSION_MARKER))||!Array['isArray'](_0x4137bc[_0x4aa111(0xf7)]))return undefined;const _0x10bf34=_0x4137bc[_0x4aa111(0xf5)],_0x44786a=normalizeModelEntries(_0x10bf34,_0x4137bc[_0x4aa111(0xf7)]);if(!_0x44786a)return undefined;return{'defaultProfile':_0x4137bc[_0x4aa111(0xf4)],'profiles':_0x10bf34,'models':_0x44786a};}catch{return undefined;}}export function readModelRegistry(_0x127f5e){const _0x4c4724=a6_0x60e9b6;if(!existsSync(_0x127f5e))return undefined;try{return parseModelRegistry(readFileSync(_0x127f5e,_0x4c4724(0xf9)));}catch{return undefined;}}function a6_0x4831(_0x25f425,_0x449d92){_0x25f425=_0x25f425-0xc8;const _0x58aeb2=a6_0x58ae();let _0x4831f6=_0x58aeb2[_0x25f425];return _0x4831f6;}function registrySource(_0x52574a){const _0x19c392=a6_0x60e9b6,_0x29f212=Object[_0x19c392(0xd1)](_0x52574a[_0x19c392(0xf5)]),_0x332573=_0x52574a[_0x19c392(0xf7)]['map'](_0x4cc8c9=>{const _0x2d63e7=_0x19c392,_0x3183ab=_0x29f212['map'](_0x4f06ec=>_0x4cc8c9[_0x2d63e7(0xdc)][_0x4f06ec]),_0x2be0e0=_0x3183ab[0x0],_0x4c2ae6=_0x2be0e0!==undefined&&_0x3183ab[_0x2d63e7(0xf6)](_0x387a80=>_0x387a80===_0x2be0e0),_0x1f2cd1={'alias':_0x4cc8c9[_0x2d63e7(0xf1)],'tableName':_0x4cc8c9[_0x2d63e7(0xfd)],'name':_0x4cc8c9[_0x2d63e7(0xc8)]};return _0x4c2ae6?{..._0x1f2cd1,'datasetCode':_0x2be0e0}:{..._0x1f2cd1,'datasetCodes':_0x4cc8c9['datasetCodes']};}),_0x4d6a7f=JSON['stringify']({'defaultProfile':_0x52574a[_0x19c392(0xf4)],'profiles':_0x52574a['profiles'],'models':_0x332573},null,0x2)[_0x19c392(0xe5)]('\x0a')[_0x19c392(0xfa)](_0x1ec64c=>'\x20\x20'+_0x1ec64c)['join']('\x0a');return _0x19c392(0xd4)+MODEL_REGISTRY_VERSION_MARKER+_0x19c392(0xca)+REGISTRY_START+'\x0a'+_0x4d6a7f+'\x20as\x20const\x20satisfies\x20LovrabetModelRegistry;\x0a'+REGISTRY_END+'\x0a';}function mergeProfileModels(_0x4dc7ed,_0x44ddbf,_0x30c74f){const _0x4fb574=a6_0x60e9b6,_0x42f8b7=_0x30c74f[_0x4fb574(0xfa)](_0x28e898=>({..._0x28e898,'alias':_0x28e898[_0x4fb574(0xf1)]||_0x28e898[_0x4fb574(0xfd)]})),_0x403950=new Map(),_0x3747a8=new Map();for(const _0x5e3ef4 of _0x42f8b7){const _0x217c6b=_0x403950[_0x4fb574(0xdb)](_0x5e3ef4['alias']);if(_0x217c6b&&_0x217c6b!==_0x5e3ef4['tableName'])throw new Error(_0x4fb574(0xcc)+_0x5e3ef4[_0x4fb574(0xf1)]+_0x4fb574(0xf3)+_0x217c6b+_0x4fb574(0xcf)+_0x5e3ef4[_0x4fb574(0xfd)]+_0x4fb574(0xe4)+_0x44ddbf+'\x22.');const _0xd4a339=_0x3747a8['get'](_0x5e3ef4[_0x4fb574(0xfd)]);if(_0xd4a339&&_0xd4a339!==_0x5e3ef4[_0x4fb574(0xf1)])throw new Error(_0x4fb574(0xda)+_0x5e3ef4['tableName']+_0x4fb574(0xed)+_0xd4a339+'\x22\x20and\x20\x22'+_0x5e3ef4[_0x4fb574(0xf1)]+_0x4fb574(0xe4)+_0x44ddbf+'\x22.');_0x403950[_0x4fb574(0xfb)](_0x5e3ef4[_0x4fb574(0xf1)],_0x5e3ef4[_0x4fb574(0xfd)]),_0x3747a8[_0x4fb574(0xfb)](_0x5e3ef4[_0x4fb574(0xfd)],_0x5e3ef4['alias']);const _0x642ead=_0x4dc7ed[_0x4fb574(0xf7)]['find'](_0x341bd8=>_0x341bd8[_0x4fb574(0xf1)]===_0x5e3ef4[_0x4fb574(0xf1)]);if(_0x642ead&&_0x642ead[_0x4fb574(0xfd)]!==_0x5e3ef4['tableName'])throw new Error(_0x4fb574(0xcc)+_0x5e3ef4[_0x4fb574(0xf1)]+'\x22\x20maps\x20to\x20table\x20\x22'+_0x642ead[_0x4fb574(0xfd)]+_0x4fb574(0xd5)+_0x5e3ef4[_0x4fb574(0xfd)]+_0x4fb574(0xe4)+_0x44ddbf+'\x22.');const _0x3cb446=_0x4dc7ed[_0x4fb574(0xf7)][_0x4fb574(0xe6)](_0x31b5c8=>_0x31b5c8['tableName']===_0x5e3ef4['tableName']);if(_0x3cb446&&_0x3cb446['alias']!==_0x5e3ef4[_0x4fb574(0xf1)])throw new Error(_0x4fb574(0xda)+_0x5e3ef4['tableName']+_0x4fb574(0xdf)+_0x3cb446[_0x4fb574(0xf1)]+_0x4fb574(0xd5)+_0x5e3ef4[_0x4fb574(0xf1)]+'\x22\x20in\x20profile\x20\x22'+_0x44ddbf+'\x22.');}for(const _0x11cac1 of _0x4dc7ed[_0x4fb574(0xf7)]){delete _0x11cac1[_0x4fb574(0xdc)][_0x44ddbf];}for(const _0x231c79 of _0x42f8b7){let _0x4d69cd=_0x4dc7ed['models']['find'](_0x62cfb7=>_0x62cfb7['alias']===_0x231c79[_0x4fb574(0xf1)]);!_0x4d69cd&&(_0x4d69cd={'alias':_0x231c79[_0x4fb574(0xf1)],'tableName':_0x231c79[_0x4fb574(0xfd)],'name':_0x231c79['name'],'datasetCodes':{}},_0x4dc7ed[_0x4fb574(0xf7)][_0x4fb574(0xf8)](_0x4d69cd)),(_0x44ddbf===_0x4dc7ed[_0x4fb574(0xf4)]||!_0x4d69cd['datasetCodes'][_0x4dc7ed[_0x4fb574(0xf4)]])&&(_0x4d69cd[_0x4fb574(0xf1)]=_0x231c79[_0x4fb574(0xf1)],_0x4d69cd[_0x4fb574(0xfd)]=_0x231c79['tableName'],_0x4d69cd['name']=_0x231c79[_0x4fb574(0xc8)]),_0x4d69cd['datasetCodes'][_0x44ddbf]=_0x231c79[_0x4fb574(0xee)];}_0x4dc7ed[_0x4fb574(0xf7)]=_0x4dc7ed[_0x4fb574(0xf7)][_0x4fb574(0x10b)](_0x1ceca1=>Object[_0x4fb574(0xd1)](_0x1ceca1['datasetCodes'])['length']>0x0);}function removeUnboundProfiles(_0x46e1e9){const _0xea414d=a6_0x60e9b6,_0x59f220=Object['entries'](_0x46e1e9[_0xea414d(0xf5)])[_0xea414d(0x10b)](([,_0xc6b488])=>_0xc6b488[_0xea414d(0x10a)]===_0xea414d(0xd2))[_0xea414d(0xfa)](([_0x43e65d])=>_0x43e65d);if(_0x59f220[_0xea414d(0xff)]===0x0)return;for(const _0xea2a08 of _0x59f220){delete _0x46e1e9[_0xea414d(0xf5)][_0xea2a08];for(const _0x1ff897 of _0x46e1e9[_0xea414d(0xf7)]){delete _0x1ff897[_0xea414d(0xdc)][_0xea2a08];}}_0x46e1e9[_0xea414d(0xf7)]=_0x46e1e9['models']['filter'](_0x1dc252=>Object[_0xea414d(0xd1)](_0x1dc252[_0xea414d(0xdc)])[_0xea414d(0xff)]>0x0);}export function getProfileModels(_0x59480d,_0x5131ad){const _0x2a756f=a6_0x60e9b6;return _0x59480d[_0x2a756f(0xf7)][_0x2a756f(0xcb)](_0x423ab8=>{const _0x246599=_0x2a756f,_0x243949=_0x423ab8[_0x246599(0xdc)][_0x5131ad];return _0x243949?[{'datasetCode':_0x243949,'tableName':_0x423ab8['tableName'],'name':_0x423ab8['name'],'alias':_0x423ab8['alias']}]:[];});}export function updateModelRegistry(_0x14a7fc){const _0x40100c=a6_0x60e9b6,_0x13876f=a6_0x5ec771[_0x40100c(0xf2)](_0x14a7fc[_0x40100c(0x10c)],MODEL_REGISTRY_FILE_NAME),_0x1985fa=existsSync(_0x13876f),_0x3abe65=readModelRegistry(_0x13876f);if(_0x1985fa&&!_0x3abe65)throw new Error(MODEL_REGISTRY_FILE_NAME+_0x40100c(0xe1));const _0x910e46=_0x3abe65??emptyRegistry(_0x14a7fc[_0x40100c(0xf4)]);if(_0x14a7fc[_0x40100c(0x10a)]!==_0x40100c(0xd2))removeUnboundProfiles(_0x910e46);const _0x55e030=_0x3abe65?getProfileModels(_0x3abe65,_0x14a7fc[_0x40100c(0xce)])['length']:0x0;if(_0x55e030>0x0&&_0x14a7fc[_0x40100c(0xf7)][_0x40100c(0xff)]===0x0&&!_0x14a7fc['allowEmptyReplacement'])throw new Error(_0x40100c(0xf0)+_0x55e030+_0x40100c(0x102)+_0x14a7fc[_0x40100c(0xce)]+_0x40100c(0x10d)+'Verify\x20the\x20selected\x20app\x20and\x20login,\x20or\x20rerun\x20with\x20--force\x20--yes\x20if\x20the\x20profile\x20is\x20intentionally\x20empty.');_0x910e46['defaultProfile']=_0x14a7fc[_0x40100c(0xf4)],_0x910e46['profiles'][_0x14a7fc[_0x40100c(0xce)]]={'appCode':_0x14a7fc[_0x40100c(0x10a)],'runtimeDomain':_0x14a7fc[_0x40100c(0xe2)]},mergeProfileModels(_0x910e46,_0x14a7fc[_0x40100c(0xce)],_0x14a7fc[_0x40100c(0xf7)]),mkdirSync(_0x14a7fc['outputDir'],{'recursive':!![]});const _0x1da86f=_0x13876f+'.'+process[_0x40100c(0x109)]+'.'+Date[_0x40100c(0xfc)]()+_0x40100c(0xeb);try{writeFileSync(_0x1da86f,registrySource(_0x910e46),{'encoding':_0x40100c(0xf9),'mode':0x1a4}),renameSync(_0x1da86f,_0x13876f);}catch(_0xa854ac){try{unlinkSync(_0x1da86f);}catch{}throw _0xa854ac;}return{'path':_0x13876f,'registry':_0x910e46,'existed':_0x1985fa};}
|
|
1
|
+
import{existsSync,mkdirSync,readFileSync,renameSync,unlinkSync,writeFileSync}from"node:fs";import path from"node:path";export const MODEL_REGISTRY_FILE_NAME="models.generated.ts";export const MODEL_RUNTIME_FILE_NAME="model-runtime.ts";export const MODEL_REGISTRY_VERSION_MARKER="/* rabetbase-model-registry:v2 */";const LEGACY_MODEL_REGISTRY_V2_PROTOCOL="lovrabet-model-registry/v2";const REGISTRY_START="/* rabetbase-model-registry:start */";const REGISTRY_END="/* rabetbase-model-registry:end */";function emptyRegistry(defaultProfile){return{defaultProfile:defaultProfile,profiles:{},models:[]}}function extractRegistryJson(content){const start=content.indexOf(REGISTRY_START);const end=content.indexOf(REGISTRY_END);if(start<0||end<=start)return undefined;return content.slice(start+REGISTRY_START.length,end).trim().replace(/\s+as const satisfies LovrabetModelRegistry;?$/,"").replace(/;$/,"")}function migrateLegacyRegistry(legacy){const registry=emptyRegistry(legacy.defaultProfile)
|
|
2
|
+
;for(const[profileName,profile]of Object.entries(legacy.profiles)){registry.profiles[profileName]={appCode:profile.appCode,runtimeDomain:profile.runtimeDomain};mergeProfileModels(registry,profileName,profile.models)}return registry}function generatedObjectLiteralToJson(source){let result="";let quote;let escaped=false;let previousToken;for(let index=0;index<source.length;index++){const char=source[index];if(quote){result+=char;if(escaped)escaped=false;else if(char==="\\")escaped=true;else if(char===quote)quote=undefined;continue}if(char==='"'){quote=char;result+=char;previousToken="value";continue}if(char===","){let cursor=index+1;while(/\s/.test(source[cursor]??""))cursor++;if(source[cursor]==="}"||source[cursor]==="]")continue;result+=char;previousToken=",";continue}if(char==="{"||char==="["){result+=char;previousToken=char;continue}if(char==="}"||char==="]"){result+=char;previousToken=char;continue}if((previousToken==="{"||previousToken===",")&&/[A-Za-z_$]/.test(char)){
|
|
3
|
+
let cursor=index+1;while(/[A-Za-z0-9_$]/.test(source[cursor]??""))cursor++;let colon=cursor;while(/\s/.test(source[colon]??""))colon++;if(source[colon]===":"){result+=JSON.stringify(source.slice(index,cursor));index=cursor-1;previousToken="key";continue}}result+=char;if(!/\s/.test(char)&&char!==":")previousToken="value"}return result}function parseGeneratedRegistryJson(json){try{return JSON.parse(json)}catch{return JSON.parse(generatedObjectLiteralToJson(json))}}function normalizeModelEntries(profiles,models){const profileNames=Object.keys(profiles);const normalized=[];for(const value of models){if(!value||typeof value!=="object"||Array.isArray(value))return undefined;const entry=value;if(typeof entry.alias!=="string"||typeof entry.tableName!=="string"||typeof entry.name!=="string"){return undefined}let datasetCodes;if(typeof entry.datasetCode==="string"&&entry.datasetCodes===undefined){datasetCodes=Object.fromEntries(profileNames.map(profileName=>[profileName,entry.datasetCode]))
|
|
4
|
+
}else if(entry.datasetCode===undefined&&entry.datasetCodes&&typeof entry.datasetCodes==="object"&&!Array.isArray(entry.datasetCodes)&&Object.values(entry.datasetCodes).every(code=>typeof code==="string")){datasetCodes={...entry.datasetCodes}}else{return undefined}normalized.push({alias:entry.alias,tableName:entry.tableName,name:entry.name,datasetCodes:datasetCodes})}return normalized}export function parseModelRegistry(content){const json=extractRegistryJson(content);if(!json)return undefined;try{const parsed=parseGeneratedRegistryJson(json);if(typeof parsed.defaultProfile!=="string"||!parsed.profiles||typeof parsed.profiles!=="object"){return undefined}if(parsed.protocol==="lovrabet-model-registry/v1"){return migrateLegacyRegistry(parsed)}if(!(parsed.protocol===LEGACY_MODEL_REGISTRY_V2_PROTOCOL||parsed.protocol===undefined&&content.includes(MODEL_REGISTRY_VERSION_MARKER))||!Array.isArray(parsed.models)){return undefined}const profiles=parsed.profiles
|
|
5
|
+
;const models=normalizeModelEntries(profiles,parsed.models);if(!models)return undefined;return{defaultProfile:parsed.defaultProfile,profiles:profiles,models:models}}catch{return undefined}}export function readModelRegistry(filePath){if(!existsSync(filePath))return undefined;try{return parseModelRegistry(readFileSync(filePath,"utf8"))}catch{return undefined}}function registrySource(registry){const profileNames=Object.keys(registry.profiles);const persistedModels=registry.models.map(model=>{const codes=profileNames.map(profileName=>model.datasetCodes[profileName]);const commonDatasetCode=codes[0];const isCommon=commonDatasetCode!==undefined&&codes.every(code=>code===commonDatasetCode);const metadata={alias:model.alias,tableName:model.tableName,name:model.name};return isCommon?{...metadata,datasetCode:commonDatasetCode}:{...metadata,datasetCodes:model.datasetCodes}});const serialized=JSON.stringify({defaultProfile:registry.defaultProfile,profiles:registry.profiles,models:persistedModels
|
|
6
|
+
},null,2).split("\n").map(line=>` ${line}`).join("\n");return`/**\n * Dataset model facts generated by Rabetbase CLI.\n *\n * This file is safe to commit. Do not edit it manually and never add credentials.\n */\n\nexport interface LovrabetModelProfile {\n appCode: string;\n runtimeDomain: string;\n}\n\nexport interface LovrabetModelEntryMetadata {\n alias: string;\n tableName: string;\n name: string;\n}\n\nexport type LovrabetModelEntry = LovrabetModelEntryMetadata & (\n | { datasetCode: string; datasetCodes?: never }\n | { datasetCode?: never; datasetCodes: Record<string, string> }\n);\n\nexport interface LovrabetModelRegistry {\n defaultProfile: string;\n profiles: Record<string, LovrabetModelProfile>;\n models: LovrabetModelEntry[];\n}\n\n${MODEL_REGISTRY_VERSION_MARKER}\nexport const LOVRABET_MODEL_REGISTRY =\n ${REGISTRY_START}\n${serialized} as const satisfies LovrabetModelRegistry;\n${REGISTRY_END}\n`}function mergeProfileModels(registry,profileName,incomingModels){
|
|
7
|
+
const normalizedIncoming=incomingModels.map(incoming=>({...incoming,alias:incoming.alias||incoming.tableName}));const incomingAliases=new Map;const incomingTables=new Map;for(const incoming of normalizedIncoming){const aliasTable=incomingAliases.get(incoming.alias);if(aliasTable&&aliasTable!==incoming.tableName){throw new Error(`Model alias "${incoming.alias}" maps to both "${aliasTable}" and "${incoming.tableName}" in profile "${profileName}".`)}const tableAlias=incomingTables.get(incoming.tableName);if(tableAlias&&tableAlias!==incoming.alias){throw new Error(`Table "${incoming.tableName}" maps to both aliases "${tableAlias}" and "${incoming.alias}" in profile "${profileName}".`)}incomingAliases.set(incoming.alias,incoming.tableName);incomingTables.set(incoming.tableName,incoming.alias);const aliasEntry=registry.models.find(model=>model.alias===incoming.alias);if(aliasEntry&&aliasEntry.tableName!==incoming.tableName){
|
|
8
|
+
throw new Error(`Model alias "${incoming.alias}" maps to table "${aliasEntry.tableName}" in the registry but "${incoming.tableName}" in profile "${profileName}".`)}const tableEntry=registry.models.find(model=>model.tableName===incoming.tableName);if(tableEntry&&tableEntry.alias!==incoming.alias){throw new Error(`Table "${incoming.tableName}" maps to alias "${tableEntry.alias}" in the registry but "${incoming.alias}" in profile "${profileName}".`)}}for(const model of registry.models){delete model.datasetCodes[profileName]}for(const incoming of normalizedIncoming){let entry=registry.models.find(model=>model.alias===incoming.alias);if(!entry){entry={alias:incoming.alias,tableName:incoming.tableName,name:incoming.name,datasetCodes:{}};registry.models.push(entry)}if(profileName===registry.defaultProfile||!entry.datasetCodes[registry.defaultProfile]){entry.alias=incoming.alias;entry.tableName=incoming.tableName;entry.name=incoming.name}entry.datasetCodes[profileName]=incoming.datasetCode}
|
|
9
|
+
registry.models=registry.models.filter(model=>Object.keys(model.datasetCodes).length>0)}function removeUnboundProfiles(registry){const unboundProfileNames=Object.entries(registry.profiles).filter(([,profile])=>profile.appCode==="NOT-SET").map(([profileName])=>profileName);if(unboundProfileNames.length===0)return;for(const profileName of unboundProfileNames){delete registry.profiles[profileName];for(const model of registry.models){delete model.datasetCodes[profileName]}}registry.models=registry.models.filter(model=>Object.keys(model.datasetCodes).length>0)}export function getProfileModels(registry,profileName){return registry.models.flatMap(model=>{const datasetCode=model.datasetCodes[profileName];return datasetCode?[{datasetCode:datasetCode,tableName:model.tableName,name:model.name,alias:model.alias}]:[]})}export function updateModelRegistry(options){const filePath=path.join(options.outputDir,MODEL_REGISTRY_FILE_NAME);const existed=existsSync(filePath)
|
|
10
|
+
;const existing=readModelRegistry(filePath);if(existed&&!existing){throw new Error(`${MODEL_REGISTRY_FILE_NAME} is not a valid Rabetbase generated file. Move or repair it before pulling models again.`)}const registry=existing??emptyRegistry(options.defaultProfile);if(options.appCode!=="NOT-SET")removeUnboundProfiles(registry);const existingProfileModelCount=existing?getProfileModels(existing,options.profileName).length:0;if(existingProfileModelCount>0&&options.models.length===0&&!options.allowEmptyReplacement){throw new Error(`Refusing to replace ${existingProfileModelCount} model(s) in profile "${options.profileName}" with an empty result. `+"Verify the selected app and login, or rerun with --force --yes if the profile is intentionally empty.")}registry.defaultProfile=options.defaultProfile;registry.profiles[options.profileName]={appCode:options.appCode,runtimeDomain:options.runtimeDomain};mergeProfileModels(registry,options.profileName,options.models);mkdirSync(options.outputDir,{
|
|
11
|
+
recursive:true});const tempPath=`${filePath}.${process.pid}.${Date.now()}.tmp`;try{writeFileSync(tempPath,registrySource(registry),{encoding:"utf8",mode:420});renameSync(tempPath,filePath)}catch(error){try{unlinkSync(tempPath)}catch{}throw error}return{path:filePath,registry:registry,existed:existed}}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{readFileSync}from"node:fs";import path from"node:path";import{fileURLToPath}from"node:url";import prettier from"prettier";import{PROJECT_DOMAIN_ROUTING_FILE_NAME}from"../config/project-domain-routing.js";function relativeImport(fromDir,targetPath){let value=path.relative(fromDir,targetPath).replace(/\\/g,"/");if(!value.startsWith("."))value=`./${value}`;return value}export async function renderModelRegistryScaffold(outputDir,projectRoot=process.cwd()){const currentFilePath=fileURLToPath(import.meta.url);const templateDir=path.resolve(path.dirname(currentFilePath),"../../templates/generate-api");const routingImport=relativeImport(path.resolve(outputDir),path.resolve(projectRoot,PROJECT_DOMAIN_ROUTING_FILE_NAME));const apiTemplate=readFileSync(path.join(templateDir,"profile-api.ts.tpl"),"utf8").replace("{ProjectRoutingImport}",routingImport);const[api,client,modelRuntime]=await Promise.all([prettier.format(apiTemplate,{parser:"typescript"
|
|
2
|
+
}),prettier.format(readFileSync(path.join(templateDir,"profile-client.ts.tpl"),"utf8"),{parser:"typescript"}),prettier.format(readFileSync(path.join(templateDir,"model-runtime.ts.tpl"),"utf8"),{parser:"typescript"})]);return{api:api,client:client,modelRuntime:modelRuntime}}
|
package/lib/api/model-source.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import{existsSync}from"node:fs";import path from"node:path";import{readRawConfig}from"../context/config-loader.js";import{MODEL_REGISTRY_FILE_NAME,readModelRegistry}from"../api/model-registry-file.js";import{CliErrors}from"../errors.js";import{CLI_BIN_NAME}from"../constant/cli.js";export function resolveApiModelSource(apiDir,appCode,selectedAppName){const absDir=path.resolve(process.cwd(),apiDir);const defaultPath=path.resolve(absDir,"api.ts");const registryPath=path.resolve(absDir,MODEL_REGISTRY_FILE_NAME);const registry=readModelRegistry(registryPath);if(registry){const matches=appCode?Object.entries(registry.profiles).filter(([,profile])=>profile.appCode===appCode):[];if(selectedAppName){if(registry.profiles[selectedAppName]){return{filePath:registryPath,profileName:selectedAppName}}if(matches.length>0){throw CliErrors.validation(`Model profile "${selectedAppName}" is missing from ${MODEL_REGISTRY_FILE_NAME}.`,`Run \`${CLI_BIN_NAME} api pull --app ${selectedAppName}\` first.`)}
|
|
2
|
+
}else{if(matches.length===1){return{filePath:registryPath,profileName:matches[0][0]}}if(matches.length>1){throw new Error(`AppCode "${appCode}" belongs to multiple model profiles: ${matches.map(([name])=>name).join(", ")}. `+"Select the target explicitly with --app <profile>.")}if(registry.profiles[registry.defaultProfile]&&!appCode){return{filePath:registryPath,profileName:registry.defaultProfile}}}}if(!appCode&&!selectedAppName)return{filePath:defaultPath};const config=readRawConfig();const apps=config.apps&&typeof config.apps==="object"?config.apps:{};const matchedEntry=selectedAppName&&apps[selectedAppName]?[selectedAppName,apps[selectedAppName]]:Object.entries(apps).find(([,profile])=>profile?.appcode===appCode);if(!matchedEntry)return{filePath:defaultPath};const[appName,profile]=matchedEntry;const defaultApp=typeof config.defaultApp==="string"?config.defaultApp:undefined;if(profile?.apiDir)return{filePath:defaultPath};if(defaultApp&&appName!==defaultApp){
|
|
3
|
+
const namedPath=path.resolve(absDir,`${appName}-api.ts`);if(existsSync(namedPath))return{filePath:namedPath}}return{filePath:defaultPath}}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{getIsSessionValid}from"../auth/is-session-valid.js";import{authServer}from"../auth/auth-server.js";import{CLI_BIN_NAME}from"../constant/cli.js";import{CliErrors}from"../errors.js";import{confirm}from"@inquirer/prompts";import ora from"ora";export async function runAuthServer(options){const isValid=await getIsSessionValid();if(isValid){console.log("√ Valid session detected, no login required.");return}if(options?.nonInteractive&&!options.autoYes){throw CliErrors.validation("Browser login cannot run in non-interactive mode.",`Run \`${CLI_BIN_NAME} auth login --yes\` and open the printed URL in your browser.`)}const shouldLogin=options?.autoYes?true:await confirm({message:"No valid session. Login now?",default:true});if(!shouldLogin)return;if(options?.nonInteractive){console.log("Starting browser login. Share the printed URL with the user.");const success=await authServer({silent:false,openBrowser:false});if(success){console.log("* Login successful!")}else{
|
|
2
|
+
console.log("! Login failed.")}return}const spinner=ora("Logging in... Please complete login in your browser.").start();const success=await authServer({silent:true,openBrowser:true});spinner.stop();if(success){console.log("* Login successful!")}else{console.log("! Login failed.")}}
|
package/lib/auth/auth-server.js
CHANGED
|
@@ -1 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import{writeFileSync}from"node:fs";import http from"node:http";import https from"node:https";import{getUserDomain}from"../constant/domain.js";import{getOfficialRoutingCdn,getOfficialRoutingProfile}from"../constant/routing-profile.js";import{getProjectDomainRoutingManifest}from"../config/project-domain-routing.js";import{exec}from"node:child_process";import{getIsSessionValid}from"../auth/is-session-valid.js";import{cookieFile}from"../auth/constant.js";import{buildLoginSuccessHtml}from"../auth/login-success-html.js";export const AUTH_LOGIN_TIMEOUT_MS=10*60*1e3;export function resolveAuthCallbackRouting(region){if(!region)return getProjectDomainRoutingManifest().local;const profile=getOfficialRoutingProfile(region);const cdn=getOfficialRoutingCdn(region);return{origin:profile.local.origin,certificateUrl:`${cdn.lovrabet}/cert/lovrabet-dev.json`}}function withPort(origin,port){const url=new URL(origin);url.port=String(port);return url.origin}export async function authServer(params){
|
|
2
|
+
const silent=params?.silent||false;const openBrowser=params?.openBrowser??true;const timeoutMs=params?.timeoutMs??AUTH_LOGIN_TIMEOUT_MS;if(await getIsSessionValid()){return true}const callbackRouting=resolveAuthCallbackRouting();const ssl=callbackRouting.certificateUrl?await(await fetch(callbackRouting.certificateUrl)).json():undefined;return new Promise(async(resolve,reject)=>{let port=0;let settled=false;let timeout;const handleRequest=async(req,res)=>{const userDomain=getUserDomain();const cookie=req.headers.cookie||"";const session=await fetch(`${userDomain}/api/auth/get-session`,{headers:{cookie:cookie}}).then(r=>r.json());const isSuccess=session&&session.session&&session.user;if(isSuccess){writeFileSync(cookieFile,cookie,"utf-8");const html=buildLoginSuccessHtml();res.writeHead(200,{"Content-Type":"text/html; charset=utf-8"});res.end(html);finish(true)}else{const redirect=encodeURIComponent(withPort(callbackRouting.origin,port));res.writeHead(302,{
|
|
3
|
+
location:`${userDomain}/sign-in?redirect=${redirect}`});res.end();return}};const server=ssl?https.createServer(ssl,handleRequest):http.createServer(handleRequest);function finish(success){if(settled)return;settled=true;if(timeout){clearTimeout(timeout)}server.close();resolve(success)}server.listen(0,"127.0.0.1",()=>{const addr=server.address();port=typeof addr==="object"&&addr?addr.port:Number(addr);const loginUrl=withPort(callbackRouting.origin,port);timeout=setTimeout(()=>{if(!silent){console.log("! Login URL expired after 10 minutes. Run the login command again to get a new URL.")}finish(false)},timeoutMs);if(!silent){console.log("🔐 Starting login service...");console.log("📍 Login URL:",loginUrl);if(openBrowser){console.log("🌐 Attempting to open browser automatically...");console.log("");console.log("💡 If the browser does not open automatically, copy the login URL above into your browser.")}else{
|
|
4
|
+
console.log("💡 Open the login URL above in your browser to complete authorization.")}console.log("")}if(!openBrowser){return}openInBrowser(loginUrl).then(success=>{if(!silent){if(success){console.log("✅ Browser opened. Please complete login in the browser.")}else{console.log("⚠️ Failed to open browser automatically");console.log("🔗 Please copy the login URL into your browser:",loginUrl)}console.log("")}}).catch(()=>{if(!silent){console.log("⚠️ Failed to open browser automatically");console.log("🔗 Please copy the login URL into your browser:",loginUrl);console.log("")}})});server.on("error",e=>{if(settled)return;settled=true;if(timeout){clearTimeout(timeout)}if(!silent){console.error("Auth server error:",e)}server.close();reject(e)})})}function openInBrowser(url){return new Promise(resolve=>{const platform=process.platform;let cmd;if(platform==="win32"){cmd=`cmd /c start "" "${url}"`}else if(platform==="darwin"){cmd=`open "${url}"`}else{cmd=`xdg-open "${url}"`}exec(cmd,err=>{
|
|
5
|
+
if(err){resolve(false)}else{resolve(true)}})})}if(import.meta.main){const isAuth=await authServer();console.log("isAuth",isAuth)}
|
package/lib/auth/constant.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{mkdirSync}from"node:fs";import{homedir}from"node:os";import{join}from"node:path";export const configDir=join(homedir(),".lovrabet");export const cookieFile=join(configDir,"cookie");mkdirSync(configDir,{recursive:true});
|
package/lib/auth/get-cookie.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{readFileSync}from"node:fs";import{cookieFile}from"../auth/constant.js";export function getCookie(){try{return readFileSync(cookieFile,"utf-8")}catch{}return""}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{existsSync,readFileSync}from"node:fs";import{getUserDomain}from"../constant/domain.js";import{cookieFile}from"../auth/constant.js";export async function getSessionUserInfo(cookie){try{if(cookie===undefined){if(!existsSync(cookieFile))return null;cookie=readFileSync(cookieFile,"utf-8")}if(!cookie)return null;const res=await fetch(`${getUserDomain()}/api/auth/get-session`,{headers:{cookie:cookie}});if(!res.ok){return null}const body=await res.json();if(!body.session||!body.user){return null}return body}catch{return null}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{existsSync,readFileSync}from"node:fs";import{getUserDomain}from"../constant/domain.js";import{cookieFile}from"../auth/constant.js";export async function getIsSessionValid(){try{if(!existsSync(cookieFile)){return false}const cookie=readFileSync(cookieFile,"utf-8");const session=await fetch(`${getUserDomain()}/api/auth/get-session`,{headers:{cookie:cookie}}).then(r=>r.json());return session&&session.session&&session.user}catch{}return false}
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
function
|
|
1
|
+
export function buildLoginSuccessHtml(){const manualClose="Unable to close automatically. Please close this tab or window manually."
|
|
2
|
+
;return`<!doctype html>\n<html lang="en">\n<head>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <title>Login successful · Rabetbase CLI</title>\n <style>\n :root {\n --bg0: #0f1419;\n --bg1: #1a2332;\n --card: #ffffff;\n --text: #1c2128;\n --muted: #5c6570;\n --accent: #2563eb;\n --accent-soft: #eff6ff;\n --success: #059669;\n --radius: 16px;\n --shadow: 0 25px 50px -12px rgba(15, 20, 25, 0.35);\n }\n * { box-sizing: border-box; }\n body {\n margin: 0;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 24px;\n font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto,\n "Helvetica Neue", Arial, "Noto Sans", "PingFang SC", "Microsoft YaHei", sans-serif;\n background: linear-gradient(160deg, var(--bg0) 0%, var(--bg1) 45%, #243047 100%);\n color: var(--text);\n }\n .card {\n width: 100%;\n max-width: 420px;\n background: var(--card);\n border-radius: var(--radius);\n box-shadow: var(--shadow);\n padding: 40px 36px 32px;\n text-align: center;\n }\n .icon {\n width: 64px;\n height: 64px;\n margin: 0 auto 20px;\n border-radius: 50%;\n background: var(--accent-soft);\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .icon svg { width: 36px; height: 36px; }\n h1 {\n margin: 0 0 12px;\n font-size: 1.375rem;\n font-weight: 600;\n letter-spacing: -0.02em;\n }\n p.lead {\n margin: 0 0 8px;\n font-size: 0.9375rem;\n color: var(--muted);\n line-height: 1.55;\n }\n .countdown {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n margin-top: 16px;\n padding: 8px 14px;\n font-size: 0.875rem;\n font-variant-numeric: tabular-nums;\n color: var(--accent);\n background: var(--accent-soft);\n border-radius: 999px;\n font-weight: 500;\n }\n #manualMsg {\n display: none;\n margin-top: 20px;\n font-size: 0.8125rem;\n color: #b91c1c;\n line-height: 1.45;\n }\n .cli-hint {\n margin-top: 28px;\n padding-top: 24px;\n border-top: 1px solid #e8ecf0;\n font-size: 0.75rem;\n color: #8b949e;\n }\n </style>\n</head>\n<body>\n <div class="card" role="status" aria-live="polite">\n <div class="icon" aria-hidden="true">\n <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <circle cx="12" cy="12" r="10" stroke="#059669" stroke-width="2" fill="none"/>\n <path d="M8 12.5l2.5 2.5L16 9" stroke="#059669" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n </div>\n <h1>Login successful</h1>\n <p class="lead">You can return to the terminal to continue. This window will try to close automatically.</p>\n <div class="countdown">\n Closing in <span id="t">5</span>s\n </div>\n <div id="manualMsg">${manualClose}</div>\n <p class="cli-hint">Rabetbase CLI · session saved locally</p>\n </div>\n <script>\n (function(){\n var t = 5;\n var el = document.getElementById('t');\n var manual = document.getElementById('manualMsg');\n var id = setInterval(function(){\n t--;\n if (t <= 0) {\n clearInterval(id);\n el.textContent = '0';\n try { window.close(); } catch(e) {}\n setTimeout(function(){\n if (!window.closed) {\n manual.style.display = 'block';\n }\n }, 300);\n } else {\n el.textContent = String(t);\n }\n }, 1000);\n })();\n <\/script>\n</body>\n</html>`
|
|
3
|
+
}
|
package/lib/auth/logout.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{unlinkSync,existsSync}from"node:fs";import{cookieFile}from"../auth/constant.js";export function logout(){if(existsSync(cookieFile)){unlinkSync(cookieFile);console.log("✓ Logged out")}else{console.log("! Not logged in")}}
|
package/lib/cli-flags.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export const dynamicCliFlags={enableBffSave:{type:"boolean"}};
|
package/lib/cli.js
CHANGED
|
@@ -1,2 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
2
|
+
import meow from"meow";import{showHelp}from"./help.js";import{CliError,CliErrors}from"./errors.js";import{isKnownService,getServiceEntry,findDefinition,resolveRemovedCommand}from"./commands/registry.js";import{runCommand,createPipelineEnv}from"./framework/runner.js";import{formatCliError}from"./framework/output.js";import{resolveErrorOutputFormat,usesStructuredErrorOutput}from"./framework/error-output.js";import{generateCommandHelp,generateServiceHelp,generateFullHelp}from"./framework/help.js";import{CLI_BIN_NAME,buildMeowFlags}from"./constant/cli.js";import{VERSION,GIT_COMMIT,BUILD_TIME}from"./generated/build-info.js";import{reportCliHelpTrace}from"./telemetry/cli-help-trace.js";import{reportCommandTrace}from"./telemetry/cli-command-trace.js";import{registerOtelShutdownOnExit,exitWithOtelShutdown}from"./telemetry/register-otel-exit-shutdown.js";import{printIssueReportNudgeForError}from"./commands/issue/nudge.js";import{assertSupportedCommandFlags}from"./framework/supported-flags.js"
|
|
3
|
+
;let dynamicCliFlags=null;try{dynamicCliFlags=(await(import("./cli-flags.js"))).dynamicCliFlags}catch{}const helpText=generateFullHelp();const cliVersion=GIT_COMMIT!=="unknown"?`${VERSION} (${GIT_COMMIT}, ${BUILD_TIME.slice(0,10)})`:VERSION;const cli=meow(helpText,{importMeta:import.meta,version:cliVersion,flags:{...buildMeowFlags(),...dynamicCliFlags||{}}});registerOtelShutdownOnExit();await run().catch(handleErrorAsync);async function run(){let service=cli.input[0];let command=cli.input[1];const flags=cli.flags;if(!service){await reportCliHelpTrace("global");showHelp();return}const removedCommand=resolveRemovedCommand(service,command);if(removedCommand){await handleErrorAsync(CliErrors.validation(removedCommand.message,removedCommand.hint))}if(!isKnownService(service)){await reportCliHelpTrace("unknown_service",{service:service});showHelp();return}const entry=getServiceEntry(service);if(!command){if(flags.help){printServiceHelp(service);return}if(entry.defaultCommand){
|
|
4
|
+
command=entry.defaultCommand}else if(entry.wildcardDef){const{buildConfigFromFlags:buildConfigFromFlags,initGlobalEnvironment:initGlobalEnvironment}=await(import("./context.js"));const cliConfig=buildConfigFromFlags(flags);await initGlobalEnvironment(cliConfig);await dispatchDeclarative(entry.wildcardDef,service,"",[],flags,cliConfig);return}else{printServiceHelp(service);return}}{let def=findDefinition(service,command);let pipelineArgs=cli.input.slice(2);if(!def){if(entry.wildcardDef){if(flags.help){console.log(generateCommandHelp(entry.wildcardDef));return}def=entry.wildcardDef;pipelineArgs=[command,...cli.input.slice(2)]}else{printServiceHelp(service);await handleErrorAsync(CliErrors.unknownCommand(`${service} ${command}`));return}}assertSupportedCommandFlags(def,flags);if(flags.help){console.log(generateCommandHelp(def));return}
|
|
5
|
+
const{buildConfigFromFlags:buildConfigFromFlags,initGlobalEnvironment:initGlobalEnvironment,isRoutingRecoveryService:isRoutingRecoveryService}=await(import("./context.js"));const cliConfig=buildConfigFromFlags(flags);if(!isRoutingRecoveryService(service)){await initGlobalEnvironment(cliConfig)}await dispatchDeclarative(def,service,command,pipelineArgs,flags,cliConfig)}}async function dispatchDeclarative(def,service,command,pipelineArgs,flags,cliConfig){const startTime=Date.now();let cmdErr;try{await runCommand(def,createPipelineEnv(cliConfig,flags,pipelineArgs))}catch(err){cmdErr=err}await reportCommandTrace({service:service,command:command,flags:flags,durationMs:Date.now()-startTime,error:cmdErr});if(cmdErr){await handleErrorAsync(cmdErr,{service:service,command:command,def:def,flags:flags,defaultFormat:cliConfig.format})}}function printServiceHelp(service){console.log(generateServiceHelp(service))}async function handleErrorAsync(err,currentCommand){
|
|
6
|
+
if(err instanceof Error&&err.name==="ExitPromptError"){process.stderr.write("\nCancelled.\n");return await exitWithOtelShutdown(0)}if(err instanceof CliError){if(err.code==="cancelled"){process.stderr.write(`\n${err.message}\n`);return await exitWithOtelShutdown(0)}let structured=false;if(currentCommand&&usesStructuredErrorOutput(currentCommand.def)){structured=formatCliError(err,{command:`${CLI_BIN_NAME} ${currentCommand.def.service} ${currentCommand.def.command}`,risk:currentCommand.def.risk,format:resolveErrorOutputFormat(currentCommand),jqFilter:typeof currentCommand.flags?.jq==="string"?currentCommand.flags.jq:undefined})}if(!structured){console.error(`Error: ${err.message}`);if(err.hint)console.error(`Hint: ${err.hint}`);if(currentCommand)printIssueReportNudgeForError(err,currentCommand)}return await exitWithOtelShutdown(err.exitCode)}console.error("Unexpected error:",err);if(currentCommand)printIssueReportNudgeForError(err,currentCommand);return await exitWithOtelShutdown(1)}
|
|
@@ -1 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import ora from"ora";import{fetchModelList}from"../../core/api-client.js";import{generateDatasetDocs}from"../../api/api-doc.js";import{CliErrors}from"../../errors.js";import{APPCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{writeCliSideChannelLine}from"../../utils/write-cli-side-channel.js";export const apiGenerate={service:"api",command:"generate",description:"Generate markdown documentation for all datasets",risk:"read",requiresAppCode:true,hasFormat:false,flags:[{...APPCODE_FLAG_OPTIONAL,hidden:true},{name:"output",type:"string",description:"Output directory (default: ./docs)"},{name:"datasetcode",type:"string",description:"Filter: comma-separated dataset codes to generate docs for"},{name:"params",type:"string",description:"Extra params passed to the doc generator (JSON object)"}],async execute(ctx){const outputDir=ctx.str("output")||"./docs";const datasetcodeStr=ctx.str("datasetcode");const paramsStr=ctx.str("params");let extraParams;if(paramsStr){try{
|
|
2
|
+
extraParams=JSON.parse(paramsStr);if(typeof extraParams!=="object"||extraParams===null||Array.isArray(extraParams)){throw new Error("must be a JSON object")}}catch(err){throw CliErrors.validation(`Invalid --params: ${err instanceof Error?err.message:String(err)}`,`Provide a valid JSON object, e.g. --params '{"key":"value"}'`)}}let filterCodes;if(datasetcodeStr){const codes=datasetcodeStr.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(codes.length===0){throw CliErrors.validation("--datasetcode cannot be empty.")}filterCodes=new Set(codes);writeCliSideChannelLine(`[90m* Generating docs for: ${codes.join(", ")}[0m`)}const spinner=ora(`Fetching dataset list for ${ctx.appCode}...`).start();let configArray;try{({configArray:configArray}=await fetchModelList(ctx.appCode,ctx.cookie));spinner.succeed(`Fetched ${configArray.length} dataset(s)`)}catch(err){spinner.fail("Failed to fetch datasets");throw err}if(configArray.length===0){writeCliSideChannelLine("! No datasets found.");return{
|
|
3
|
+
ok:true}}let datasetsToGenerate=configArray;if(filterCodes){datasetsToGenerate=configArray.filter(d=>filterCodes.has(d.datasetCode));const notFound=[...filterCodes].filter(c=>!configArray.some(d=>d.datasetCode===c));if(notFound.length>0){writeCliSideChannelLine(`[33m! The following dataset codes do not exist: ${notFound.join(", ")}[0m`)}if(datasetsToGenerate.length===0){throw CliErrors.validation(`None of the specified dataset codes exist: ${[...filterCodes].join(", ")}`)}writeCliSideChannelLine(`[90m* Filtered ${datasetsToGenerate.length} of ${configArray.length} dataset(s)[0m`)}let current=0;const results=await generateDatasetDocs(datasetsToGenerate,ctx.appCode,ctx.cookie,outputDir,(idx,total,fileName)=>{current=idx;process.stdout.write(`\r [${String(idx).padStart(String(total).length)}/${total}] ${fileName}.md`)},extraParams);if(current>0)process.stdout.write("\n");const succeeded=results.filter(r=>r.success).length;const failed=results.filter(r=>!r.success).length
|
|
4
|
+
;writeCliSideChannelLine("");writeCliSideChannelLine(`✓ Generated ${succeeded} doc(s) in ${outputDir}`);if(failed>0){writeCliSideChannelLine(`! ${failed} doc(s) failed`);for(const r of results.filter(r=>!r.success)){writeCliSideChannelLine(` • ${r.datasetName} (${r.datasetCode}): ${r.error}`)}}return{ok:failed===0,message:failed>0?`Doc generation: ${succeeded} succeeded, ${failed} failed`:`Doc generation complete: ${succeeded} file(s)`}}};
|