@lovrabet/rabetbase-cli 2.6.0-beta.3 → 2.6.0-beta.4

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.
Files changed (51) hide show
  1. package/README.md +6 -2
  2. package/lib/auth/auth-server.js +5 -5
  3. package/lib/auth/get-session-user.js +1 -1
  4. package/lib/auth/is-session-valid.js +1 -1
  5. package/lib/commands/config/init.d.ts +1 -1
  6. package/lib/commands/config/init.js +5 -5
  7. package/lib/commands/doctor.js +3 -3
  8. package/lib/commands/metric/contract.d.ts +8 -6
  9. package/lib/commands/metric/contract.js +3 -5
  10. package/lib/commands/metric/definition.d.ts +31 -31
  11. package/lib/commands/metric/definition.js +5 -4
  12. package/lib/commands/metric/delete.js +3 -3
  13. package/lib/commands/metric/detail.js +2 -1
  14. package/lib/commands/metric/list.js +2 -2
  15. package/lib/commands/metric/publish.js +5 -4
  16. package/lib/commands/metric/shared.d.ts +4 -0
  17. package/lib/commands/metric/shared.js +2 -1
  18. package/lib/commands/metric/validate.js +1 -1
  19. package/lib/config/domain-config.d.ts +1 -1
  20. package/lib/config/domain-config.js +9 -8
  21. package/lib/config/schema.d.ts +1 -1
  22. package/lib/config/schema.js +7 -7
  23. package/lib/constant/domain.d.ts +10 -0
  24. package/lib/constant/domain.js +4 -4
  25. package/lib/constant/routing-profile.d.ts +16 -16
  26. package/lib/context/config-loader.js +3 -3
  27. package/lib/context.js +8 -7
  28. package/lib/core/api-client.d.ts +43 -2
  29. package/lib/core/api-client.js +15 -12
  30. package/lib/generated/build-info.d.ts +4 -4
  31. package/lib/generated/build-info.js +1 -1
  32. package/lib/generated/official-routing.d.ts +17 -17
  33. package/lib/generated/official-routing.js +3 -3
  34. package/lib/telemetry/ensure-cli-otel-config.js +1 -1
  35. package/package.json +3 -2
  36. package/skills/rabetbase/SKILL.md +1 -1
  37. package/skills/rabetbase/guides/metric-development.md +26 -24
  38. package/skills/rabetbase/references/rabetbase-config.md +2 -1
  39. package/skills/rabetbase/references/rabetbase-db-analyze.md +2 -2
  40. package/skills/rabetbase/references/rabetbase-db-create.md +1 -1
  41. package/skills/rabetbase/references/rabetbase-flow-commands.md +1 -1
  42. package/skills/rabetbase/references/rabetbase-init.md +6 -4
  43. package/skills/rabetbase/references/rabetbase-menu-list.md +1 -1
  44. package/skills/rabetbase/references/rabetbase-metric.md +44 -64
  45. package/skills/rabetbase-dataset-generation/SKILL.md +1 -1
  46. package/skills/rabetbase-metrics-generation/SKILL.md +1 -1
  47. package/skills/rabetbase-metrics-generation/references/verification.md +1 -1
  48. package/skills/rabetbase-page-generation/SKILL.md +1 -1
  49. package/skills/rabetbase.manifest.json +3 -3
  50. package/templates/metrics/definition.json +33 -64
  51. package/templates/metrics/metric-definition.schema.json +81 -104
package/README.md CHANGED
@@ -124,7 +124,7 @@ For an independent deployment, import a versioned routing manifest instead of
124
124
  adding region-specific conditions to commands:
125
125
 
126
126
  ```bash
127
- rabetbase config init --domain-config ./lovrabet-domains.json
127
+ rabetbase config init --domain-config ./lovrabet-domains.json --user-center-domain https://user.customer.example.com
128
128
  ```
129
129
 
130
130
  ```json
@@ -136,7 +136,7 @@ rabetbase config init --domain-config ./lovrabet-domains.json
136
136
  "lovrabet": "https://g.lovrabet.com"
137
137
  },
138
138
  "domains": {
139
- "userDomain": "https://user.customer.example.com",
139
+ "userDomain": "https://accounts-api.customer.example.com",
140
140
  "apiDomain": "https://api.customer.example.com",
141
141
  "runtimeDomain": "https://runtime.customer.example.com",
142
142
  "skillDomain": "https://skills.customer.example.com",
@@ -150,6 +150,10 @@ rabetbase config init --domain-config ./lovrabet-domains.json
150
150
  }
151
151
  ```
152
152
 
153
+ The CLI stores the optional browser origin (`userCenterDomain`) at the top level of its own configuration. The manifest supplies `userDomain` for the user-center API.
154
+ If your deployment serves both on the same host, set both fields to that origin when upgrading.
155
+ Omitting `userCenterDomain` selects the official page for the region and environment via `@lovrabet/fetch`.
156
+
153
157
  A Domain can be a shared HTTPS origin string or a consumer-specific object.
154
158
  Rabetbase resolves `rabetbase-cli` first and then `default`; if neither exists,
155
159
  the import fails instead of sending requests to another consumer's Domain.
@@ -1,5 +1,5 @@
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)}
1
+ import{writeFileSync}from"node:fs";import http from"node:http";import https from"node:https";import{requireAuthApiDomain,getUserPageDomain}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}
2
+ export async function authServer(params){const silent=params?.silent||false;const openBrowser=params?.openBrowser??true;const timeoutMs=params?.timeoutMs??AUTH_LOGIN_TIMEOUT_MS;const userApiDomain=requireAuthApiDomain();if(await getIsSessionValid()){return true}const userPageDomain=getUserPageDomain();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 cookie=req.headers.cookie||"";const session=await fetch(`${userApiDomain}/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{
3
+ const redirect=encodeURIComponent(withPort(callbackRouting.origin,port));res.writeHead(302,{location:`${userPageDomain}/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("")
4
+ ;console.log("💡 If the browser does not open automatically, copy the login URL above into your browser.")}else{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"){
5
+ cmd=`cmd /c start "" "${url}"`}else if(platform==="darwin"){cmd=`open "${url}"`}else{cmd=`xdg-open "${url}"`}exec(cmd,err=>{if(err){resolve(false)}else{resolve(true)}})})}if(import.meta.main){const isAuth=await authServer();console.log("isAuth",isAuth)}
@@ -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
+ import{getCookie}from"../auth/get-cookie.js";import{requireAuthApiDomain}from"../constant/domain.js";export async function getSessionUserInfo(cookie){const sessionCookie=cookie??getCookie();if(!sessionCookie)return null;const userApiDomain=requireAuthApiDomain();try{const res=await fetch(`${userApiDomain}/api/auth/get-session`,{headers:{cookie:sessionCookie}});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
- 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
+ import{existsSync,readFileSync}from"node:fs";import{getAuthApiDomain}from"../constant/domain.js";import{cookieFile}from"../auth/constant.js";export async function getIsSessionValid(){const userApiDomain=getAuthApiDomain();if(!userApiDomain)return false;try{if(!existsSync(cookieFile)){return false}const cookie=readFileSync(cookieFile,"utf-8");const session=await fetch(`${userApiDomain}/api/auth/get-session`,{headers:{cookie:cookie}}).then(r=>r.json());return session&&session.session&&session.user}catch{}return false}
@@ -7,7 +7,7 @@ export declare function executeConfigInit(ctx: RuntimeContext): Promise<{
7
7
  mode: string;
8
8
  protocol: "lovrabet-routing/v1" | undefined;
9
9
  region: "global" | "id" | "cn" | null;
10
- domains: Partial<Record<"apiDomain" | "userDomain" | "runtimeDomain" | "skillDomain" | "kbDomain" | "kbServiceDomain" | "appDomain" | "localDomain" | "certificateDomain", string>>;
10
+ domains: Partial<Record<"apiDomain" | "userDomain" | "userCenterDomain" | "runtimeDomain" | "skillDomain" | "kbDomain" | "kbServiceDomain" | "appDomain" | "localDomain" | "certificateDomain", string>>;
11
11
  cdn: import("../../config/domain-config.js").EnterpriseRoutingCdn | undefined;
12
12
  };
13
13
  }>;
@@ -1,5 +1,5 @@
1
- import{select}from"@inquirer/prompts";import{withDiagnostic,CliErrors}from"../../errors.js";import{readScopedConfig,writeScopedConfig}from"../../commands/config/shared.js";import{DOMAIN_CONFIG_FIELDS,LEGACY_DOMAIN_CONFIG_FIELDS,resolveDomainConfigInput}from"../../config/domain-config.js";import{ENTERPRISE_ROUTING_KIND,ENTERPRISE_ROUTING_PROTOCOL}from"../../generated/routing-contract.js";import{DEFAULT_LOVRABET_REGION,ENABLED_LOVRABET_REGION_VALUES,isEnabledLovrabetRegion}from"../../constant/region.js";import{getOfficialRoutingProfile}from"../../constant/routing-profile.js";import{GLOBAL_SCOPE_FLAG}from"../../commands/common/flags.js";export const configInitFlags=[GLOBAL_SCOPE_FLAG,{name:"region",type:"string",description:`Official Lovrabet region: ${ENABLED_LOVRABET_REGION_VALUES.join(", ")}`,enum:[...ENABLED_LOVRABET_REGION_VALUES]},{name:"domain-config",type:"string",description:"Independent-deployment Domain JSON file"},{name:"user-domain",type:"string",
2
- description:"Custom User HTTPS origin"},{name:"api-domain",type:"string",description:"Custom platform API HTTPS origin"},{name:"runtime-domain",type:"string",description:"Custom Runtime HTTPS origin"},{name:"skill-domain",type:"string",description:"Custom SkillHub HTTPS origin"},{name:"kb-domain",type:"string",description:"Custom knowledge-base HTTPS origin"},{name:"kb-service-domain",type:"string",description:"Custom KB Service HTTPS origin"},{name:"app-domain",type:"string",description:"Custom Lovrabet workspace HTTPS origin"},{name:"local-domain",type:"string",description:"Custom local callback HTTPS origin"},{name:"certificate-domain",type:"string",description:"Custom certificate service HTTPS origin"}];async function resolveRegion(ctx){const explicit=ctx.str("region");if(explicit){if(!isEnabledLovrabetRegion(explicit)){throw withDiagnostic(CliErrors.validation(`Region "${explicit}" is not currently available.`),`Available regions: ${ENABLED_LOVRABET_REGION_VALUES.join(", ")}`)}
3
- return explicit}if(ctx.nonInteractive)return DEFAULT_LOVRABET_REGION;try{return await select({message:"Select Lovrabet region",default:DEFAULT_LOVRABET_REGION,choices:ENABLED_LOVRABET_REGION_VALUES.map(region=>({name:`${getOfficialRoutingProfile(region).label} (${region})`,value:region}))})}catch(err){if(err?.name==="ExitPromptError"){throw CliErrors.cancelled()}throw err}}export async function executeConfigInit(ctx){const routingInput=resolveDomainConfigInput(ctx);const domains=routingInput.domains;const hasDomains=Object.keys(domains).length>0;if(hasDomains&&ctx.str("region")){throw CliErrors.validation("Choose either an official region or independent-deployment Domains, not both.")}if(!!domains.localDomain!==!!domains.certificateDomain){throw CliErrors.validation("Independent deployment requires --local-domain and --certificate-domain together.")}const scope=ctx.bool("global")?"global":"project";const config=readScopedConfig(scope)
4
- ;for(const field of DOMAIN_CONFIG_FIELDS)delete config[field];for(const field of LEGACY_DOMAIN_CONFIG_FIELDS)delete config[field];delete config.routing;let region=null;if(hasDomains){delete config.region;if(routingInput.mode==="enterprise-v1"){config.routing={protocol:ENTERPRISE_ROUTING_PROTOCOL,kind:ENTERPRISE_ROUTING_KIND,domains:routingInput.manifestDomains,cdn:routingInput.cdn}}else{Object.assign(config,domains)}}else{region=await resolveRegion(ctx);if(region===DEFAULT_LOVRABET_REGION)delete config.region;else config.region=region}writeScopedConfig(config,scope);return{ok:true,message:hasDomains?`Rabetbase connection configured for independent deployment. Domains: ${Object.keys(routingInput.mode==="enterprise-v1"?routingInput.manifestDomains:domains).join(", ")}.`:`Rabetbase connection configured for region: ${region}.`,data:{mode:hasDomains?"independent":"official",protocol:routingInput.mode==="enterprise-v1"?ENTERPRISE_ROUTING_PROTOCOL:undefined,region:region,domains:domains,
5
- cdn:routingInput.mode==="enterprise-v1"?routingInput.cdn:undefined}}}export const configInitDefinition={service:"config",command:"init",description:"Initialize the Lovrabet region or independent-deployment Domains",risk:"write",confirmationDescription:"Updates the selected Rabetbase region or independent-deployment Domain configuration. Cookie, output format, and app bindings stay unchanged.",requiresAuth:false,requiresAppCode:false,hasFormat:false,flags:configInitFlags,execute:executeConfigInit};
1
+ import{select}from"@inquirer/prompts";import{withDiagnostic,CliErrors}from"../../errors.js";import{readScopedConfig,writeScopedConfig}from"../../commands/config/shared.js";import{DOMAIN_CONFIG_FIELDS,LEGACY_DOMAIN_CONFIG_FIELDS,resolveDomainConfigInput}from"../../config/domain-config.js";import{ENTERPRISE_ROUTING_KIND,ENTERPRISE_ROUTING_PROTOCOL}from"../../generated/routing-contract.js";import{DEFAULT_LOVRABET_REGION,ENABLED_LOVRABET_REGION_VALUES,isEnabledLovrabetRegion}from"../../constant/region.js";import{getOfficialRoutingProfile}from"../../constant/routing-profile.js";import{GLOBAL_SCOPE_FLAG}from"../../commands/common/flags.js";export const configInitFlags=[GLOBAL_SCOPE_FLAG,{name:"region",type:"string",description:`Official Lovrabet region: ${ENABLED_LOVRABET_REGION_VALUES.join(", ")}`,enum:[...ENABLED_LOVRABET_REGION_VALUES]},{name:"domain-config",type:"string",description:"Independent-deployment Domain JSON file"},{name:"user-center-domain",type:"string",
2
+ description:"Custom user-center browser HTTPS origin"},{name:"user-domain",type:"string",description:"Custom user-center API HTTPS origin"},{name:"api-domain",type:"string",description:"Custom platform API HTTPS origin"},{name:"runtime-domain",type:"string",description:"Custom Runtime HTTPS origin"},{name:"skill-domain",type:"string",description:"Custom SkillHub HTTPS origin"},{name:"kb-domain",type:"string",description:"Custom knowledge-base HTTPS origin"},{name:"kb-service-domain",type:"string",description:"Custom KB Service HTTPS origin"},{name:"app-domain",type:"string",description:"Custom Lovrabet workspace HTTPS origin"},{name:"local-domain",type:"string",description:"Custom local callback HTTPS origin"},{name:"certificate-domain",type:"string",description:"Custom certificate service HTTPS origin"}];async function resolveRegion(ctx){const explicit=ctx.str("region");if(explicit){if(!isEnabledLovrabetRegion(explicit)){
3
+ throw withDiagnostic(CliErrors.validation(`Region "${explicit}" is not currently available.`),`Available regions: ${ENABLED_LOVRABET_REGION_VALUES.join(", ")}`)}return explicit}if(ctx.nonInteractive)return DEFAULT_LOVRABET_REGION;try{return await select({message:"Select Lovrabet region",default:DEFAULT_LOVRABET_REGION,choices:ENABLED_LOVRABET_REGION_VALUES.map(region=>({name:`${getOfficialRoutingProfile(region).label} (${region})`,value:region}))})}catch(err){if(err?.name==="ExitPromptError"){throw CliErrors.cancelled()}throw err}}export async function executeConfigInit(ctx){const routingInput=resolveDomainConfigInput(ctx);const domains=routingInput.domains;const hasDomains=Object.keys(domains).length>0;if(hasDomains&&ctx.str("region")){throw CliErrors.validation("Choose either an official region or independent-deployment Domains, not both.")}if(!!domains.localDomain!==!!domains.certificateDomain){
4
+ throw CliErrors.validation("Independent deployment requires --local-domain and --certificate-domain together.")}const scope=ctx.bool("global")?"global":"project";const config=readScopedConfig(scope);for(const field of DOMAIN_CONFIG_FIELDS)delete config[field];for(const field of LEGACY_DOMAIN_CONFIG_FIELDS)delete config[field];delete config.routing;let region=null;if(hasDomains){delete config.region;if(routingInput.mode==="enterprise-v1"){config.routing={protocol:ENTERPRISE_ROUTING_PROTOCOL,kind:ENTERPRISE_ROUTING_KIND,domains:routingInput.manifestDomains,cdn:routingInput.cdn};if(domains.userCenterDomain)config.userCenterDomain=domains.userCenterDomain}else{Object.assign(config,domains)}}else{region=await resolveRegion(ctx);if(region===DEFAULT_LOVRABET_REGION)delete config.region;else config.region=region}writeScopedConfig(config,scope);return{ok:true,
5
+ message:hasDomains?`Rabetbase connection configured for independent deployment. Domains: ${Object.keys(domains).join(", ")}.`:`Rabetbase connection configured for region: ${region}.`,data:{mode:hasDomains?"independent":"official",protocol:routingInput.mode==="enterprise-v1"?ENTERPRISE_ROUTING_PROTOCOL:undefined,region:region,domains:domains,cdn:routingInput.mode==="enterprise-v1"?routingInput.cdn:undefined}}}export const configInitDefinition={service:"config",command:"init",description:"Initialize the Lovrabet region or independent-deployment Domains",risk:"write",confirmationDescription:"Updates the selected Rabetbase region or independent-deployment Domain configuration. Cookie, output format, and app bindings stay unchanged.",requiresAuth:false,requiresAppCode:false,hasFormat:false,flags:configInitFlags,execute:executeConfigInit};
@@ -1,4 +1,4 @@
1
- import chalk from"chalk";import{CLI_BIN_NAME}from"../constant/cli.js";import{DEFAULT_CONFIG_VALUES}from"../constant/defaults.js";import{VERSION,GIT_COMMIT,BUILD_TIME}from"../generated/build-info.js";import{getActiveRegion,getApiDomain,getAppDomain,getKbDomain,getKbServiceDomain,getSkillDomain,getUserDomain,getRuntimeDomain}from"../constant/domain.js";import{getProjectConfigPath,getGlobalConfigPath,buildConfigFromFlags,initGlobalEnvironment,inspectCliConfigJsonFile,loadRawConfigLayers}from"../context.js";import{getIsSessionValid}from"../auth/is-session-valid.js";import{getCookie}from"../auth/get-cookie.js";import{buildAppDoctorFields}from"../config/schema.js";import{resolveEffectiveRegion}from"../config/region-config.js";import{inspectBuiltinSkill}from"../skills/builtin-skill.js";import{DEFAULT_LOVRABET_REGION,isInvalidLovrabetRegion}from"../constant/region.js";function describeRegionValue(value){
1
+ import chalk from"chalk";import{CLI_BIN_NAME}from"../constant/cli.js";import{DEFAULT_CONFIG_VALUES}from"../constant/defaults.js";import{VERSION,GIT_COMMIT,BUILD_TIME}from"../generated/build-info.js";import{getActiveRegion,getApiDomain,getAppDomain,getKbDomain,getKbServiceDomain,getSkillDomain,getUserDomain,getUserPageDomain,getRuntimeDomain}from"../constant/domain.js";import{getProjectConfigPath,getGlobalConfigPath,buildConfigFromFlags,initGlobalEnvironment,inspectCliConfigJsonFile,loadRawConfigLayers}from"../context.js";import{getIsSessionValid}from"../auth/is-session-valid.js";import{getCookie}from"../auth/get-cookie.js";import{buildAppDoctorFields}from"../config/schema.js";import{resolveEffectiveRegion}from"../config/region-config.js";import{inspectBuiltinSkill}from"../skills/builtin-skill.js";import{DEFAULT_LOVRABET_REGION,isInvalidLovrabetRegion}from"../constant/region.js";function describeRegionValue(value){
2
2
  return typeof value==="string"?JSON.stringify(value):`<${value===null?"null":typeof value}>`}async function execute(_ctx){const cliVersion=GIT_COMMIT!=="unknown"?`${VERSION} (${GIT_COMMIT}, ${BUILD_TIME.slice(0,10)})`:VERSION;const resolved=buildConfigFromFlags({});const fileCookie=getCookie();let routingError;try{await initGlobalEnvironment(resolved)}catch(err){routingError=err instanceof Error?err:new Error(String(err))}console.log();console.log(chalk.bold(`${CLI_BIN_NAME} doctor`));console.log(chalk.gray("─".repeat(50)));console.log(` CLI Version: ${cliVersion}`);console.log(` Node: ${process.version}`);console.log(` Platform: ${process.platform} ${process.arch}`);const builtinSkill=inspectBuiltinSkill();console.log();console.log(chalk.bold(" Built-in Skill"));console.log(chalk.gray(" ─".repeat(30)));const skillState=builtinSkill.state==="current"?chalk.green(`✓ ${builtinSkill.state}`):chalk.red(`✗ ${builtinSkill.state}`)
3
3
  ;console.log(` State: ${skillState}`);console.log(` Package Version: ${builtinSkill.packageVersion}`);console.log(` Skill Version: ${builtinSkill.skillVersion||chalk.gray("(unknown)")}`);console.log(` Installed Path: ${builtinSkill.installedPath||chalk.gray("(not found)")}`);if(builtinSkill.reason)console.log(` Reason: ${builtinSkill.reason}`);if(builtinSkill.state!=="current"){console.log(` Repair: ${builtinSkill.repairCommand}`)}console.log();console.log(chalk.bold(" Config Files"));console.log(chalk.gray(" ─".repeat(30)));const globalPath=getGlobalConfigPath();const projectPath=getProjectConfigPath();console.log(` Global: ${globalPath||chalk.gray("(not found)")}`);console.log(` Project: ${projectPath||chalk.gray("(not found)")}`);console.log();console.log(chalk.bold(" Config JSON"));console.log(chalk.gray(" ─".repeat(30)));const printJsonDiag=(label,path)=>{if(!path){
4
4
  console.log(` ${label.padEnd(17)} ${chalk.gray("(no file)")}`);return}const r=inspectCliConfigJsonFile(path);if(r.status==="ok"){console.log(` ${label.padEnd(17)} ${chalk.green("✓ Valid JSON")}`)}else if(r.status==="empty"){console.log(` ${label.padEnd(17)} ${chalk.yellow("⚠ Empty (treated as {})")}`)}else if(r.status==="missing"){console.log(` ${label.padEnd(17)} ${chalk.gray("(missing)")}`)}else{console.log(` ${label.padEnd(17)} ${chalk.red("✗ Invalid JSON")}`);console.log(` ${"".padEnd(17)} ${chalk.red(r.message)}`)}};printJsonDiag("Global",globalPath);printJsonDiag("Project",projectPath);const configLayers=loadRawConfigLayers();const invalidRegionEntries=[{label:"Project",value:configLayers.projectConfig.region,present:Object.prototype.hasOwnProperty.call(configLayers.projectConfig,"region"),repairCommand:`${CLI_BIN_NAME} config delete region`},{label:"Global",value:configLayers.globalConfig.region,
@@ -8,5 +8,5 @@ console.log(` ${entry.label.padEnd(17)} ${chalk.red(`✗ Invalid ${describeRegi
8
8
  ;const mergedRegionLabel=mergedRegionIsInvalid?chalk.red(`${describeRegionValue(resolved.regionConfiguredValue??resolved.raw?.region)} (invalid)`):`${resolved.region??DEFAULT_LOVRABET_REGION} (${resolved.regionSource??"default"})`;console.log(` region: ${mergedRegionLabel}`);console.log(` env: ${resolved.env}`);console.log(` app locale: ${resolved.locale}`);console.log(` apiDir: ${resolved.apiDir}`);console.log(` defaultApp: ${resolved.defaultApp||chalk.gray("(none)")}`);console.log(` currentApp: ${resolved.currentApp||chalk.gray("(none)")}`);console.log(` explicitAppName: ${resolved.explicitAppName||chalk.gray("(none)")}`);console.log(` format: ${resolved.format||chalk.gray(`(default: ${DEFAULT_CONFIG_VALUES.format})`)}`);console.log(` pageSize: ${resolved.pageSize??chalk.gray("(default)")}`);console.log(` riskLevel: ${resolved.riskLevel}`);console.log(` verbose: ${resolved.verbose}`)
9
9
  ;console.log(` cookie: ${resolved.cookie?chalk.green("(set, length="+resolved.cookie.length+")"):fileCookie?chalk.green("(set via file, length="+fileCookie.length+")"):chalk.gray("(none)")}`);const appNames=Object.keys(resolved.apps);if(appNames.length>0){console.log();console.log(chalk.bold(" Apps"));console.log(chalk.gray(" ─".repeat(30)));for(const name of appNames){const app=resolved.apps[name];const isDefault=name===resolved.defaultApp;const isCurrent=name===resolved.currentApp;const marker=isCurrent?chalk.green(" ← current"):"";const tag=isDefault?" (default)":"";console.log(` ${name}${tag}${marker}`);console.log(` appcode: ${app.appcode}`);const projectApps=configLayers.projectConfig.apps&&typeof configLayers.projectConfig.apps==="object"?configLayers.projectConfig.apps:{};const isProjectApp=Object.prototype.hasOwnProperty.call(projectApps,name);const appRegion=isInvalidLovrabetRegion(app.region)?{region:resolved.region??DEFAULT_LOVRABET_REGION
10
10
  }:resolveEffectiveRegion({appRegion:app.region,projectRegion:isProjectApp?configLayers.projectConfig.region:undefined,globalRegion:configLayers.globalConfig.region,mergedRegion:resolved.raw.region,appName:name});const fields=buildAppDoctorFields(app,{region:appRegion.region,env:resolved.env,apiDir:resolved.raw.apiDir||DEFAULT_CONFIG_VALUES.apiDir,cookie:resolved.cookie||fileCookie||undefined,accessKey:resolved.accessKey});console.log(` region: ${fields.region.value} ${chalk.gray(`(${fields.region.source})`)}`);console.log(` env: ${fields.env.value} ${chalk.gray(`(${fields.env.source})`)}`);console.log(` apiDir: ${fields.apiDir.value} ${chalk.gray(`(${fields.apiDir.source})`)}`);const cookieVal=fields.cookie.value?chalk.green(`(set, length=${fields.cookie.value.length})`):chalk.gray("(none)");console.log(` cookie: ${cookieVal} ${chalk.gray(`(${fields.cookie.source})`)}`)
11
- ;const akVal=fields.accessKey.value?chalk.green(`(set, length=${fields.accessKey.value.length})`):chalk.gray("(none)");console.log(` accessKey: ${akVal} ${chalk.gray(`(${fields.accessKey.source})`)}`)}}console.log();console.log(chalk.bold(" API Endpoints"));console.log(chalk.gray(" ─".repeat(30)));if(routingError){console.log(` Status: ${chalk.red("Unavailable until routing configuration is repaired")}`)}else{console.log(` region: ${getActiveRegion()}`);console.log(` apiDomain: ${getApiDomain()}`);console.log(` userDomain: ${getUserDomain()}`);console.log(` runtimeDomain: ${getRuntimeDomain()}`);console.log(` skillDomain: ${getSkillDomain()}`);console.log(` kbDomain: ${getKbDomain()}`);console.log(` kbServiceDomain: ${getKbServiceDomain()??"not configured"}`);console.log(` appDomain: ${getAppDomain()}`)}console.log();console.log(chalk.bold(" Auth"));console.log(chalk.gray(" ─".repeat(30)));if(routingError){
12
- console.log(` Status: ${chalk.yellow("Not checked until routing configuration is repaired")}`)}else if(fileCookie){const isValid=await getIsSessionValid();console.log(` Status: ${isValid?chalk.green("✓ Valid"):chalk.red("✗ Expired")}`)}else{console.log(` Status: ${chalk.red("✗ Not logged in")}`)}console.log();return{ok:true}}export const doctorDefinition={service:"doctor",command:"check",description:"Diagnose CLI configuration and connectivity",risk:"read",requiresAuth:false,requiresAppCode:false,hasFormat:false,flags:[],execute:execute};
11
+ ;const akVal=fields.accessKey.value?chalk.green(`(set, length=${fields.accessKey.value.length})`):chalk.gray("(none)");console.log(` accessKey: ${akVal} ${chalk.gray(`(${fields.accessKey.source})`)}`)}}console.log();console.log(chalk.bold(" Connection Endpoints"));console.log(chalk.gray(" ─".repeat(30)));if(routingError){console.log(` Status: ${chalk.red("Unavailable until routing configuration is repaired")}`)}else{console.log(` region: ${getActiveRegion()}`);console.log(` apiDomain: ${getApiDomain()}`);console.log(` userCenterDomain: ${getUserPageDomain()}`);console.log(` userDomain: ${getUserDomain()}`);console.log(` runtimeDomain: ${getRuntimeDomain()}`);console.log(` skillDomain: ${getSkillDomain()}`);console.log(` kbDomain: ${getKbDomain()}`);console.log(` kbServiceDomain: ${getKbServiceDomain()??"not configured"}`);console.log(` appDomain: ${getAppDomain()}`)}console.log();console.log(chalk.bold(" Auth"))
12
+ ;console.log(chalk.gray(" ─".repeat(30)));if(routingError){console.log(` Status: ${chalk.yellow("Not checked until routing configuration is repaired")}`)}else if(fileCookie){const isValid=await getIsSessionValid();console.log(` Status: ${isValid?chalk.green("✓ Valid"):chalk.red("✗ Expired")}`)}else{console.log(` Status: ${chalk.red("✗ Not logged in")}`)}console.log();return{ok:true}}export const doctorDefinition={service:"doctor",command:"check",description:"Diagnose CLI configuration and connectivity",risk:"read",requiresAuth:false,requiresAppCode:false,hasFormat:false,flags:[],execute:execute};
@@ -1,8 +1,10 @@
1
- import type { ValidateFunction } from 'ajv';
2
1
  export declare function readMetricJson(file: string): Promise<unknown>;
3
2
  export declare function parseMetricJson(text: string): unknown;
4
- export declare function compileMetricContract(value: unknown): {
5
- input: import("ajv/dist/core.js").AnyValidateFunction<unknown>;
6
- output: import("ajv/dist/core.js").AnyValidateFunction<unknown>;
7
- };
8
- export declare function assertMetricInput(validate: ValidateFunction, value: unknown): asserts value is Record<string, unknown>;
3
+ /**
4
+ * contract 是 BFF 元数据的只读投影。CLI 只认识外层对象,不解释内部协议:
5
+ * 不编译 Schema、不检查 examples、不解析引用、不猜测参数、不补默认值或删字段。
6
+ * 将来内部格式升级时仍原样透传。对象检查通过不代表契约完整、业务正确或执行获授权。
7
+ */
8
+ export declare function validateMetricContract(value: unknown): Record<string, unknown>;
9
+ /** Validate transport integrity only; parameter semantics belong to the BFF. */
10
+ export declare function assertMetricInput(value: unknown): asserts value is Record<string, unknown>;
@@ -1,5 +1,3 @@
1
- import{readFile}from"node:fs/promises";import{Ajv2020}from"ajv/dist/2020.js";import addFormats from"ajv-formats";import{CliError,CliErrors}from"../../errors.js";function object(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}export async function readMetricJson(file){try{return parseMetricJson(await readFile(file,"utf8"))}catch(error){if(error instanceof CliError)throw error;throw CliErrors.validation(`Cannot read a valid metric JSON document: ${file}`)}}function assertMetricNumbers(value,failure=CliErrors.validation){if(typeof value==="number"&&(!Number.isFinite(value)||Number.isInteger(value)&&!Number.isSafeInteger(value))){throw failure("Metric JSON numbers must be finite and integers must be within the safe integer range.","Represent larger integers as decimal strings in the schema, examples and endpoint payloads.")}if(value!==null&&typeof value==="object"){for(const child of Object.values(value))assertMetricNumbers(child,failure)}}
2
- export function parseMetricJson(text){try{const parsed=JSON.parse(text);assertMetricNumbers(parsed);const stack=[];for(const[token]of text.matchAll(/"(?:\\[\s\S]|[^"\\])*"|[{}\[\],]/g)){const frame=stack[stack.length-1];if(token==="{")stack.push({keys:new Set,keyExpected:true});else if(token==="[")stack.push(null);else if(token==="}"||token==="]")stack.pop();else if(token===","){if(frame)frame.keyExpected=true}else if(frame?.keyExpected){const key=JSON.parse(token);if(frame.keys.has(key))throw CliErrors.validation("Metric JSON must not contain duplicate object keys.");frame.keys.add(key);frame.keyExpected=false}}return parsed}catch(error){if(error instanceof CliError)throw error;throw CliErrors.validation("Cannot parse a valid metric JSON document.")}}export function compileMetricContract(value){assertMetricNumbers(value)
3
- ;if(!object(value)||!Object.hasOwn(value,"inputSchema")||!Object.hasOwn(value,"outputSchema")||Object.keys(value).some(key=>!["inputSchema","outputSchema","examples"].includes(key))){throw CliErrors.validation("Metric contract requires inputSchema and outputSchema, with optional examples only.")}const compile=(schema,label)=>{if(!object(schema))throw CliErrors.validation(`${label} must be a JSON Schema object.`);try{const ajv=new Ajv2020({strict:true,allErrors:false,coerceTypes:false,useDefaults:false,removeAdditional:false});addFormats.default(ajv);const validate=ajv.compile(schema);if("$async"in validate&&validate.$async)throw new Error("Asynchronous schemas are not supported.");return validate}catch(error){throw CliErrors.validation(`Invalid metric ${label}: ${error instanceof Error?error.message:"schema compilation failed"}`,"Use synchronous JSON Schema 2020-12 with local fragment references; remote schemas are not loaded.")}}
4
- ;if(!object(value.inputSchema)||value.inputSchema.type!=="object"){throw CliErrors.validation("Metric inputSchema must declare type: object.")}const input=compile(value.inputSchema,"inputSchema");const output=compile(value.outputSchema,"outputSchema");if(value.examples!==undefined){if(!Array.isArray(value.examples))throw CliErrors.validation("Metric contract examples must be an array.");for(const[index,example]of value.examples.entries()){if(!object(example)||!Object.hasOwn(example,"input")||!Object.hasOwn(example,"output")||Object.keys(example).some(key=>!["input","output"].includes(key))){throw CliErrors.validation(`Metric example ${index} requires input and output only.`)}assertMetricInput(input,example.input);if(!output(example.output))throw CliErrors.validation(`Metric example ${index} output: ${validationMessage(output)}`)}}return{input:input,output:output}}function validationMessage(validate){const error=validate.errors?.[0]
5
- ;return error?`${error.instancePath||"/"} ${error.message}`:"does not match its schema"}export function assertMetricInput(validate,value){if(!object(value))throw CliErrors.validation("Metric input must be a JSON object.");assertMetricNumbers(value);if(!validate(value))throw CliErrors.validation(`Metric input: ${validationMessage(validate)}`)}
1
+ import{readFile}from"node:fs/promises";import{CliError,CliErrors}from"../../errors.js";function object(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}export async function readMetricJson(file){try{return parseMetricJson(await readFile(file,"utf8"))}catch(error){if(error instanceof CliError)throw error;throw CliErrors.validation(`Cannot read a valid metric JSON document: ${file}`)}}function assertMetricNumbers(value,failure=CliErrors.validation){if(typeof value==="number"&&(!Number.isFinite(value)||Number.isInteger(value)&&!Number.isSafeInteger(value))){throw failure("Metric JSON numbers must be finite and integers must be within the safe integer range.","Represent larger integers as decimal strings in the schema, examples and endpoint payloads.")}if(value!==null&&typeof value==="object"){for(const child of Object.values(value))assertMetricNumbers(child,failure)}}export function parseMetricJson(text){try{const parsed=JSON.parse(text)
2
+ ;assertMetricNumbers(parsed);const stack=[];for(const[token]of text.matchAll(/"(?:\\[\s\S]|[^"\\])*"|[{}\[\],]/g)){const frame=stack[stack.length-1];if(token==="{")stack.push({keys:new Set,keyExpected:true});else if(token==="[")stack.push(null);else if(token==="}"||token==="]")stack.pop();else if(token===","){if(frame)frame.keyExpected=true}else if(frame?.keyExpected){const key=JSON.parse(token);if(frame.keys.has(key))throw CliErrors.validation("Metric JSON must not contain duplicate object keys.");frame.keys.add(key);frame.keyExpected=false}}return parsed}catch(error){if(error instanceof CliError)throw error;throw CliErrors.validation("Cannot parse a valid metric JSON document.")}}export function validateMetricContract(value){if(!object(value))throw CliErrors.validation("Metric contract must be a JSON object.");assertMetricNumbers(value);return value}export function assertMetricInput(value){if(!object(value))throw CliErrors.validation("Metric input must be a JSON object.")
3
+ ;assertMetricNumbers(value)}
@@ -1,43 +1,43 @@
1
- export interface MetricEntry {
2
- name: string;
3
- description: string;
4
- displayName?: string;
5
- categoryPath?: string[];
6
- unit: string;
7
- contract: unknown;
1
+ /**
2
+ * 指标定义原则(与 templates/metrics/metric-definition.schema.json 保持一致):
3
+ * - 应用 + 稳定 code 定位指标;label/synonyms/categoryPath 只用于理解与组织,不改变身份或权限。
4
+ * - 定义描述业务含义、单位、真实执行目标与输入/输出契约;实际计算及数据权限由 BFF/平台落实。
5
+ * - 不声明 defaultViews/default_views,也不新增 presentation/chartConfig 等替代展示配置;
6
+ * customPage、前端子应用和 Agent 宿主依据真实契约、实际结果及任务上下文决定卡片、图表或表格。
7
+ * - 返回能力必须有目标实现和契约依据:数组不等于明细,月序列不意味着支持日/周或区间总值。
8
+ * 展示切换不授予新计算能力,不得改写范围、聚合规则、单位、精度,或将 null/缺失/失败变成零。
9
+ * - 未知口径须确认,不由 LLM 补齐;CLI 仅校验契约外层对象,不解析内部 Schema/示例,不代替真实执行与业务对账。
10
+ * - 云端当前定义是运行态执行依据,本地 JSON 是开发辅助;扩展 JSON 字段按原值保留,不参与权限或 BFF 参数组装。
11
+ */
12
+ export interface MetricEntry extends Record<string, unknown> {
13
+ code: string;
8
14
  target: {
9
- appCode: string;
10
- } & ({
11
- kind: 'sql';
12
- sqlCode: string;
13
- } | {
14
15
  kind: 'bff';
16
+ appCode: string;
15
17
  functionName: string;
16
- });
18
+ };
19
+ label?: string;
20
+ synonyms?: string[];
21
+ description?: string;
22
+ unit?: string;
23
+ categoryPath?: string[];
24
+ contract?: unknown;
17
25
  }
18
26
  export declare function validateMetricEntry(entry: unknown, path?: string): MetricEntry;
19
- /** The canonical metric name is the app-config key; never add or strip a prefix. */
20
- export declare function validateMetricName(name: string): string;
21
- export declare function validateMetricDefinition(value: unknown, appCode?: string, name?: string): {
27
+ /** Metric identity is appCode + code; label is display-only. No name/displayName aliases. */
28
+ export declare function validateMetricCode(code: string): string;
29
+ export declare function validateMetricDefinition(value: unknown, appCode?: string, code?: string, requireContract?: boolean): {
22
30
  metric: MetricEntry;
23
- contract: {
24
- input: import("ajv/dist/core.js").AnyValidateFunction<unknown>;
25
- output: import("ajv/dist/core.js").AnyValidateFunction<unknown>;
26
- };
31
+ contract: unknown;
27
32
  };
28
- /** Authoring must also satisfy app-config publication constraints. */
33
+ /** Development input follows v1; HTTP storage limits belong to the publication adapter. */
29
34
  export declare function validateMetricPublication(value: unknown, appCode?: string): {
30
35
  metric: MetricEntry;
31
- contract: {
32
- input: import("ajv/dist/core.js").AnyValidateFunction<unknown>;
33
- output: import("ajv/dist/core.js").AnyValidateFunction<unknown>;
34
- };
36
+ contract: unknown;
35
37
  };
36
- /** Assemble only the split storage format; metadata cannot be overridden by value. */
38
+ /** Assemble only the split storage format; identity cannot be overridden by definition. */
37
39
  export declare function readStoredMetric(record: {
38
40
  appCode: string;
39
- key: string;
40
- tags?: string | null;
41
- description?: string | null;
42
- value?: string | null;
43
- }, appCode: string, name?: string): MetricEntry;
41
+ code: string;
42
+ definition: unknown;
43
+ }, appCode: string, code?: string): MetricEntry;
@@ -1,4 +1,5 @@
1
- import{CliErrors}from"../../errors.js";import{SQLCODE_FLAG}from"../../commands/common/flags.js";import{compileMetricContract,parseMetricJson}from"./contract.js";function invalid(path,message){throw CliErrors.validation(`${path}: ${message}`,"Read rabetbase metric schema and correct the definition.")}function object(value,keys,path,optional=[]){if(!value||typeof value!=="object"||Array.isArray(value))invalid(path,"Expected an object.");const record=value;for(const key of keys){if(!Object.hasOwn(record,key))invalid(`${path}.${key}`,"Required field is missing.")}for(const key of Object.keys(record)){if(!keys.includes(key)&&!optional.includes(key))invalid(`${path}.${key}`,"Unknown field.")}return record}function text(value,path){if(typeof value!=="string"||!value.trim()||value!==value.trim()){invalid(path,"Expected a non-empty string without leading or trailing whitespace.")}return value}export function validateMetricEntry(entry,path="metric"){
2
- const metric=object(entry,["name","description","unit","target","contract"],path,["displayName","categoryPath"]);if(Object.hasOwn(metric,"displayName"))text(metric.displayName,`${path}.displayName`);if(Object.hasOwn(metric,"categoryPath")){const categories=metric.categoryPath;if(!Array.isArray(categories)||categories.length<1||categories.length>2){invalid(`${path}.categoryPath`,"Expected a category path with one or two levels.")}for(const[index,category]of categories.entries())text(category,`${path}.categoryPath[${index}]`)}validateMetricName(text(metric.name,`${path}.name`));for(const field of["description","unit"])text(metric[field],`${path}.${field}`);const targetValue=metric.target;if(!targetValue||typeof targetValue!=="object"||Array.isArray(targetValue))invalid(`${path}.target`,"Expected an object.");const kind=targetValue.kind;if(kind!=="sql"&&kind!=="bff")invalid(`${path}.target.kind`,"Expected sql or bff.");const selector=kind==="sql"?"sqlCode":"functionName"
3
- ;const target=object(targetValue,["kind","appCode",selector],`${path}.target`);const appCode=text(target.appCode,`${path}.target.appCode`);const code=text(target[selector],`${path}.target.${selector}`);if(kind==="sql"&&!SQLCODE_FLAG.pattern.regex.test(code)){invalid(`${path}.target.sqlCode`,"Expected a SQL code in xxxxxxxx-xxxxxxxx hexadecimal format.")}return metric}export function validateMetricName(name){if(!/^metrics\.[a-z][a-z0-9_-]*$/.test(name)||name!==name.trim()||name.length>256){throw CliErrors.validation("Metric name must be a metrics.<identifier> key of at most 256 characters.")}return name}export function validateMetricDefinition(value,appCode,name){const metric=validateMetricEntry(value);if(appCode!==undefined&&metric.target.appCode!==appCode||name!==undefined&&metric.name!==name){throw CliErrors.validation("Metric identity does not match the selected app and name.")}const contract=compileMetricContract(metric.contract);return{metric:metric,contract:contract}}
4
- export function validateMetricPublication(value,appCode){const validated=validateMetricDefinition(value,appCode);if(validated.metric.description.length>256){throw CliErrors.validation("Metric description must not exceed 256 characters.")}return validated}export function readStoredMetric(record,appCode,name){if(!record||typeof record!=="object"||Array.isArray(record)||record.appCode!==appCode||record.tags!=="METRIC"||typeof record.value!=="string"||typeof record.key!=="string"){throw CliErrors.apiError("Invalid metric app-config record.")}const storedName=record.key;const value=parseMetricJson(record.value);if(!value||typeof value!=="object"||Array.isArray(value)||["name","description","tags"].some(field=>Object.hasOwn(value,field))){throw CliErrors.apiError("Metric value must contain only the metric payload, without app-config metadata.")}return validateMetricDefinition({...value,name:storedName,description:record.description},appCode,name).metric}
1
+ import{CliErrors}from"../../errors.js";import{assertMetricInput,validateMetricContract}from"./contract.js";function invalid(path,message){throw CliErrors.validation(`${path}: ${message}`,"Read rabetbase metric schema and correct the definition.")}const RESERVED_DEFINITION_FIELDS=["id","appCode","createdBy","createdAt","updatedBy","updatedAt","latestChange","extend","name","displayName","aliasNames","metricName","metricCode","metricsCode","calculationSpec","defaultViews","default_views","presentation","chartConfig"];function object(value,keys,path,allowAdditional=false){if(!value||typeof value!=="object"||Array.isArray(value))invalid(path,"Expected an object.");const record=value;for(const key of keys){if(!Object.hasOwn(record,key))invalid(`${path}.${key}`,"Required field is missing.")}for(const key of Object.keys(record)){if(!allowAdditional&&!keys.includes(key))invalid(`${path}.${key}`,"Unknown field.")}return record}function text(value,path){
2
+ if(typeof value!=="string"||!value.trim()||value!==value.trim()){invalid(path,"Expected a non-empty string without leading or trailing whitespace.")}return value}export function validateMetricEntry(entry,path="metric"){assertMetricInput(entry);const metric=object(entry,["code","target"],path,true);for(const field of RESERVED_DEFINITION_FIELDS){if(Object.hasOwn(metric,field))invalid(`${path}.${field}`,"Reserved metric definition field.")}for(const field of["label","unit"]){if(Object.hasOwn(metric,field))text(metric[field],`${path}.${field}`)}if(Object.hasOwn(metric,"description")&&(typeof metric.description!=="string"||!/\S/.test(metric.description))){invalid(`${path}.description`,"Expected Markdown containing non-whitespace text.")}if(Object.hasOwn(metric,"synonyms")){const synonyms=metric.synonyms;if(!Array.isArray(synonyms))invalid(`${path}.synonyms`,"Expected an array of strings.");for(const[index,synonym]of synonyms.entries())text(synonym,`${path}.synonyms[${index}]`)
3
+ ;if(new Set(synonyms).size!==synonyms.length)invalid(`${path}.synonyms`,"Duplicate synonyms are not allowed within one metric.")}if(Object.hasOwn(metric,"categoryPath")){const categories=metric.categoryPath;if(!Array.isArray(categories)||categories.length<1||categories.length>2){invalid(`${path}.categoryPath`,"Expected a category path with one or two levels.")}for(const[index,category]of categories.entries())text(category,`${path}.categoryPath[${index}]`)}validateMetricCode(text(metric.code,`${path}.code`));const target=object(metric.target,["kind","appCode","functionName"],`${path}.target`);if(target.kind!=="bff")invalid(`${path}.target.kind`,"Expected bff. SQL metrics are not supported.");text(target.appCode,`${path}.target.appCode`);text(target.functionName,`${path}.target.functionName`);return metric}export function validateMetricCode(code){if(!/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/.test(code)||code!==code.trim()||code.length>256){
4
+ throw CliErrors.validation("Metric code must be a lower_snake_case identifier of at most 256 characters without a resource prefix.")}return code}export function validateMetricDefinition(value,appCode,code,requireContract=true){const metric=validateMetricEntry(value);if(appCode!==undefined&&metric.target.appCode!==appCode||code!==undefined&&metric.code!==code){throw CliErrors.validation("Metric identity does not match the selected app and code.")}if(requireContract||Object.hasOwn(metric,"contract"))validateMetricContract(metric.contract);return{metric:metric,contract:metric.contract}}export function validateMetricPublication(value,appCode){return validateMetricDefinition(value,appCode,undefined,false)}export function readStoredMetric(record,appCode,code){if(!record||typeof record!=="object"||Array.isArray(record)||record.appCode!==appCode||typeof record.code!=="string"){throw CliErrors.apiError("Invalid metric record identity.")}const value=record.definition
5
+ ;if(!value||typeof value!=="object"||Array.isArray(value)||["code","contract"].some(field=>Object.hasOwn(value,field))){throw CliErrors.apiError("Saved metric definition must be an object without root code/contract.")}return validateMetricDefinition({...value,code:record.code},appCode,code,false).metric}
@@ -1,3 +1,3 @@
1
- import{deleteAppConfig,getAppConfigByKey}from"../../core/api-client.js";import{withDiagnostic,CliErrors}from"../../errors.js";import{metricWriteFailure}from"./shared.js";import{APPCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{requireAppConfigId}from"../../commands/app-config/shared.js";import{validateMetricName}from"./definition.js";async function prepare(ctx){const key=ctx.str("name");validateMetricName(key);const before=await getAppConfigByKey(ctx.appCode,key);if(!before)throw withDiagnostic(CliErrors.validation(`Metric not found: ${key}`),`appCode: ${ctx.appCode}`);if(before.appCode!==ctx.appCode||before.key!==key||before.tags!=="METRIC"){throw CliErrors.validation("The metric key is occupied by a different app-config record.")}return{before:before,id:requireAppConfigId(before)}}function resultData(before,id,dryRun){return{operation:"delete",selector:{appCode:before.appCode,key:before.key,id:id},before:{appCode:before.appCode,key:before.key,id:id,
2
- description:before.description,tags:before.tags},after:null,dryRun:dryRun,backend:"app-config",warnings:["Only the metric definition is deleted. Referenced SQL/BFF and local files are retained.","Deletion takes effect immediately. Concurrent changes have no version-conflict protection."]}}export const metricDelete={service:"metric",command:"delete",risk:"high-risk-write",strictFlags:true,description:"Delete one application metric definition and verify its absence",flags:[APPCODE_FLAG_OPTIONAL,{name:"name",type:"string",required:true,description:"Exact full metric name (e.g. metrics.paid_order_count)"}],async dryRun(ctx){const{before:before,id:id}=await prepare(ctx);return{method:"POST",url:"/smartapi/app-config/delete",data:resultData(before,id,true)}},async execute(ctx){const{before:before,id:id}=await prepare(ctx);let after;try{await deleteAppConfig({appCode:ctx.appCode,id:id});after=await getAppConfigByKey(ctx.appCode,before.key)}catch(error){
3
- const hint=`Inspect ${before.key} in app ${ctx.appCode} before deleting again; a missing response does not prove the deletion failed.`;throw metricWriteFailure(error,"Metric deletion could not be verified.",hint)}if(after!==null){throw CliErrors.apiError("Metric delete readback still contains a record.","Inspect the current app-config record before deleting again; it may have changed or been recreated.")}return{ok:true,data:resultData(before,id,false),message:`Deleted metric ${before.key}`}}};
1
+ import{deleteMetric,getMetricByCode,getMetricById,getPlatformErrorCode,getPlatformHttpStatus,isPlatformTransportFailure}from"../../core/api-client.js";import{withDiagnostic,CliErrors}from"../../errors.js";import{metricWriteFailure,requireMetricId}from"./shared.js";import{APPCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{validateMetricCode}from"./definition.js";async function prepare(ctx){const key=ctx.str("code");validateMetricCode(key);const before=await getMetricByCode(ctx.appCode,key);if(!before)throw withDiagnostic(CliErrors.validation(`Metric not found: ${key}`),`appCode: ${ctx.appCode}`);if(before.appCode!==ctx.appCode||before.code!==key){throw CliErrors.validation("Metric identity does not match the selected app and code.")}return{before:before,id:requireMetricId(before)}}async function verifyDeleted(appCode,id){try{await getMetricById(appCode,id)}catch(error){if(getPlatformErrorCode(error)==="306"&&getPlatformHttpStatus(error)===undefined)return;throw error}
2
+ throw CliErrors.apiError("Metric readback did not confirm the original record ID is absent.")}function resultData(before,id,dryRun){return{operation:"delete",selector:{appCode:before.appCode,code:before.code,id:id},before:{appCode:before.appCode,code:before.code,id:id},after:null,dryRun:dryRun,backend:"app_metric",warnings:["Only the metric definition is deleted. Referenced SQL/BFF and local files are retained.","Deletion takes effect immediately. Concurrent changes have no version-conflict protection."]}}export const metricDelete={service:"metric",command:"delete",risk:"high-risk-write",strictFlags:true,description:"Delete one application metric definition and verify its absence",flags:[APPCODE_FLAG_OPTIONAL,{name:"code",type:"string",required:true,description:"Exact full metric code (e.g. paid_order_count)"}],async dryRun(ctx){const{before:before,id:id}=await prepare(ctx);return{method:"POST",url:"/api/studio/metric/v1/delete",data:resultData(before,id,true)}},async execute(ctx){
3
+ const{before:before,id:id}=await prepare(ctx);let writeError;const failure=error=>metricWriteFailure(error,"Metric deletion could not be verified.",`Inspect ${before.code} in app ${ctx.appCode} by ID ${id} before deleting again; a missing response does not prove the deletion failed.`);try{await deleteMetric({appCode:ctx.appCode,id:id})}catch(error){if(!isPlatformTransportFailure(error))throw failure(error);writeError=error}try{await verifyDeleted(ctx.appCode,id)}catch(error){throw failure(writeError??error)}const data=resultData(before,id,false);if(writeError)data.warnings.push("Write response was unavailable; readback confirms current absence, not attribution to this request.");return{ok:true,data:data,message:`Confirmed metric record ${id} is absent from app ${ctx.appCode}.`}}};
@@ -1 +1,2 @@
1
- import{getMetricDetail}from"../../core/api-client.js";import{APPCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{validateMetricName,validateMetricDefinition}from"./definition.js";export const metricDetail={service:"metric",command:"detail",risk:"read",strictFlags:true,description:"Read and validate the current editable application metric definition",flags:[APPCODE_FLAG_OPTIONAL,{name:"name",type:"string",required:true,description:"Exact full metric name (e.g. metrics.paid_order_count); use name, not displayName"}],async execute(ctx){const name=ctx.str("name");const record=await getMetricDetail(ctx.appCode,validateMetricName(name));const definition=record&&typeof record==="object"&&"metricDefinition"in record?record.metricDefinition:undefined;return{ok:true,data:validateMetricDefinition(definition,ctx.appCode,name).metric}}};
1
+ import{getMetricDetail}from"../../core/api-client.js";import{CliErrors}from"../../errors.js";import{APPCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{readStoredMetric,validateMetricCode,validateMetricDefinition}from"./definition.js";export const metricDetail={service:"metric",command:"detail",risk:"read",strictFlags:true,description:"Read and validate the current editable application metric definition",flags:[APPCODE_FLAG_OPTIONAL,{name:"code",type:"string",required:true,description:"Exact full metric code (e.g. paid_order_count); use code, not label"}],async execute(ctx){const code=ctx.str("code");const record=await getMetricDetail(ctx.appCode,validateMetricCode(code));if(!record||record.appCode!==ctx.appCode||record.code!==code)throw CliErrors.validation("Metric record identity does not match the selected app and code.");if(record?.detail===null&&record.detailError){return{ok:true,data:readStoredMetric(record,ctx.appCode,code),
2
+ message:`Saved definition only; current consumer detail unavailable: ${record.detailError.message}. ${record.detailError.nextAction??""}`}}return{ok:true,data:validateMetricDefinition(record?.detail,ctx.appCode,code).metric}}};
@@ -1,2 +1,2 @@
1
- import{listAppConfigs}from"../../core/api-client.js";import{CliErrors}from"../../errors.js";import{APPCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{readStoredMetric}from"./definition.js";export const metricList={service:"metric",command:"list",risk:"read",strictFlags:true,description:"List application metric summaries, optionally filtering keys or descriptions by keyword",flags:[APPCODE_FLAG_OPTIONAL,{name:"key",type:"string",description:"Case-insensitive literal substring of the config key or description"}],async execute(ctx){const key=ctx.str("key").trim();const records=await listAppConfigs(ctx.appCode,{tags:"METRIC",...key?{keyword:key}:{}});const names=new Set;const summaries=records.map(record=>{const{name:name,description:description,displayName:displayName,categoryPath:categoryPath,unit:unit}=readStoredMetric(record,ctx.appCode);if(names.has(name))throw CliErrors.apiError("Duplicate metric identity in app-config.");names.add(name);return{name:name,
2
- description:description,...displayName===undefined?{}:{displayName:displayName},...categoryPath===undefined?{}:{categoryPath:categoryPath},unit:unit}});const metrics=summaries.sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);return{ok:true,data:{appCode:ctx.appCode,count:metrics.length,metrics:metrics}}}};
1
+ import{listMetrics}from"../../core/api-client.js";import{CliErrors}from"../../errors.js";import{APPCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{readStoredMetric}from"./definition.js";export const metricList={service:"metric",command:"list",risk:"read",strictFlags:true,description:"List application metric summaries, optionally filtering codes, labels, synonyms or descriptions by keyword",flags:[APPCODE_FLAG_OPTIONAL,{name:"keyword",type:"string",description:"Case-insensitive literal substring of the metric code, label, synonyms or description"}],async execute(ctx){const keyword=ctx.str("keyword").trim();const records=await listMetrics(ctx.appCode,{...keyword?{keyword:keyword}:{}});const codes=new Set;const summaries=records.map(record=>{const{code:code,description:description,label:label,synonyms:synonyms,categoryPath:categoryPath,unit:unit}=readStoredMetric(record,ctx.appCode);if(codes.has(code))throw CliErrors.apiError("Duplicate metric identity.");codes.add(code)
2
+ ;return{code:code,...description===undefined?{}:{description:description},...label===undefined?{}:{label:label},...synonyms===undefined?{}:{synonyms:synonyms},...categoryPath===undefined?{}:{categoryPath:categoryPath},...unit===undefined?{}:{unit:unit}}});const metrics=summaries.sort((a,b)=>a.code<b.code?-1:a.code>b.code?1:0);return{ok:true,data:{appCode:ctx.appCode,count:metrics.length,metrics:metrics}}}};
@@ -1,4 +1,5 @@
1
- import{resolve}from"node:path";import{createAppConfig,getAppConfigByKey,updateAppConfig}from"../../core/api-client.js";import{CliErrors}from"../../errors.js";import{metricWriteFailure}from"./shared.js";import{APPCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{requireAppConfigId}from"../../commands/app-config/shared.js";import{readMetricJson}from"./contract.js";import{readStoredMetric,validateMetricPublication}from"./definition.js";import{diffMetricPublication}from"./publication-diff.js";const TAG="METRIC";async function prepare(ctx){const{metric:metric}=validateMetricPublication(await readMetricJson(resolve(ctx.str("file"))),ctx.appCode);const key=metric.name;const before=await getAppConfigByKey(ctx.appCode,key);if(before&&(before.appCode!==ctx.appCode||before.key!==key||before.tags!==TAG)){throw CliErrors.validation("The metric key is occupied by a different app-config record.")}if(before)requireAppConfigId(before);let previous=null;if(before){try{previous={
2
- ...readStoredMetric(before,ctx.appCode,key)}}catch{throw CliErrors.validation("The current metric definition cannot be reviewed.","Inspect the current metric with app-config get before publishing; no changes were written.")}}const changes=diffMetricPublication(previous,{...metric});const{name:name,description:description,...payload}=metric;return{before:before,changes:changes,input:{appCode:ctx.appCode,key:key,description:description,tags:TAG,value:JSON.stringify(payload)}}}function metadata(item){return item?{appCode:item.appCode,key:item.key,description:item.description,tags:item.tags}:null}function resultData(before,after,changes,dryRun){const warnings=["Updates take effect immediately. Concurrent publishing has no version-conflict protection."];if(before&&changes.some(change=>/^\/(target|contract)(\/|$)/.test(change.path))){warnings.push("Target or contract changed. Revalidate consumers before relying on the new definition.")}return{operation:before?"update":"create",selector:{
3
- appCode:after.appCode,key:after.key},before:metadata(before),after:metadata(after),dryRun:dryRun,backend:"app-config",changes:changes,warnings:warnings}}export const metricPublish={service:"metric",command:"publish",risk:"write",strictFlags:true,description:"Validate and publish one application metric through app-config",flags:[APPCODE_FLAG_OPTIONAL,{name:"file",type:"string",required:true,description:"Self-contained metric definition JSON file"}],async dryRun(ctx){const{before:before,input:input,changes:changes}=await prepare(ctx);return{method:"POST",url:`/smartapi/app-config/${before?"update":"create"}`,data:resultData(before,input,changes,true)}},async execute(ctx){const{before:before,input:input,changes:changes}=await prepare(ctx);let after;try{if(before)await updateAppConfig({...input,id:requireAppConfigId(before)});else await createAppConfig(input);after=await getAppConfigByKey(ctx.appCode,input.key)}catch(error){
4
- const hint=`Inspect ${input.key} in app ${ctx.appCode} before publishing again; a missing response does not prove the write failed.`;throw metricWriteFailure(error,"Metric publication could not be verified.",hint)}if(!after||after.appCode!==input.appCode||after.key!==input.key||after.tags!==TAG||after.description!==input.description||after.value!==input.value){throw CliErrors.apiError("Metric publish readback did not match the submitted definition.","The write may have succeeded. Inspect the app-config record before publishing again.")}return{ok:true,data:resultData(before,after,changes,false),message:`Published metric ${input.key}`}}};
1
+ import{resolve}from"node:path";import{isDeepStrictEqual}from"node:util";import{isPlatformTransportFailure,createMetric,getMetricByCode,getMetricById,updateMetric}from"../../core/api-client.js";import{CliErrors}from"../../errors.js";import{metricWriteFailure,requireMetricId}from"./shared.js";import{APPCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{readMetricJson}from"./contract.js";import{readStoredMetric,validateMetricPublication}from"./definition.js";import{diffMetricPublication}from"./publication-diff.js";async function prepare(ctx){const{metric:metric}=validateMetricPublication(await readMetricJson(resolve(ctx.str("file"))),ctx.appCode);const{code:code,contract:_derivedContract,...definition}=metric;const id=ctx.str("id");if(id&&!/^[1-9][0-9]*$/.test(id))throw CliErrors.validation("Metric id must be a positive decimal string.");const before=id?await getMetricById(ctx.appCode,id):await getMetricByCode(ctx.appCode,code)
2
+ ;if(id&&(!before||before.id!==id))throw CliErrors.apiError("Metric lookup did not match the selected ID.");let previous=null;if(before){requireMetricId(before);previous=readStoredMetric(before,ctx.appCode,id?undefined:code);if(before.code!==code){const occupied=await getMetricByCode(ctx.appCode,code);if(occupied&&occupied.id!==before.id)throw CliErrors.validation("The requested metric code is already in use.")}}return{before:before,changes:diffMetricPublication(previous,{code:code,...definition}),input:{appCode:ctx.appCode,code:code,definition:definition}}}function metadata(item){return item?{appCode:item.appCode,code:item.code,..."id"in item?{id:item.id}:{},definition:item.definition}:null}function resultData(before,after,changes,dryRun){const warnings=["Updates take effect immediately. Concurrent publishing has no version-conflict protection."]
3
+ ;if(before&&changes.some(change=>/^\/target(\/|$)/.test(change.path)))warnings.push("Target changed. Revalidate consumers before relying on the new definition.");if(before&&before.code!==after.code)warnings.push("Metric code changed. Update caller references to the new code.");return{operation:before?"update":"create",selector:{appCode:after.appCode,code:after.code,...before?{id:before.id}:{}},before:metadata(before),after:metadata(after),dryRun:dryRun,backend:"app_metric",changes:changes,warnings:warnings}}export const metricPublish={service:"metric",command:"publish",risk:"write",strictFlags:true,description:"Validate and save one application metric; changes take effect immediately",flags:[APPCODE_FLAG_OPTIONAL,{name:"file",type:"string",required:true,description:"Self-contained metric definition JSON file"},{name:"id",type:"string",description:"Existing stable metric record ID; required when renaming code"}],async dryRun(ctx){
4
+ const{before:before,input:input,changes:changes}=await prepare(ctx);return{method:"POST",url:`/api/studio/metric/v1/${before?"update":"create"}`,data:resultData(before,input,changes,true)}},async execute(ctx){const{before:before,input:input,changes:changes}=await prepare(ctx);let after;let writeError;const failure=error=>metricWriteFailure(error,"Metric publication could not be verified.",`Inspect ${input.code} in app ${ctx.appCode} before publishing again; a missing response does not prove the write failed.`);try{if(before)await updateMetric({...input,id:requireMetricId(before)});else await createMetric(input)}catch(error){if(!isPlatformTransportFailure(error))throw failure(error);writeError=error}try{after=await getMetricByCode(ctx.appCode,input.code)}catch(error){throw failure(writeError??error)}if(!after||after.appCode!==input.appCode||after.code!==input.code||before&&after.id!==before.id||!isDeepStrictEqual(after.definition,input.definition)){
5
+ if(writeError)throw failure(writeError);throw CliErrors.apiError("Metric publish readback did not match the submitted definition.","The write may have succeeded. Inspect the current metric before publishing again.")}requireMetricId(after);const data=resultData(before,after,changes,false);if(writeError)data.warnings.push("Write response was unavailable; readback confirms the requested current state, not attribution to this request.");return{ok:true,data:data,message:`Published metric ${input.code}`}}};
@@ -12,3 +12,7 @@ export declare const metricCommand: {
12
12
  export declare function readMetricAsset(kind: 'definition' | 'contract' | 'example'): Promise<any>;
13
13
  /** Keep diagnostics while replacing generic retry advice with write-state inspection. */
14
14
  export declare function metricWriteFailure(error: unknown, message: string, hint: string): CliError;
15
+ /** IDs are opaque decimal strings; never round through JavaScript numbers. */
16
+ export declare function requireMetricId(record: {
17
+ id?: unknown;
18
+ }): string;
@@ -1 +1,2 @@
1
- import{readFile}from"node:fs/promises";import{CliError,CliErrors}from"../../errors.js";export const metricCommand={service:"metric",risk:"read",requiresAuth:false,requiresAppCode:false,hasFormat:true,strictFlags:true,structuredErrors:true};export async function readMetricAsset(kind){const file=kind==="example"?"definition.json":"metric-definition.schema.json";const asset=JSON.parse(await readFile(new URL(`../../../templates/metrics/${file}`,import.meta.url),"utf8"));return kind==="contract"?{$schema:asset.$schema,...asset.properties.contract}:asset}export function metricWriteFailure(error,message,hint){if(!(error instanceof CliError))return CliErrors.apiError(message,hint);const descriptors=Object.getOwnPropertyDescriptors(error);return Object.defineProperties(new CliError(error.code,error.exitCode,error.message),{...descriptors,hint:{...descriptors.hint,value:hint}})}
1
+ import{readFile}from"node:fs/promises";import{CliError,CliErrors}from"../../errors.js";export const metricCommand={service:"metric",risk:"read",requiresAuth:false,requiresAppCode:false,hasFormat:true,strictFlags:true,structuredErrors:true};export async function readMetricAsset(kind){const file=kind==="example"?"definition.json":"metric-definition.schema.json";const asset=JSON.parse(await readFile(new URL(`../../../templates/metrics/${file}`,import.meta.url),"utf8"));return kind==="contract"?{$schema:asset.$schema,...asset.properties.contract}:asset}export function metricWriteFailure(error,message,hint){if(!(error instanceof CliError))return CliErrors.apiError(message,hint);const descriptors=Object.getOwnPropertyDescriptors(error);return Object.defineProperties(new CliError(error.code,error.exitCode,error.message),{...descriptors,hint:{...descriptors.hint,value:hint}})}export function requireMetricId(record){if(typeof record.id!=="string"||!/^[1-9][0-9]*$/.test(record.id)){
2
+ throw CliErrors.apiError("Invalid metric record ID; expected a positive decimal string.")}return record.id}
@@ -1 +1 @@
1
- import{resolve}from"node:path";import{metricCommand}from"./shared.js";import{readMetricJson}from"./contract.js";import{validateMetricPublication}from"./definition.js";export const metricValidate={...metricCommand,command:"validate",description:"Validate a metric definition, contracts and examples without executing queries",flags:[{name:"file",type:"string",required:true,description:"Self-contained metric definition JSON file"}],async execute(ctx){const file=ctx.str("file");validateMetricPublication(await readMetricJson(resolve(file)));return{ok:true,data:{valid:true,verification:"definition-and-contract"}}}};
1
+ import{resolve}from"node:path";import{metricCommand}from"./shared.js";import{readMetricJson}from"./contract.js";import{validateMetricPublication}from"./definition.js";export const metricValidate={...metricCommand,command:"validate",description:"Validate metric definition structure without interpreting contract internals",flags:[{name:"file",type:"string",required:true,description:"Self-contained metric definition JSON file"}],async execute(ctx){const file=ctx.str("file");validateMetricPublication(await readMetricJson(resolve(file)));return{ok:true,data:{valid:true,verification:"definition-structure"}}}};
@@ -1,5 +1,5 @@
1
1
  import { ENTERPRISE_ROUTING_CDN_FIELDS, ENTERPRISE_ROUTING_DOMAIN_FIELDS } from "../generated/routing-contract.js";
2
- export declare const DOMAIN_CONFIG_FIELDS: readonly ["userDomain", "apiDomain", "runtimeDomain", "skillDomain", "kbDomain", "kbServiceDomain", "appDomain", "localDomain", "certificateDomain"];
2
+ export declare const DOMAIN_CONFIG_FIELDS: readonly ["userDomain", "userCenterDomain", "apiDomain", "runtimeDomain", "skillDomain", "kbDomain", "kbServiceDomain", "appDomain", "localDomain", "certificateDomain"];
3
3
  export type DomainConfigField = (typeof DOMAIN_CONFIG_FIELDS)[number];
4
4
  export type DomainConfig = Partial<Record<DomainConfigField, string>>;
5
5
  export type EnterpriseRoutingDomainField = (typeof ENTERPRISE_ROUTING_DOMAIN_FIELDS)[number];
@@ -1,8 +1,9 @@
1
- import{existsSync,readFileSync}from"node:fs";import{isAbsolute,resolve}from"node:path";import{CliErrors}from"../errors.js";import{ENTERPRISE_ROUTING_CDN_FIELDS,ENTERPRISE_ROUTING_DOMAIN_FIELDS,ENTERPRISE_ROUTING_KIND,ENTERPRISE_ROUTING_PROTOCOL,REQUIRED_ENTERPRISE_ROUTING_CDN_FIELDS,REQUIRED_ENTERPRISE_ROUTING_DOMAIN_FIELDS}from"../generated/routing-contract.js";export const DOMAIN_CONFIG_FIELDS=["userDomain","apiDomain","runtimeDomain","skillDomain","kbDomain","kbServiceDomain","appDomain","localDomain","certificateDomain"];const DOMAIN_FLAGS={userDomain:"user-domain",apiDomain:"api-domain",runtimeDomain:"runtime-domain",skillDomain:"skill-domain",kbDomain:"kb-domain",kbServiceDomain:"kb-service-domain",appDomain:"app-domain",localDomain:"local-domain",certificateDomain:"certificate-domain"};export const LEGACY_DOMAIN_CONFIG_FIELDS=["agentDomain","platformDomain","skillHubDomain"];const ENTERPRISE_TO_LOCAL_FIELD={userDomain:"userDomain",apiDomain:"apiDomain",
2
- runtimeDomain:"runtimeDomain",skillDomain:"skillDomain",kbDomain:"kbDomain",kbServiceDomain:"kbServiceDomain",appDomain:"appDomain",localDomain:"localDomain",certificateDomain:"certificateDomain"};const ROUTING_CONSUMER="rabetbase-cli";export function normalizeDomainOrigin(field,input){if(typeof input!=="string"||!input.trim()){throw CliErrors.validation(`Invalid ${field}: expected a non-empty HTTPS origin.`)}let url;try{url=new URL(input.trim())}catch{throw CliErrors.validation(`Invalid ${field}: "${input}" is not a valid URL.`)}if(url.protocol!=="https:"||url.username||url.password||url.pathname!=="/"&&url.pathname!==""||url.search||url.hash){throw CliErrors.validation(`Invalid ${field}: expected an HTTPS origin without credentials, path, query, or fragment.`,"For internal deployments, terminate TLS at the ingress, reverse proxy, or load balancer; an internal CA is supported.")}return url.origin}export function normalizeRoutingDomainValue(field,input){
3
- if(typeof input==="string")return normalizeDomainOrigin(field,input);if(!input||typeof input!=="object"||Array.isArray(input)){throw CliErrors.validation(`Invalid ${field}: expected an HTTPS origin or consumer Domain object.`)}const source=input;const resolved=source[ROUTING_CONSUMER]??source.default;if(resolved===undefined){throw CliErrors.validation(`Enterprise ${field} does not provide a Domain for ${ROUTING_CONSUMER} and has no default.`)}return normalizeDomainOrigin(field,resolved)}export function normalizeCdnBaseUrl(field,input){if(typeof input!=="string"||!input.trim()){throw CliErrors.validation(`Invalid cdn.${field}: expected a non-empty HTTPS URL.`)}const value=input.trim().replace(/\/$/,"");let url;try{url=new URL(value)}catch{throw CliErrors.validation(`Invalid cdn.${field}: "${input}" is not a valid URL.`)}if(url.protocol!=="https:"||url.username||url.password||url.search||url.hash||url.href.replace(/\/$/,"")!==value||field==="lovrabet"&&url.origin!==value){
4
- throw CliErrors.validation(`Invalid cdn.${field}: expected an HTTPS ${field==="lovrabet"?"origin":"base URL"} without credentials, query, or fragment.`)}return value}export function resolveEnterpriseRoutingConfig(input){return resolveEnterpriseRoutingManifest(input)?.domains}export function resolveEnterpriseRoutingManifest(input){if(input===undefined)return undefined;if(!input||typeof input!=="object"||Array.isArray(input)){throw CliErrors.validation("Invalid enterprise routing config: expected an object.")}return parseEnterpriseRoutingManifest(input)}export function readDomainConfigInput(filePath){const absolutePath=isAbsolute(filePath)?filePath:resolve(process.cwd(),filePath);if(!existsSync(absolutePath)){throw CliErrors.validation(`Domain config file not found: ${absolutePath}`)}let parsed;try{parsed=JSON.parse(readFileSync(absolutePath,"utf8"))}catch{throw CliErrors.validation(`Invalid domain config JSON: ${absolutePath}`)}
5
- if(!parsed||typeof parsed!=="object"||Array.isArray(parsed)){throw CliErrors.validation("Invalid domain config: expected a JSON object.")}const source=parsed;if("protocol"in source)return parseEnterpriseRoutingManifest(source);const unknown=Object.keys(source).filter(key=>!DOMAIN_CONFIG_FIELDS.includes(key));if(unknown.length>0){throw CliErrors.validation(`Unsupported domain config field(s): ${unknown.join(", ")}. Allowed fields: ${DOMAIN_CONFIG_FIELDS.join(", ")}`)}const result={};for(const field of DOMAIN_CONFIG_FIELDS){if(source[field]!==undefined){result[field]=normalizeDomainOrigin(field,source[field])}}if(Object.keys(result).length===0){throw CliErrors.validation("Invalid domain config: provide at least one supported Domain.")}return{mode:"legacy",domains:result}}export function readDomainConfig(filePath){return readDomainConfigInput(filePath).domains}export function resolveDomainConfigInput(ctx){const filePath=(ctx.str("domain-config")||"").trim()
6
- ;const input=filePath?readDomainConfigInput(filePath):{mode:"legacy",domains:{}};const explicitFields=DOMAIN_CONFIG_FIELDS.filter(field=>Boolean((ctx.str(DOMAIN_FLAGS[field])||"").trim()));if(input.mode==="enterprise-v1"&&explicitFields.length>0){throw CliErrors.validation("Enterprise routing manifests cannot be combined with individual Domain flags.","Update the manifest so both CLIs consume the same routing data.")}for(const field of DOMAIN_CONFIG_FIELDS){const value=(ctx.str(DOMAIN_FLAGS[field])||"").trim();if(value)input.domains[field]=normalizeDomainOrigin(field,value)}return input}export function resolveDomainFlags(ctx){return resolveDomainConfigInput(ctx).domains}export function parseEnterpriseRoutingManifest(source){if(source.protocol!==ENTERPRISE_ROUTING_PROTOCOL||source.kind!==ENTERPRISE_ROUTING_KIND){throw CliErrors.validation(`Unsupported routing manifest: expected protocol "${ENTERPRISE_ROUTING_PROTOCOL}" and kind "${ENTERPRISE_ROUTING_KIND}".`)}
7
- if(!source.domains||typeof source.domains!=="object"||Array.isArray(source.domains)){throw CliErrors.validation("Invalid enterprise routing manifest: domains must be an object.")}if(!source.cdn||typeof source.cdn!=="object"||Array.isArray(source.cdn)){throw CliErrors.validation("Invalid enterprise routing manifest: cdn must be an object.")}const rawDomains=source.domains;const missing=REQUIRED_ENTERPRISE_ROUTING_DOMAIN_FIELDS.filter(field=>rawDomains[field]===undefined);if(missing.length>0){throw CliErrors.validation(`Enterprise routing manifest is missing required Domain(s): ${missing.join(", ")}`)}if(rawDomains.localDomain===undefined!==(rawDomains.certificateDomain===undefined)){throw CliErrors.validation("Enterprise routing manifest requires localDomain and certificateDomain together.")}const rawCdn=source.cdn;const unknownCdnFields=Object.keys(rawCdn).filter(field=>!ENTERPRISE_ROUTING_CDN_FIELDS.includes(field));if(unknownCdnFields.length>0){
8
- throw CliErrors.validation(`Unsupported enterprise CDN field(s): ${unknownCdnFields.join(", ")}. Allowed fields: ${ENTERPRISE_ROUTING_CDN_FIELDS.join(", ")}`)}const missingCdnFields=REQUIRED_ENTERPRISE_ROUTING_CDN_FIELDS.filter(field=>rawCdn[field]===undefined);if(missingCdnFields.length>0){throw CliErrors.validation(`Enterprise routing manifest is missing required CDN field(s): ${missingCdnFields.join(", ")}`)}const cdn={};for(const field of ENTERPRISE_ROUTING_CDN_FIELDS){cdn[field]=normalizeCdnBaseUrl(field,rawCdn[field])}const manifestDomains={};const domains={};for(const field of ENTERPRISE_ROUTING_DOMAIN_FIELDS){const value=rawDomains[field];if(value===undefined)continue;const normalized=normalizeRoutingDomainValue(field,value);manifestDomains[field]=normalized;const localField=ENTERPRISE_TO_LOCAL_FIELD[field];if(localField){domains[localField]=normalized}}return{mode:"enterprise-v1",domains:domains,manifestDomains:manifestDomains,cdn:cdn}}
1
+ import{existsSync,readFileSync}from"node:fs";import{isAbsolute,resolve}from"node:path";import{CliErrors}from"../errors.js";import{ENTERPRISE_ROUTING_CDN_FIELDS,ENTERPRISE_ROUTING_DOMAIN_FIELDS,ENTERPRISE_ROUTING_KIND,ENTERPRISE_ROUTING_PROTOCOL,REQUIRED_ENTERPRISE_ROUTING_CDN_FIELDS,REQUIRED_ENTERPRISE_ROUTING_DOMAIN_FIELDS}from"../generated/routing-contract.js";export const DOMAIN_CONFIG_FIELDS=["userDomain","userCenterDomain","apiDomain","runtimeDomain","skillDomain","kbDomain","kbServiceDomain","appDomain","localDomain","certificateDomain"];const DOMAIN_FLAGS={userDomain:"user-domain",userCenterDomain:"user-center-domain",apiDomain:"api-domain",runtimeDomain:"runtime-domain",skillDomain:"skill-domain",kbDomain:"kb-domain",kbServiceDomain:"kb-service-domain",appDomain:"app-domain",localDomain:"local-domain",certificateDomain:"certificate-domain"};export const LEGACY_DOMAIN_CONFIG_FIELDS=["agentDomain","platformDomain","skillHubDomain"];const ENTERPRISE_TO_LOCAL_FIELD={
2
+ userDomain:"userDomain",apiDomain:"apiDomain",runtimeDomain:"runtimeDomain",skillDomain:"skillDomain",kbDomain:"kbDomain",kbServiceDomain:"kbServiceDomain",appDomain:"appDomain",localDomain:"localDomain",certificateDomain:"certificateDomain"};const ROUTING_CONSUMER="rabetbase-cli";export function normalizeDomainOrigin(field,input){if(typeof input!=="string"||!input.trim()){throw CliErrors.validation(`Invalid ${field}: expected a non-empty HTTPS origin.`)}let url;try{url=new URL(input.trim())}catch{throw CliErrors.validation(`Invalid ${field}: "${input}" is not a valid URL.`)}if(url.protocol!=="https:"||url.username||url.password||url.pathname!=="/"&&url.pathname!==""||url.search||url.hash){throw CliErrors.validation(`Invalid ${field}: expected an HTTPS origin without credentials, path, query, or fragment.`,"For internal deployments, terminate TLS at the ingress, reverse proxy, or load balancer; an internal CA is supported.")}return url.origin}
3
+ export function normalizeRoutingDomainValue(field,input){if(typeof input==="string")return normalizeDomainOrigin(field,input);if(!input||typeof input!=="object"||Array.isArray(input)){throw CliErrors.validation(`Invalid ${field}: expected an HTTPS origin or consumer Domain object.`)}const source=input;const resolved=source[ROUTING_CONSUMER]??source.default;if(resolved===undefined){throw CliErrors.validation(`Enterprise ${field} does not provide a Domain for ${ROUTING_CONSUMER} and has no default.`)}return normalizeDomainOrigin(field,resolved)}export function normalizeCdnBaseUrl(field,input){if(typeof input!=="string"||!input.trim()){throw CliErrors.validation(`Invalid cdn.${field}: expected a non-empty HTTPS URL.`)}const value=input.trim().replace(/\/$/,"");let url;try{url=new URL(value)}catch{throw CliErrors.validation(`Invalid cdn.${field}: "${input}" is not a valid URL.`)}
4
+ if(url.protocol!=="https:"||url.username||url.password||url.search||url.hash||url.href.replace(/\/$/,"")!==value||field==="lovrabet"&&url.origin!==value){throw CliErrors.validation(`Invalid cdn.${field}: expected an HTTPS ${field==="lovrabet"?"origin":"base URL"} without credentials, query, or fragment.`)}return value}export function resolveEnterpriseRoutingConfig(input){return resolveEnterpriseRoutingManifest(input)?.domains}export function resolveEnterpriseRoutingManifest(input){if(input===undefined)return undefined;if(!input||typeof input!=="object"||Array.isArray(input)){throw CliErrors.validation("Invalid enterprise routing config: expected an object.")}return parseEnterpriseRoutingManifest(input)}export function readDomainConfigInput(filePath){const absolutePath=isAbsolute(filePath)?filePath:resolve(process.cwd(),filePath);if(!existsSync(absolutePath)){throw CliErrors.validation(`Domain config file not found: ${absolutePath}`)}let parsed;try{
5
+ parsed=JSON.parse(readFileSync(absolutePath,"utf8"))}catch{throw CliErrors.validation(`Invalid domain config JSON: ${absolutePath}`)}if(!parsed||typeof parsed!=="object"||Array.isArray(parsed)){throw CliErrors.validation("Invalid domain config: expected a JSON object.")}const source=parsed;if("protocol"in source)return parseEnterpriseRoutingManifest(source);const unknown=Object.keys(source).filter(key=>!DOMAIN_CONFIG_FIELDS.includes(key));if(unknown.length>0){throw CliErrors.validation(`Unsupported domain config field(s): ${unknown.join(", ")}. Allowed fields: ${DOMAIN_CONFIG_FIELDS.join(", ")}`)}const result={};for(const field of DOMAIN_CONFIG_FIELDS){if(source[field]!==undefined){result[field]=normalizeDomainOrigin(field,source[field])}}if(Object.keys(result).length===0){throw CliErrors.validation("Invalid domain config: provide at least one supported Domain.")}return{mode:"legacy",domains:result}}export function readDomainConfig(filePath){
6
+ return readDomainConfigInput(filePath).domains}export function resolveDomainConfigInput(ctx){const filePath=(ctx.str("domain-config")||"").trim();const input=filePath?readDomainConfigInput(filePath):{mode:"legacy",domains:{}};const explicitFields=DOMAIN_CONFIG_FIELDS.filter(field=>Boolean((ctx.str(DOMAIN_FLAGS[field])||"").trim()));if(input.mode==="enterprise-v1"&&explicitFields.some(field=>field!=="userCenterDomain")){throw CliErrors.validation("Enterprise routing manifests cannot be combined with individual service Domain flags.","Update the manifest so both CLIs consume the same routing data.")}for(const field of DOMAIN_CONFIG_FIELDS){const value=(ctx.str(DOMAIN_FLAGS[field])||"").trim();if(value)input.domains[field]=normalizeDomainOrigin(field,value)}return input}export function resolveDomainFlags(ctx){return resolveDomainConfigInput(ctx).domains}export function parseEnterpriseRoutingManifest(source){
7
+ if(source.protocol!==ENTERPRISE_ROUTING_PROTOCOL||source.kind!==ENTERPRISE_ROUTING_KIND){throw CliErrors.validation(`Unsupported routing manifest: expected protocol "${ENTERPRISE_ROUTING_PROTOCOL}" and kind "${ENTERPRISE_ROUTING_KIND}".`)}if(!source.domains||typeof source.domains!=="object"||Array.isArray(source.domains)){throw CliErrors.validation("Invalid enterprise routing manifest: domains must be an object.")}if(!source.cdn||typeof source.cdn!=="object"||Array.isArray(source.cdn)){throw CliErrors.validation("Invalid enterprise routing manifest: cdn must be an object.")}const rawDomains=source.domains;const missing=REQUIRED_ENTERPRISE_ROUTING_DOMAIN_FIELDS.filter(field=>rawDomains[field]===undefined);if(missing.length>0){throw CliErrors.validation(`Enterprise routing manifest is missing required Domain(s): ${missing.join(", ")}`)}if(rawDomains.localDomain===undefined!==(rawDomains.certificateDomain===undefined)){
8
+ throw CliErrors.validation("Enterprise routing manifest requires localDomain and certificateDomain together.")}const rawCdn=source.cdn;const unknownCdnFields=Object.keys(rawCdn).filter(field=>!ENTERPRISE_ROUTING_CDN_FIELDS.includes(field));if(unknownCdnFields.length>0){throw CliErrors.validation(`Unsupported enterprise CDN field(s): ${unknownCdnFields.join(", ")}. Allowed fields: ${ENTERPRISE_ROUTING_CDN_FIELDS.join(", ")}`)}const missingCdnFields=REQUIRED_ENTERPRISE_ROUTING_CDN_FIELDS.filter(field=>rawCdn[field]===undefined);if(missingCdnFields.length>0){throw CliErrors.validation(`Enterprise routing manifest is missing required CDN field(s): ${missingCdnFields.join(", ")}`)}const cdn={};for(const field of ENTERPRISE_ROUTING_CDN_FIELDS){cdn[field]=normalizeCdnBaseUrl(field,rawCdn[field])}const manifestDomains={};const domains={};for(const field of ENTERPRISE_ROUTING_DOMAIN_FIELDS){const value=rawDomains[field];if(value===undefined)continue
9
+ ;const normalized=normalizeRoutingDomainValue(field,value);manifestDomains[field]=normalized;const localField=ENTERPRISE_TO_LOCAL_FIELD[field];if(localField){domains[localField]=normalized}}return{mode:"enterprise-v1",domains:domains,manifestDomains:manifestDomains,cdn:cdn}}
@@ -1,6 +1,6 @@
1
1
  import type { FlagDef } from "../framework/types.js";
2
2
  export { DEFAULT_CONFIG_VALUES } from "../constant/defaults.js";
3
- export declare const PROJECT_CREATE_INHERITABLE_KEYS: readonly ["cookie", "accessKey", "locale", "format", "riskLevel", "region", "routing", "userDomain", "apiDomain", "runtimeDomain", "skillDomain", "kbDomain", "kbServiceDomain", "appDomain", "localDomain", "certificateDomain"];
3
+ export declare const PROJECT_CREATE_INHERITABLE_KEYS: readonly ["cookie", "accessKey", "locale", "format", "riskLevel", "region", "routing", "userDomain", "userCenterDomain", "apiDomain", "runtimeDomain", "skillDomain", "kbDomain", "kbServiceDomain", "appDomain", "localDomain", "certificateDomain"];
4
4
  export interface ConfigMetadataFields {
5
5
  version?: string;
6
6
  createdAt?: string;
@@ -1,7 +1,7 @@
1
- import{DEFAULT_CONFIG_VALUES}from"../constant/defaults.js";import{isDaily,isProduction,RABETBASE_ENV_VALUES}from"../constant/env.js";import{RABETBASE_OUTPUT_FORMAT_VALUES}from"../constant/output.js";import{RISK_LEVEL_VALUES}from"../constant/risk.js";import{ENABLED_LOVRABET_REGION_VALUES}from"../constant/region.js";export{DEFAULT_CONFIG_VALUES}from"../constant/defaults.js";export const PROJECT_CREATE_INHERITABLE_KEYS=["cookie","accessKey","locale","format","riskLevel","region","routing","userDomain","apiDomain","runtimeDomain","skillDomain","kbDomain","kbServiceDomain","appDomain","localDomain","certificateDomain"];export const TOP_LEVEL_CONFIG_KEYS=new Set(["appcode","env","locale","format","cookie","accessKey","apiDir","region","userDomain","apiDomain","runtimeDomain","skillDomain","kbDomain","kbServiceDomain","appDomain","localDomain","certificateDomain"]);export const CONFIG_ENUM_VALUES={env:[...RABETBASE_ENV_VALUES],format:[...RABETBASE_OUTPUT_FORMAT_VALUES],
2
- region:[...ENABLED_LOVRABET_REGION_VALUES]};export function formatConfigKeyList(keys){return[...keys].join(", ")}export function getTopLevelConfigKeyList(){return[...TOP_LEVEL_CONFIG_KEYS]}export function isTopLevelConfigKey(key){return TOP_LEVEL_CONFIG_KEYS.has(key)}export function getTopLevelConfigKeySummary(){return formatConfigKeyList(getTopLevelConfigKeyList())}export function getConfigCommandKeyDescription(){return`Config key (${getTopLevelConfigKeySummary()})`}export const APP_PROFILE_FLAG_KEY_MAP={apiGroup:"apiGroup",region:"region",env:"env",apiDir:"apiDir",cookie:"cookie",accessKey:"accessKey",defaultFormat:"format",pageSize:"pageSize",riskLevel:"riskLevel",locale:"locale"};export function getAppProfileFlagDefs(){return[{name:"apiGroup",type:"string",description:"Join key for app profiles that share one generated API model registry"},{name:"region",type:"string",description:"Country/region for this app profile",enum:[...ENABLED_LOVRABET_REGION_VALUES]},{name:"env",
3
- type:"string",description:"Target environment",enum:[...RABETBASE_ENV_VALUES]},{name:"apiDir",type:"string",description:"API directory path"},{name:"cookie",type:"string",description:"Auth cookie",hidden:true},{name:"accessKey",type:"string",description:"Access key",hidden:true},{name:"defaultFormat",type:"string",description:"Default output format for this app (profile)",enum:[...RABETBASE_OUTPUT_FORMAT_VALUES]},{name:"pageSize",type:"number",description:"Default page size"},{name:"riskLevel",type:"string",description:"Risk level",enum:[...RISK_LEVEL_VALUES]},{name:"locale",type:"string",description:"App locale (not CLI language; reserved for later app use)"}]}export function collectAppProfileOverrides(getFlagValue){const profile={};for(const[flagKey,profileKey]of Object.entries(APP_PROFILE_FLAG_KEY_MAP)){const val=getFlagValue(flagKey);if(!val)continue;profile[profileKey]=profileKey==="pageSize"?Number(val):val}return profile}export function buildAppProfileListFields(profile){return{
4
- apiGroup:profile.apiGroup??null,region:profile.region??null,env:profile.env??null,apiDir:profile.apiDir??null,hasCookie:!!profile.cookie,hasAccessKey:!!profile.accessKey,format:profile.format??null,pageSize:profile.pageSize??null,riskLevel:profile.riskLevel??null,locale:profile.locale??null}}export function buildAppDoctorFields(profile,effective){return{region:{value:profile.region||effective.region,source:profile.region?"app":"inherit"},env:{value:profile.env||effective.env,source:profile.env?"app":"inherit"},apiDir:{value:profile.apiDir||effective.apiDir,source:profile.apiDir?"app":"inherit"},cookie:{value:profile.cookie||effective.cookie,source:profile.cookie?"app":"inherit"},accessKey:{value:profile.accessKey||effective.accessKey,source:profile.accessKey?"app":"inherit"}}}export function buildCanonicalAppConfig(appCodes,env){const normalized=appCodes.map(code=>String(code||"").trim()).filter(Boolean);if(normalized.length===0)return{};const apps={};for(const appCode of normalized){
5
- apps[appCode]=env&&!isProduction(env)?{appcode:appCode,env:env}:{appcode:appCode}}return normalized.length>1?{apps:apps,defaultApp:normalized[0]}:{apps:apps}}export function normalizeStoredDefaultApp(config,preferredApp){const apps=config.apps&&typeof config.apps==="object"?config.apps:{};const names=Object.keys(apps);if(names.length<=1){delete config.defaultApp;return undefined}const current=typeof config.defaultApp==="string"&&apps[config.defaultApp]?config.defaultApp:undefined;const selected=preferredApp&&apps[preferredApp]?preferredApp:current;if(selected){config.defaultApp=selected;return selected}delete config.defaultApp;return undefined}export function buildCanonicalProjectConfig(base,options){const{appCodes:appCodes=[],env:env,metadata:metadata}=options;const config={...base,...metadata||{}};delete config.appcode;delete config.app;const effectiveEnv=env||(typeof config.env==="string"?config.env:"")||DEFAULT_CONFIG_VALUES.env
6
- ;if(isProduction(effectiveEnv))delete config.env;else config.env=effectiveEnv;const appConfig=buildCanonicalAppConfig(appCodes,effectiveEnv);if(Object.keys(appConfig).length>0){config.apps=appConfig.apps;if(appConfig.defaultApp)config.defaultApp=appConfig.defaultApp;else delete config.defaultApp}return normalizeConfigForWrite(config)}function isRecord(value){return!!value&&typeof value==="object"&&!Array.isArray(value)}export function normalizeConfigForWrite(input){const config={...input};const inputApps=isRecord(input.apps)?input.apps:undefined;const apps=inputApps?Object.fromEntries(Object.entries(inputApps).map(([name,profile])=>[name,isRecord(profile)?{...profile}:profile])):undefined;if(apps){const topLevelEnv=typeof config.env==="string"?config.env:undefined;const hasDefaultOverride=Object.values(apps).some(profile=>isRecord(profile)&&typeof profile.env==="string"&&isProduction(profile.env));if(topLevelEnv&&isDaily(topLevelEnv)&&hasDefaultOverride){
7
- for(const profile of Object.values(apps)){if(!isRecord(profile))continue;if(profile.env===undefined)profile.env=topLevelEnv}delete config.env}for(const profile of Object.values(apps)){if(isRecord(profile)&&typeof profile.env==="string"&&isProduction(profile.env)){delete profile.env}}config.apps=apps}if(typeof config.env==="string"&&isProduction(config.env)){delete config.env}return config}const LOCALE_MAP={zh:"zh-CN","zh-cn":"zh-CN",zh_cn:"zh-CN",en:"en-US","en-us":"en-US",en_us:"en-US"};export function normalizeLocale(value){if(!value)return null;return LOCALE_MAP[value.toLowerCase()]??null}
1
+ import{DEFAULT_CONFIG_VALUES}from"../constant/defaults.js";import{isDaily,isProduction,RABETBASE_ENV_VALUES}from"../constant/env.js";import{RABETBASE_OUTPUT_FORMAT_VALUES}from"../constant/output.js";import{RISK_LEVEL_VALUES}from"../constant/risk.js";import{ENABLED_LOVRABET_REGION_VALUES}from"../constant/region.js";export{DEFAULT_CONFIG_VALUES}from"../constant/defaults.js";export const PROJECT_CREATE_INHERITABLE_KEYS=["cookie","accessKey","locale","format","riskLevel","region","routing","userDomain","userCenterDomain","apiDomain","runtimeDomain","skillDomain","kbDomain","kbServiceDomain","appDomain","localDomain","certificateDomain"];export const TOP_LEVEL_CONFIG_KEYS=new Set(["appcode","env","locale","format","cookie","accessKey","apiDir","region","userDomain","userCenterDomain","apiDomain","runtimeDomain","skillDomain","kbDomain","kbServiceDomain","appDomain","localDomain","certificateDomain"]);export const CONFIG_ENUM_VALUES={env:[...RABETBASE_ENV_VALUES],
2
+ format:[...RABETBASE_OUTPUT_FORMAT_VALUES],region:[...ENABLED_LOVRABET_REGION_VALUES]};export function formatConfigKeyList(keys){return[...keys].join(", ")}export function getTopLevelConfigKeyList(){return[...TOP_LEVEL_CONFIG_KEYS]}export function isTopLevelConfigKey(key){return TOP_LEVEL_CONFIG_KEYS.has(key)}export function getTopLevelConfigKeySummary(){return formatConfigKeyList(getTopLevelConfigKeyList())}export function getConfigCommandKeyDescription(){return`Config key (${getTopLevelConfigKeySummary()})`}export const APP_PROFILE_FLAG_KEY_MAP={apiGroup:"apiGroup",region:"region",env:"env",apiDir:"apiDir",cookie:"cookie",accessKey:"accessKey",defaultFormat:"format",pageSize:"pageSize",riskLevel:"riskLevel",locale:"locale"};export function getAppProfileFlagDefs(){return[{name:"apiGroup",type:"string",description:"Join key for app profiles that share one generated API model registry"},{name:"region",type:"string",description:"Country/region for this app profile",
3
+ enum:[...ENABLED_LOVRABET_REGION_VALUES]},{name:"env",type:"string",description:"Target environment",enum:[...RABETBASE_ENV_VALUES]},{name:"apiDir",type:"string",description:"API directory path"},{name:"cookie",type:"string",description:"Auth cookie",hidden:true},{name:"accessKey",type:"string",description:"Access key",hidden:true},{name:"defaultFormat",type:"string",description:"Default output format for this app (profile)",enum:[...RABETBASE_OUTPUT_FORMAT_VALUES]},{name:"pageSize",type:"number",description:"Default page size"},{name:"riskLevel",type:"string",description:"Risk level",enum:[...RISK_LEVEL_VALUES]},{name:"locale",type:"string",description:"App locale (not CLI language; reserved for later app use)"}]}export function collectAppProfileOverrides(getFlagValue){const profile={};for(const[flagKey,profileKey]of Object.entries(APP_PROFILE_FLAG_KEY_MAP)){const val=getFlagValue(flagKey);if(!val)continue;profile[profileKey]=profileKey==="pageSize"?Number(val):val}return profile}
4
+ export function buildAppProfileListFields(profile){return{apiGroup:profile.apiGroup??null,region:profile.region??null,env:profile.env??null,apiDir:profile.apiDir??null,hasCookie:!!profile.cookie,hasAccessKey:!!profile.accessKey,format:profile.format??null,pageSize:profile.pageSize??null,riskLevel:profile.riskLevel??null,locale:profile.locale??null}}export function buildAppDoctorFields(profile,effective){return{region:{value:profile.region||effective.region,source:profile.region?"app":"inherit"},env:{value:profile.env||effective.env,source:profile.env?"app":"inherit"},apiDir:{value:profile.apiDir||effective.apiDir,source:profile.apiDir?"app":"inherit"},cookie:{value:profile.cookie||effective.cookie,source:profile.cookie?"app":"inherit"},accessKey:{value:profile.accessKey||effective.accessKey,source:profile.accessKey?"app":"inherit"}}}export function buildCanonicalAppConfig(appCodes,env){const normalized=appCodes.map(code=>String(code||"").trim()).filter(Boolean)
5
+ ;if(normalized.length===0)return{};const apps={};for(const appCode of normalized){apps[appCode]=env&&!isProduction(env)?{appcode:appCode,env:env}:{appcode:appCode}}return normalized.length>1?{apps:apps,defaultApp:normalized[0]}:{apps:apps}}export function normalizeStoredDefaultApp(config,preferredApp){const apps=config.apps&&typeof config.apps==="object"?config.apps:{};const names=Object.keys(apps);if(names.length<=1){delete config.defaultApp;return undefined}const current=typeof config.defaultApp==="string"&&apps[config.defaultApp]?config.defaultApp:undefined;const selected=preferredApp&&apps[preferredApp]?preferredApp:current;if(selected){config.defaultApp=selected;return selected}delete config.defaultApp;return undefined}export function buildCanonicalProjectConfig(base,options){const{appCodes:appCodes=[],env:env,metadata:metadata}=options;const config={...base,...metadata||{}};delete config.appcode;delete config.app
6
+ ;const effectiveEnv=env||(typeof config.env==="string"?config.env:"")||DEFAULT_CONFIG_VALUES.env;if(isProduction(effectiveEnv))delete config.env;else config.env=effectiveEnv;const appConfig=buildCanonicalAppConfig(appCodes,effectiveEnv);if(Object.keys(appConfig).length>0){config.apps=appConfig.apps;if(appConfig.defaultApp)config.defaultApp=appConfig.defaultApp;else delete config.defaultApp}return normalizeConfigForWrite(config)}function isRecord(value){return!!value&&typeof value==="object"&&!Array.isArray(value)}export function normalizeConfigForWrite(input){const config={...input};const inputApps=isRecord(input.apps)?input.apps:undefined;const apps=inputApps?Object.fromEntries(Object.entries(inputApps).map(([name,profile])=>[name,isRecord(profile)?{...profile}:profile])):undefined;if(apps){const topLevelEnv=typeof config.env==="string"?config.env:undefined
7
+ ;const hasDefaultOverride=Object.values(apps).some(profile=>isRecord(profile)&&typeof profile.env==="string"&&isProduction(profile.env));if(topLevelEnv&&isDaily(topLevelEnv)&&hasDefaultOverride){for(const profile of Object.values(apps)){if(!isRecord(profile))continue;if(profile.env===undefined)profile.env=topLevelEnv}delete config.env}for(const profile of Object.values(apps)){if(isRecord(profile)&&typeof profile.env==="string"&&isProduction(profile.env)){delete profile.env}}config.apps=apps}if(typeof config.env==="string"&&isProduction(config.env)){delete config.env}return config}const LOCALE_MAP={zh:"zh-CN","zh-cn":"zh-CN",zh_cn:"zh-CN",en:"en-US","en-us":"en-US",en_us:"en-US"};export function normalizeLocale(value){if(!value)return null;return LOCALE_MAP[value.toLowerCase()]??null}
@@ -2,10 +2,15 @@ import { type LovrabetRegion } from "../constant/region.js";
2
2
  /**
3
3
  * 初始化自定义域名(从 .rabetbase.json 合并配置中读取)。
4
4
  * 未配置的字段传 undefined,回退到默认域名。
5
+ *
6
+ * lovrabet-routing 的每份地区、环境路由都必须提供 user(用户中心 API)和 runtime(运行态 API),
7
+ * 以便两个服务各有默认地址。普通 CLI 配置中的 userDomain 和 runtimeDomain 是独立的可选覆盖项;
8
+ * 省略哪一项,就读取路由中对应的默认值,即使两个默认地址目前相同。
5
9
  */
6
10
  export declare function initDomains(domains?: {
7
11
  apiDomain?: string;
8
12
  userDomain?: string;
13
+ userCenterDomain?: string;
9
14
  runtimeDomain?: string;
10
15
  skillDomain?: string;
11
16
  kbDomain?: string;
@@ -21,8 +26,13 @@ export declare function initDomains(domains?: {
21
26
  region?: LovrabetRegion;
22
27
  }): void;
23
28
  export declare const getUserDomain: () => string;
29
+ /** Resolve a browser user-center origin independently of the authentication API. */
30
+ export declare function getUserPageDomain(region?: "global" | "id" | "cn", env?: string): string;
24
31
  export declare const getApiDomain: () => string;
25
32
  export declare const getRuntimeDomain: () => string;
33
+ /** Early telemetry can run before the CLI has selected the user API for this invocation. */
34
+ export declare function getAuthApiDomain(): string | undefined;
35
+ export declare function requireAuthApiDomain(): string;
26
36
  export declare const getSkillDomain: () => string;
27
37
  export declare const getKbDomain: () => string;
28
38
  /** Resolve only the dedicated KB management and search service; never infer it from another service. */