@lovrabet/rabetbase-cli 2.6.0-beta.4 → 2.6.1-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -3
- package/lib/commands/bff/push.js +18 -16
- package/lib/commands/metric/definition.d.ts +1 -1
- package/lib/commands/metric/detail.d.ts +15 -0
- package/lib/commands/metric/detail.js +2 -2
- package/lib/commands/metric/diagnostics.d.ts +18 -0
- package/lib/commands/metric/diagnostics.js +8 -0
- package/lib/commands/metric/list.js +2 -2
- package/lib/commands/metric/publish.js +6 -5
- package/lib/commands/metric/push-preflight.d.ts +2 -0
- package/lib/commands/metric/push-preflight.js +3 -0
- package/lib/commands/metric/shared.d.ts +1 -0
- package/lib/commands/metric/shared.js +2 -2
- package/lib/commands/metric/validate.js +2 -1
- package/lib/core/api-client.d.ts +5 -1
- package/lib/core/api-client.js +71 -70
- package/lib/core/bff/types.d.ts +3 -0
- package/lib/generated/build-info.d.ts +4 -4
- package/lib/generated/build-info.js +1 -1
- package/package.json +2 -2
- package/skills/rabetbase/SKILL.md +1 -1
- package/skills/rabetbase/guides/backend-function.md +16 -2
- package/skills/rabetbase/guides/bff-creation-workflow.md +1 -0
- package/skills/rabetbase/guides/metric-development.md +49 -52
- package/skills/rabetbase/references/rabetbase-bff-push.md +4 -2
- package/skills/rabetbase/references/rabetbase-metric.md +27 -15
- package/skills/rabetbase-dataset-generation/SKILL.md +1 -1
- package/skills/rabetbase-metrics-generation/SKILL.md +2 -2
- package/skills/rabetbase-metrics-generation/references/workflow.md +8 -10
- package/skills/rabetbase-page-generation/SKILL.md +1 -1
- package/skills/rabetbase.manifest.json +3 -3
- package/templates/metrics/definition.json +1 -25
- package/templates/metrics/metric-definition.schema.json +5 -5
- package/templates/metrics/metricPaidOrderCount.js +78 -0
package/README.md
CHANGED
|
@@ -47,8 +47,16 @@ the CLI may already be installed; fix the reported cause and rerun
|
|
|
47
47
|
|
|
48
48
|
`rabetbase update` installs the target CLI and invokes that new package's explicit
|
|
49
49
|
Skill installer before reporting success. A failed Skill step returns failure
|
|
50
|
-
without claiming that the CLI package was rolled back.
|
|
51
|
-
|
|
50
|
+
without claiming that the CLI package was rolled back.
|
|
51
|
+
|
|
52
|
+
When upgrading from 2.5.13, the old updater can install the new CLI and then exit
|
|
53
|
+
with `Built-in Skill verification failed`, because the new package has no
|
|
54
|
+
`postinstall`. First check `rabetbase --version`. Only if it is the intended
|
|
55
|
+
target version and the error is this Skill verification failure, run
|
|
56
|
+
`rabetbase cli-skill install`, then require `rabetbase doctor` to report the
|
|
57
|
+
matching version as `current`. Do not suppress npm installation errors or
|
|
58
|
+
continue after a failed Skill installation. In automation, handle this specific
|
|
59
|
+
partial completion explicitly: an `&&` chain or `set -e` stops before repair.
|
|
52
60
|
|
|
53
61
|
## Update and Verify
|
|
54
62
|
|
|
@@ -342,4 +350,4 @@ Preview the redacted content before submitting. On success, the command displays
|
|
|
342
350
|
|
|
343
351
|
### 指标目录与本地校验
|
|
344
352
|
|
|
345
|
-
`rabetbase metric schema`
|
|
353
|
+
`rabetbase metric schema` 读取指标定义结构,`metric example` 返回单个定义示例,`metric validate --file <metric.json>` 校验定义字段及 JSON 数值安全性。指标以应用和 `code` 定位,通过独立指标服务发布,仅支持 BFF 目标。默认发布示例只包含可写字段。详情中的 `contract` 来自绑定 ENDPOINT 的元数据,导出后可供 `metric validate` 诊断,发布时会剔除。运行态调用使用 `lovrabet metric exec`,仍需真实执行及业务对账。详见 [命令参考](skills/rabetbase/references/rabetbase-metric.md)、[定义结构](templates/metrics/metric-definition.schema.json)、[内置示例](templates/metrics/definition.json) 和 [操作指引](https://qizhiyuntu.feishu.cn/wiki/PY4DwJ2a8iyaf9koETicamgEnAf)。
|
package/lib/commands/bff/push.js
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
|
-
import{readFile}from"node:fs/promises";import{saveBffScript,getBffScriptInfo,getBffScriptStatistics,getPlatformErrorCode,listDatasets,clearBffScriptCache}from"../../core/api-client.js";import{loadAliasMap}from"../../core/alias-resolver.js";import{resolveApiModelSource}from"../../api/model-source.js";import{loadBffProjectConfig}from"../../core/bff/config.js";import{normalizeBffType,scanLocalBffFunctions}from"../../core/bff/file-system.js";import{buildHookDirectoryIndexes,assertUnambiguousHookAliases,assertUnambiguousHookDirectoryMappings,preflightPushHookDirectories,trackedHookDirectoryMappings}from"../../core/bff/hook-directory.js";import{computeFileHash}from"../../core/bff/hash.js";import{createEmptyBffLock,ensureLockScope,readBffLockFile,writeBffLockFile}from"../../core/bff/lock.js";import{extractScriptDescription,snakeToCamel}from"../../core/bff/utils.js";import{sleep}from"../../utils/sleep.js"
|
|
2
|
-
;const CACHE_CLEAR_ATTEMPTS=2;const CACHE_CLEAR_INTERVAL_MS=300;export const bffPush={service:"bff",command:"push",description:"Push local Backend Function scripts to remote",risk:"write",structuredErrors:true,flags:[{name:"type",type:"string",description:"Push only this script type",enum:["COMMON","ENDPOINT","HOOK"]},{name:"name",type:"string",description:"Push only the named function (requires --type)"},{name:"force",type:"boolean",description:"Force push ignoring hash protection"}],async dryRun(ctx){const config=loadBffProjectConfig(ctx.appCode);const rawLock=await readBffLockFile(config.lockFilePath);const{appLock:appLock}=ensureLockScope(rawLock??createEmptyBffLock(),ctx.appCode,config.scriptsRoot,"push");const localFunctions=await getTargetFunctions(config,ctx)
|
|
3
|
-
;const hookMaps=await buildHookMaps(ctx.appCode,ctx.apiDir,preflightFunctions,appLock,ctx.selectedAppName||ctx.mergedCli?.currentApp||ctx.mergedCli?.defaultApp);const force=ctx.bool("force");const preview=[];for(const fn of localFunctions){const localHash=await computeFileHash(fn.filePath);const lockEntry=appLock.functions[fn.lockKey];const unchanged=!!lockEntry&&lockEntry.hash===localHash;const hook=hookMaps.resolutions.get(fn.lockKey);const missingRemoteVersion=!!lockEntry?.remoteId&&lockEntry.version==null&&(force||!unchanged);const conflict=missingRemoteVersion?missingRemoteVersionConflict(fn,lockEntry):undefined;const status=hookMaps.failures.has(fn.lockKey)?"failed":!force&&unchanged?"unchanged":conflict?"conflict":"would_push";
|
|
4
|
-
conflict:conflict}:{},...hookMaps.existingHooks.has(fn.lockKey)?{datasetCode:lockEntry?.datasetCode,bindingPreserved:true,warnings:[existingHookWarning(fn.lockKey)]}:{},...hook?{alias:hook.alias??null,datasetCode:hook.datasetCode,operationType:fn.operationType,functionNode:fn.functionNode,warnings:hook.warnings}:{}})}return{method:"POST",url:"/api/management/library/scripts/save",body:{appCode:ctx.appCode,force:force,files:preview,cacheClearAtRuntime:preview.some(item=>item.status==="would_push"),cacheClearAtRuntimeTimes:preview.some(item=>item.status==="would_push")?CACHE_CLEAR_ATTEMPTS:0},description:`Would inspect ${preview.length} local Backend Function script(s) for push and clear runtime cache if files are uploaded`}},async execute(ctx){
|
|
5
|
-
;const localFunctions=await getTargetFunctions(config,ctx);if(localFunctions.length===0){return{ok:true,data:{uploaded:[],skipped:[],conflicts:[],failed:[]},message:"No local Backend Function scripts found."}}const force=ctx.bool("force");const nextLockData=JSON.parse(JSON.stringify(lockData));const nextAppLock=nextLockData.apps[ctx.appCode];if(!nextAppLock){throw new Error(`Lock scope for app "${ctx.appCode}" not found after ensureLockScope.`)}const preflightFunctions=localFunctions.some(fn=>fn.type==="HOOK")?await scanLocalBffFunctions(config,"HOOK"):localFunctions;const hookMaps=await buildHookMaps(ctx.appCode,ctx.apiDir,preflightFunctions,nextAppLock,ctx.selectedAppName||ctx.mergedCli?.currentApp||ctx.mergedCli?.defaultApp);const uploaded=[]
|
|
6
|
-
const localHash=await computeFileHash(fn.filePath);const lockEntry=nextAppLock.functions[fn.lockKey];if(!force&&lockEntry&&lockEntry.hash===localHash){skipped.push({lockKey:fn.lockKey,reason:"unchanged"});continue}if(lockEntry?.remoteId&&lockEntry.version==null){conflicts.push(missingRemoteVersionConflict(fn,lockEntry));continue}try{await
|
|
7
|
-
|
|
8
|
-
;
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
;
|
|
12
|
-
|
|
13
|
-
;
|
|
14
|
-
;
|
|
15
|
-
|
|
16
|
-
;if(
|
|
1
|
+
import{readFile}from"node:fs/promises";import{saveBffScript,getBffScriptInfo,getBffScriptStatistics,getPlatformErrorCode,getPlatformErrorData,getPlatformHttpStatus,isPlatformTransportFailure,listDatasets,clearBffScriptCache}from"../../core/api-client.js";import{loadAliasMap}from"../../core/alias-resolver.js";import{resolveApiModelSource}from"../../api/model-source.js";import{loadBffProjectConfig}from"../../core/bff/config.js";import{normalizeBffType,scanLocalBffFunctions}from"../../core/bff/file-system.js";import{buildHookDirectoryIndexes,assertUnambiguousHookAliases,assertUnambiguousHookDirectoryMappings,preflightPushHookDirectories,trackedHookDirectoryMappings}from"../../core/bff/hook-directory.js";import{computeContentHash,computeFileHash}from"../../core/bff/hash.js";import{createEmptyBffLock,ensureLockScope,readBffLockFile,writeBffLockFile}from"../../core/bff/lock.js";import{extractScriptDescription,snakeToCamel}from"../../core/bff/utils.js";import{sleep}from"../../utils/sleep.js"
|
|
2
|
+
;import{CLI_BIN_NAME}from"../../constant/cli.js";import{CliErrors}from"../../errors.js";import{metricPushPreflight}from"../../commands/metric/push-preflight.js";const CACHE_CLEAR_ATTEMPTS=2;const CACHE_CLEAR_INTERVAL_MS=300;export const bffPush={service:"bff",command:"push",description:"Push local Backend Function scripts to remote",risk:"write",structuredErrors:true,flags:[{name:"type",type:"string",description:"Push only this script type",enum:["COMMON","ENDPOINT","HOOK"]},{name:"name",type:"string",description:"Push only the named function (requires --type)"},{name:"force",type:"boolean",description:"Force push ignoring hash protection"}],async dryRun(ctx){const config=loadBffProjectConfig(ctx.appCode);const rawLock=await readBffLockFile(config.lockFilePath);const{appLock:appLock}=ensureLockScope(rawLock??createEmptyBffLock(),ctx.appCode,config.scriptsRoot,"push");const localFunctions=await getTargetFunctions(config,ctx)
|
|
3
|
+
;const preflightFunctions=localFunctions.some(fn=>fn.type==="HOOK")?await scanLocalBffFunctions(config,"HOOK"):localFunctions;const hookMaps=await buildHookMaps(ctx.appCode,ctx.apiDir,preflightFunctions,appLock,ctx.selectedAppName||ctx.mergedCli?.currentApp||ctx.mergedCli?.defaultApp);const force=ctx.bool("force");const preview=[];for(const fn of localFunctions){const localHash=await computeFileHash(fn.filePath);const lockEntry=appLock.functions[fn.lockKey];const unchanged=!!lockEntry&&lockEntry.hash===localHash;const hook=hookMaps.resolutions.get(fn.lockKey);const missingRemoteVersion=!!lockEntry?.remoteId&&lockEntry.version==null&&(force||!unchanged);const conflict=missingRemoteVersion?missingRemoteVersionConflict(fn,lockEntry):undefined;const status=hookMaps.failures.has(fn.lockKey)?"failed":!force&&unchanged?"unchanged":conflict?"conflict":"would_push";const metricWarnings=status==="would_push"?await metricPushPreflight(ctx.appCode,fn):[];preview.push({lockKey:fn.lockKey,
|
|
4
|
+
filePath:fn.filePath,remoteId:lockEntry?.remoteId??null,mode:lockEntry?.remoteId?"update":"create",status:status,...metricWarnings.length?{warnings:metricWarnings}:{},...hookMaps.failures.get(fn.lockKey),...conflict?{conflict:conflict}:{},...hookMaps.existingHooks.has(fn.lockKey)?{datasetCode:lockEntry?.datasetCode,bindingPreserved:true,warnings:[existingHookWarning(fn.lockKey)]}:{},...hook?{alias:hook.alias??null,datasetCode:hook.datasetCode,operationType:fn.operationType,functionNode:fn.functionNode,warnings:hook.warnings}:{}})}return{method:"POST",url:"/api/management/library/scripts/save",body:{appCode:ctx.appCode,force:force,files:preview,cacheClearAtRuntime:preview.some(item=>item.status==="would_push"),cacheClearAtRuntimeTimes:preview.some(item=>item.status==="would_push")?CACHE_CLEAR_ATTEMPTS:0},description:`Would inspect ${preview.length} local Backend Function script(s) for push and clear runtime cache if files are uploaded`}},async execute(ctx){
|
|
5
|
+
const config=loadBffProjectConfig(ctx.appCode);const rawLock=await readBffLockFile(config.lockFilePath);const{lockData:lockData,appLock:appLock}=ensureLockScope(rawLock??createEmptyBffLock(),ctx.appCode,config.scriptsRoot,"push");const localFunctions=await getTargetFunctions(config,ctx);if(localFunctions.length===0){return{ok:true,data:{uploaded:[],skipped:[],conflicts:[],failed:[]},message:"No local Backend Function scripts found."}}const force=ctx.bool("force");const nextLockData=JSON.parse(JSON.stringify(lockData));const nextAppLock=nextLockData.apps[ctx.appCode];if(!nextAppLock){throw new Error(`Lock scope for app "${ctx.appCode}" not found after ensureLockScope.`)}const preflightFunctions=localFunctions.some(fn=>fn.type==="HOOK")?await scanLocalBffFunctions(config,"HOOK"):localFunctions;const hookMaps=await buildHookMaps(ctx.appCode,ctx.apiDir,preflightFunctions,nextAppLock,ctx.selectedAppName||ctx.mergedCli?.currentApp||ctx.mergedCli?.defaultApp);const uploaded=[]
|
|
6
|
+
;const skipped=[];const conflicts=[];const failed=[];const pushWarnings=[];for(const fn of localFunctions){const preflightError=hookMaps.failures.get(fn.lockKey);if(preflightError){failed.push({lockKey:fn.lockKey,...preflightError});continue}const localHash=await computeFileHash(fn.filePath);const lockEntry=nextAppLock.functions[fn.lockKey];if(!force&&lockEntry&&lockEntry.hash===localHash){skipped.push({lockKey:fn.lockKey,reason:"unchanged"});continue}if(lockEntry?.remoteId&&lockEntry.version==null){conflicts.push(missingRemoteVersionConflict(fn,lockEntry));continue}try{const source=await readFile(fn.filePath,"utf8");const warnings=await metricPushPreflight(ctx.appCode,fn,source);for(const warning of warnings)console.warn(warning);pushWarnings.push(...warnings);const latestScript=await uploadSingleFunction(ctx.appCode,fn,nextAppLock,hookMaps,source);if(latestScript.dependenciesIncomplete===true){
|
|
7
|
+
const warning=`${fn.lockKey}: Published successfully. Dependency information for this version is incomplete.`;pushWarnings.push(warning);console.warn(warning)}const entry=nextAppLock.functions[fn.lockKey];uploaded.push({lockKey:fn.lockKey,remoteId:entry?.remoteId??0})}catch(error){const conflict=remoteVersionChangedConflict(fn,lockEntry,error);if(conflict){conflicts.push(conflict);continue}const failure=pushFailure(error);if(failure.remoteErrorCode==="BFF_METADATA_ANALYSIS_FAILED"){failure.functionName=fn.name;failure.hint="Check the published version and source. If the intended change is missing, contact the Studio maintainer before retrying."}failed.push({lockKey:fn.lockKey,...failure})}}nextAppLock.lastSync=(new Date).toISOString();await writeBffLockFile(config.lockFilePath,nextLockData);await waitForUploadedLockEntries(config.lockFilePath,ctx.appCode,uploaded.map(item=>item.lockKey));let cacheClear={attempted:false,cleared:false};if(uploaded.length>0){try{let message=""
|
|
8
|
+
;for(let attempt=0;attempt<CACHE_CLEAR_ATTEMPTS;attempt+=1){message=await clearBffScriptCache();if(attempt<CACHE_CLEAR_ATTEMPTS-1){await sleep(CACHE_CLEAR_INTERVAL_MS)}}cacheClear={attempted:true,cleared:true,message:message||"Runtime script cache cleared."}}catch(error){cacheClear={attempted:true,cleared:false,error:error instanceof Error?error.message:String(error)}}}const primarySucceeded=failed.length===0&&(cacheClear.attempted?cacheClear.cleared:true);const ok=primarySucceeded;const cacheMessage=cacheClear.attempted?cacheClear.cleared?"runtime cache cleared":"runtime cache clear failed":"runtime cache not needed";return{ok:ok,data:{uploaded:uploaded,skipped:skipped,conflicts:conflicts,failed:failed,cacheClear:cacheClear,warnings:[...pushWarnings,...[...hookMaps.resolutions.values()].flatMap(item=>item.warnings),...[...hookMaps.existingHooks].map(existingHookWarning)]},message:formatPushMessage(uploaded.length,skipped.length,conflicts.length,failed.length,cacheMessage)}}}
|
|
9
|
+
;function missingRemoteVersionConflict(fn,lockEntry){return remoteVersionConflict(fn,lockEntry,"BFF_REMOTE_VERSION_MISSING","The local sync lock has no remote version for this script.")}function remoteVersionChangedConflict(fn,lockEntry,error){if(!lockEntry?.remoteId||lockEntry.version==null||!isRemoteVersionConflict(error)){return undefined}const remoteErrorCode=getPlatformErrorCode(error);const details=getPlatformErrorData(error);const versions=details&&typeof details==="object"?details:{};const conflict=remoteVersionConflict(fn,lockEntry,"BFF_REMOTE_VERSION_CHANGED",error instanceof Error?error.message:String(error));if(remoteErrorCode)conflict.remoteErrorCode=remoteErrorCode;for(const key of["submittedVersion","currentVersion"]){const version=versions[key];if(typeof version==="number"&&Number.isSafeInteger(version))conflict[key]=version}return conflict}function remoteVersionConflict(fn,lockEntry,code,message){return{code:code,lockKey:fn.lockKey,filePath:fn.filePath,
|
|
10
|
+
remoteId:lockEntry.remoteId,...lockEntry.version!=null?{expectedVersion:lockEntry.version}:{},message:message,nextAction:{action:"review_remote_and_merge",command:`${CLI_BIN_NAME} bff detail --id ${lockEntry.remoteId} --format compress`,requiresReview:true,message:"Review the remote source. Set aside the edited local script outside the sync directory, pull to refresh the version, then merge your edits and retry push."}}}function isRemoteVersionConflict(error){const remoteCode=getPlatformErrorCode(error);if(remoteCode==="536")return true;const legacyConflict=/(?:version|optimistic)[\s_-]*(?:conflict|mismatch|changed|stale|out[\s_-]*of[\s_-]*date)|(?:conflict|mismatch|changed|stale|out[\s_-]*of[\s_-]*date)[\s_-]*(?:version|optimistic)/i;if(remoteCode&&remoteCode!=="500")return legacyConflict.test(remoteCode);if(!remoteCode&&(isPlatformTransportFailure(error)||(getPlatformHttpStatus(error)??0)>=500)){return false}const message=error instanceof Error?error.message:String(error)
|
|
11
|
+
;return legacyConflict.test(message)||/Script has been modified by someone else, please refresh and retry\. Current version:\s*\d+,\s*submitted version:\s*\d+/i.test(message)}function formatPushMessage(uploaded,skipped,conflicts,failed,cacheMessage){const parts=[`Push complete: ${uploaded} uploaded`,`${skipped} skipped`];if(conflicts>0){parts.push(`${conflicts} conflict${conflicts===1?"":"s"} ${conflicts===1?"requires":"require"} resolution`)}if(failed>0)parts.push(`${failed} failed`);parts.push(cacheMessage);return parts.join(", ")}async function getTargetFunctions(config,ctx){const typeFlag=ctx.str("type");const nameFlag=ctx.str("name");const filterType=normalizeBffType(typeFlag)??undefined;if(nameFlag&&!filterType){throw CliErrors.validation("--name requires --type to identify the function.")}const allFunctions=await scanLocalBffFunctions(config,filterType);if(nameFlag){const matches=allFunctions.filter(fn=>fn.name===nameFlag);if(matches.length===0){
|
|
12
|
+
throw CliErrors.validation(`Local function not found: ${filterType}/${nameFlag}`)}return matches}return allFunctions}function pushFailure(cause){const remoteErrorCode=getPlatformErrorCode(cause);return{error:cause instanceof Error?cause.message:String(cause),...remoteErrorCode?{remoteErrorCode:remoteErrorCode}:{}}}function existingHookWarning(lockKey){return{code:"EXISTING_HOOK_BINDING_PRESERVED",lockKey:lockKey,message:"Dataset metadata is unavailable; the existing script and binding were verified. Update by script ID without rebinding."}}async function buildHookMaps(appCode,apiDir,localFunctions,appLock,selectedAppName){const hasHooks=localFunctions.some(fn=>fn.type==="HOOK");if(!hasHooks)return{resolutions:new Map,failures:new Map,existingHooks:new Set};const source=resolveApiModelSource(apiDir,appCode,selectedAppName);const aliasEntries=loadAliasMap(apiDir,undefined,source.filePath,source.profileName);assertUnambiguousHookAliases(aliasEntries)
|
|
13
|
+
;const aliasToDatasetCode=[...aliasEntries.map(entry=>[entry.alias,entry.datasetCode]),...trackedHookDirectoryMappings(appLock).map(entry=>[entry.alias,entry.datasetCode])];const datasets=await listDatasets(appCode);assertUnambiguousHookDirectoryMappings(aliasToDatasetCode.map(([alias,datasetCode])=>({alias:alias,datasetCode:datasetCode})));const indexes=buildHookDirectoryIndexes(datasets,aliasToDatasetCode);const directoryErrors=new Map;const resolutions=preflightPushHookDirectories(localFunctions,appLock,indexes,directoryErrors);const failures=new Map;for(const[key,error]of directoryErrors)failures.set(key,{error:error});const existingHooks=new Set;const candidates=localFunctions.filter(fn=>failures.get(fn.lockKey)?.error.startsWith("HOOK_DATASET_NOT_FOUND:")&&appLock.functions[fn.lockKey]?.remoteId&&appLock.functions[fn.lockKey]?.datasetCode);if(candidates.length>0){let statistics;try{statistics=await getBffScriptStatistics(appCode)}catch(error){const failure=pushFailure(error)
|
|
14
|
+
;for(const fn of candidates)failures.set(fn.lockKey,{...failure,error:`Cannot verify existing HOOK binding: ${failure.error}`});return{resolutions:resolutions,failures:failures,existingHooks:existingHooks}}for(const fn of candidates){const entry=appLock.functions[fn.lockKey];try{const directories=new Set(localFunctions.filter(item=>item.type==="HOOK"&&appLock.functions[item.lockKey]?.datasetCode===entry.datasetCode).map(item=>item.alias));if(directories.size>1){throw CliErrors.validation("Multiple HOOK directories reference the same missing Dataset. Resolve duplicate directories before pushing.")}const bindings=statistics.flatMap(item=>[{datasetCode:item.datasetCode,operationType:snakeToCamel(item.operationType),functionNode:"before",id:item.beforeScriptId},{datasetCode:item.datasetCode,operationType:snakeToCamel(item.operationType),functionNode:"after",id:item.afterScriptId}]).filter(item=>item.id===entry.remoteId);const remote=await getBffScriptInfo(entry.remoteId)
|
|
15
|
+
;if(remote.id!==entry.remoteId||remote.appCode!==appCode||remote.scriptType!=="HOOK"||remote.functionName!==fn.name||entry.version==null||remote.version!==entry.version||bindings.length!==1||bindings[0].datasetCode!==entry.datasetCode||bindings[0].operationType!==fn.operationType||bindings[0].functionNode!==fn.functionNode||entry.operationType!==fn.operationType||entry.functionNode!==fn.functionNode){throw CliErrors.validation("Existing HOOK identity, version or binding does not match the local lock. Pull and review before pushing.")}existingHooks.add(fn.lockKey);failures.delete(fn.lockKey)}catch(error){failures.set(fn.lockKey,pushFailure(error))}}}return{resolutions:resolutions,failures:failures,existingHooks:existingHooks}}async function uploadSingleFunction(appCode,fn,appLock,hookMaps,sourceCode){const hash=computeContentHash(sourceCode);const lockEntry=appLock.functions[fn.lockKey];if(lockEntry?.remoteId&&lockEntry.version==null){
|
|
16
|
+
throw CliErrors.validation(`${fn.lockKey}: missing remote version. Run \`push\` after \`pull\` to sync version info.`)}let descriptionToSend=extractScriptDescription(sourceCode);if(!descriptionToSend&&lockEntry?.remoteId){const remote=await getBffScriptInfo(lockEntry.remoteId);descriptionToSend=remote.description||undefined}const payload={appCode:appCode,functionName:fn.name,scriptType:fn.type,scriptContent:sourceCode};if(lockEntry?.remoteId)payload["id"]=lockEntry.remoteId;if(lockEntry?.version!=null)payload["version"]=lockEntry.version;if(descriptionToSend)payload["description"]=descriptionToSend;if(fn.type==="HOOK"){const hook=hookMaps.resolutions.get(fn.lockKey);if(!hook&&!hookMaps.existingHooks.has(fn.lockKey)||!fn.operationType||!fn.functionNode){throw CliErrors.validation(`Incomplete HOOK path: ${fn.lockKey}`)}if(hook){payload["datasetId"]=hook.dataset.id;payload["operationType"]=fn.operationType}payload["functionNode"]=fn.functionNode}const saved=await saveBffScript(payload)
|
|
17
|
+
;const remoteId=saved.id;const latestScript=saved.script??await getBffScriptInfo(remoteId);const nextEntry={hash:hash,remoteId:remoteId,version:latestScript.version};if(fn.type==="HOOK"){const hook=hookMaps.resolutions.get(fn.lockKey);if(!hook){appLock.functions[fn.lockKey]={...lockEntry,...nextEntry};return latestScript}nextEntry.alias=hook.alias??lockEntry?.alias;nextEntry.datasetCode=hook.datasetCode;nextEntry.operationType=fn.operationType;nextEntry.functionNode=fn.functionNode}appLock.functions[fn.lockKey]=nextEntry;return latestScript}const LOCK_SETTLE_RETRY_COUNT=20;const LOCK_SETTLE_DELAY_MS=100;async function waitForUploadedLockEntries(lockFilePath,appCode,lockKeys){if(lockKeys.length===0)return;for(let i=0;i<LOCK_SETTLE_RETRY_COUNT;i+=1){const latestLock=await readBffLockFile(lockFilePath);const functions=latestLock?.apps?.[appCode]?.functions??{};const allPresent=lockKeys.every(lockKey=>!!functions[lockKey]?.remoteId);if(allPresent)return;await sleep(LOCK_SETTLE_DELAY_MS)}
|
|
18
|
+
throw new Error(`Lock file not settled after push for ${lockKeys.join(", ")}.`)}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* customPage、前端子应用和 Agent 宿主依据真实契约、实际结果及任务上下文决定卡片、图表或表格。
|
|
7
7
|
* - 返回能力必须有目标实现和契约依据:数组不等于明细,月序列不意味着支持日/周或区间总值。
|
|
8
8
|
* 展示切换不授予新计算能力,不得改写范围、聚合规则、单位、精度,或将 null/缺失/失败变成零。
|
|
9
|
-
* - 未知口径须确认,不由 LLM
|
|
9
|
+
* - 未知口径须确认,不由 LLM 补齐;定义读取保持原貌,开发诊断独立检查 Schema 与示例,业务口径须结合真实执行对账。
|
|
10
10
|
* - 云端当前定义是运行态执行依据,本地 JSON 是开发辅助;扩展 JSON 字段按原值保留,不参与权限或 BFF 参数组装。
|
|
11
11
|
*/
|
|
12
12
|
export interface MetricEntry extends Record<string, unknown> {
|
|
@@ -1,2 +1,17 @@
|
|
|
1
|
+
import { type MetricDetailRecord } from '../../core/api-client.js';
|
|
1
2
|
import type { CommandDefinition } from '../../framework/types.js';
|
|
2
3
|
export declare const metricDetail: CommandDefinition;
|
|
4
|
+
export declare function savedDefinitionWarning(code: string, functionName: string, error: NonNullable<MetricDetailRecord['detailError']>): string;
|
|
5
|
+
export declare function readCloudMetric(appCode: string, code: string): Promise<{
|
|
6
|
+
metric: import("./definition.js").MetricEntry;
|
|
7
|
+
warning: string;
|
|
8
|
+
detailError: {
|
|
9
|
+
code: string;
|
|
10
|
+
message: string;
|
|
11
|
+
nextAction?: string;
|
|
12
|
+
};
|
|
13
|
+
} | {
|
|
14
|
+
metric: import("./definition.js").MetricEntry;
|
|
15
|
+
warning: undefined;
|
|
16
|
+
detailError?: undefined;
|
|
17
|
+
}>;
|
|
@@ -1,2 +1,2 @@
|
|
|
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
|
|
2
|
-
|
|
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 current=await readCloudMetric(ctx.appCode,code);if(current.detailError){console.warn(JSON.stringify({warning:current.warning,appCode:ctx.appCode,code:code,functionName:current.metric.target.functionName,detailError:current.detailError}))}return{ok:true,data:current.metric}}};export function savedDefinitionWarning(code,functionName,error){
|
|
2
|
+
return`${code} (${functionName}): Saved definition only; current consumer detail unavailable (API error code: ${error.code}). ${error.message} ${error.nextAction??""}`.trim()}export async function readCloudMetric(appCode,code){const record=await getMetricDetail(appCode,validateMetricCode(code));if(!record||record.appCode!==appCode||record.code!==code)throw CliErrors.validation("Metric record identity does not match the selected app and code.");if(record.detail===null&&record.detailError){const metric=readStoredMetric(record,appCode,code);const detailError=record.detailError;const warning=savedDefinitionWarning(code,metric.target.functionName,detailError);return{metric:metric,warning:warning,detailError:detailError}}return{metric:validateMetricDefinition(record.detail,appCode,code).metric,warning:undefined}}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { MetricEntry } from './definition.js';
|
|
2
|
+
export declare function contractWarnings(metric: MetricEntry, contract: unknown): string[];
|
|
3
|
+
export declare function declaredSchemaWarnings(subject: string, contract: unknown, sides: readonly ('inputSchema' | 'outputSchema')[]): string[];
|
|
4
|
+
export declare function reviewContract(metric: MetricEntry, contract: unknown): {
|
|
5
|
+
warnings: string[];
|
|
6
|
+
evidence: {
|
|
7
|
+
semanticReview: string;
|
|
8
|
+
description: string | undefined;
|
|
9
|
+
inputFields: string[];
|
|
10
|
+
declarations: Record<string, string>;
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
type Review = {
|
|
14
|
+
warnings: string[];
|
|
15
|
+
evidence?: ReturnType<typeof reviewContract>['evidence'];
|
|
16
|
+
};
|
|
17
|
+
export declare function activeContractReview(metric: MetricEntry, id?: string): Promise<Review>;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{Ajv2020}from"ajv/dist/2020.js";import{fullFormats}from"ajv-formats/dist/formats.js";import{isDeepStrictEqual}from"node:util";import{getMetricDetail}from"../../core/api-client.js";import{diffMetricPublication}from"./publication-diff.js";import{savedDefinitionWarning}from"./detail.js";const pointerKey=key=>key.replace(/~/g,"~0").replace(/\//g,"~1");function object(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)?value:{}}function declarations(schema,root,seen=new Set){if(!schema||typeof schema!=="object"||seen.has(schema))return[];seen.add(schema);const node=object(schema);const parts=[node];if(typeof node.$ref==="string"&&node.$ref.startsWith("#/")){let ref=root;for(const token of node.$ref.slice(2).split("/"))ref=object(ref)[token.replace(/~1/g,"/").replace(/~0/g,"~")];parts.push(...declarations(ref,root,seen))}for(const group of[node.allOf,node.anyOf,node.oneOf]){
|
|
2
|
+
if(Array.isArray(group))for(const child of group)parts.push(...declarations(child,root,seen))}return parts}function bindingWarnings(root,examples){const paths=new Set;function nodes(path){let parts=declarations(root,root);for(const key of path.split("/").filter(Boolean)){parts=parts.flatMap(node=>declarations(key==="[]"?node.items:object(node.properties)[key.replace(/~1/g,"/").replace(/~0/g,"~")],root))}return parts}const has=path=>nodes(path).some(n=>n.type!==undefined||n.enum!==undefined||n.const!==undefined);const fields=path=>nodes(path).flatMap(n=>Object.keys(object(n.properties)));const aggregates=examples.map(x=>object(object(x).aggregate));const aggregateKeys=new Set([...fields("aggregate"),...aggregates.flatMap(Object.keys)]);const hasRecord=fields("").includes("record")||examples.some(x=>Object.hasOwn(object(x),"record"));const trend=aggregateKeys.has("points");if(aggregateKeys.has("value"))paths.add("aggregate/value");if(trend){
|
|
3
|
+
for(const field of["granularity","points","points/[]/value"])paths.add("aggregate/"+field);const itemFields=fields("aggregate/points/[]");const hasMillis=itemFields.includes("startTimeMs")||itemFields.includes("endTimeMs");if(hasMillis){paths.add("aggregate/points/[]/startTimeMs");paths.add("aggregate/points/[]/endTimeMs")}if(!hasMillis||itemFields.includes("startTime")||itemFields.includes("endTime")){paths.add("aggregate/points/[]/startTime");paths.add("aggregate/points/[]/endTime")}}const warnings=[];if(!aggregateKeys.has("value")&&!trend&&!hasRecord)warnings.push("/outputSchema: No standard BI binding is declared.");if(hasRecord){for(const field of["tableData","paging/currentPage","paging/pageSize","paging/totalCount"])paths.add("record/"+field);const columns=fields("record/tableData/[]");for(const example of examples){const rows=object(object(example).record).tableData;if(Array.isArray(rows))for(const row of rows)columns.push(...Object.keys(object(row)))}
|
|
4
|
+
if(!columns.length)warnings.push("/outputSchema/record/tableData: declare the table columns.");for(const column of columns)paths.add("record/tableData/[]/"+pointerKey(column))}for(const path of paths)if(!has(path))warnings.push("/outputSchema: missing a typed BI binding for "+path+".");return warnings}export function contractWarnings(metric,contract){const warnings=declaredSchemaWarnings(metric.code+" ("+metric.target.functionName+")",contract,["inputSchema","outputSchema"]);if(!metric.description)warnings.push(metric.code+" ("+metric.target.functionName+") /description: metric calculation and scope cannot be checked without a definition.");return warnings}export function declaredSchemaWarnings(subject,contract,sides){const warnings=[];for(const side of sides){const schema=object(object(contract)[side]);const path="/"+side;if(schema.type!=="object")warnings.push(path+"/type: expected object.");const examples=schema.examples
|
|
5
|
+
;if(side==="outputSchema"&&(!Array.isArray(examples)||!examples.length))warnings.push(path+"/examples: expected at least one complete output example.");try{const validate=new Ajv2020({strict:false,allErrors:true,ownProperties:true,logger:false,formats:{date:fullFormats.date,time:fullFormats.time,"date-time":fullFormats["date-time"]}}).compile(schema);if("$async"in validate)throw new Error("Asynchronous schemas are unsupported.");if(Array.isArray(examples)){examples.forEach((example,index)=>{if(!validate(example))for(const error of validate.errors??[]){warnings.push(path+"/examples/"+index+error.instancePath+": "+error.message+".")}})}if(side==="outputSchema")warnings.push(...bindingWarnings(schema,Array.isArray(examples)?examples:[]))}catch(error){warnings.push(path+": could not check schema: "+(error instanceof Error?error.message:String(error)))}}return warnings.map(warning=>subject+" "+warning)}export function reviewContract(metric,contract){const descriptions={}
|
|
6
|
+
;function collect(schema,path){const node=object(schema);if(typeof node.description==="string"&&node.description.trim())descriptions[path]=node.description;for(const key of["properties","$defs"]){for(const[name,child]of Object.entries(object(node[key]))){collect(child,path+"/"+key+"/"+pointerKey(name))}}if(node.items)collect(node.items,path+"/items");for(const key of["allOf","anyOf","oneOf"]){const children=node[key];if(Array.isArray(children))children.forEach((child,i)=>collect(child,path+"/"+key+"/"+i))}}for(const side of["inputSchema","outputSchema"])collect(object(contract)[side],"/"+side);const warnings=contractWarnings(metric,contract);if(!Object.keys(descriptions).length)warnings.push(metric.code+" ("+metric.target.functionName+"): ENDPOINT descriptions are missing; the business definition cannot be compared.");const input=object(object(contract).inputSchema);const inputFields=[...new Set(declarations(input,input).flatMap(node=>Object.keys(object(node.properties))))].sort()
|
|
7
|
+
;const semanticReview=metric.description&&Object.keys(descriptions).length?"required":"insufficient-evidence";return{warnings:warnings,evidence:{semanticReview:semanticReview,description:metric.description,inputFields:inputFields,declarations:descriptions}}}export async function activeContractReview(metric,id){const prefix=metric.code+" ("+metric.target.functionName+"): ";try{const record=await getMetricDetail(metric.target.appCode,metric.code);const sameRecord=record?.appCode===metric.target.appCode&&record.code===metric.code&&(!id||record.id===id);if(sameRecord&&record.detail===null&&record.detailError&&isDeepStrictEqual(record.definition.target,metric.target)){return{warnings:[savedDefinitionWarning(metric.code,metric.target.functionName,record.detailError)]}}if(!sameRecord||record.detail?.code!==metric.code||!isDeepStrictEqual(record.detail.target,metric.target)||!record.detail.contract){return{warnings:[prefix+"Active ENDPOINT contract could not be verified for this binding."]}}
|
|
8
|
+
const review=reviewContract(metric,record.detail.contract);if(metric.contract){for(const change of diffMetricPublication(object(metric.contract),object(record.detail.contract))){review.warnings.push(prefix+change.path+": "+change.operation+" in the active declaration compared with the local contract.")}}return review}catch(error){return{warnings:[prefix+"Active contract check incomplete: "+(error instanceof Error?error.message:String(error))]}}}
|
|
@@ -1,2 +1,2 @@
|
|
|
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
|
|
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
|
+
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 by keyword or bound BFF ENDPOINT",flags:[APPCODE_FLAG_OPTIONAL,{name:"keyword",type:"string",description:"Literal substring of code, label, synonyms, description or bound BFF name"},{name:"function-name",type:"string",description:"Exact, case-sensitive registered name of the bound BFF ENDPOINT"}],async execute(ctx){const keyword=ctx.str("keyword").trim();const functionName=ctx.str("function-name").trim();const records=await listMetrics(ctx.appCode,{...keyword&&{keyword:keyword},...functionName&&{functionName:functionName}});const codes=new Set;const summaries=records.map(record=>{
|
|
2
|
+
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);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,5 +1,6 @@
|
|
|
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.")
|
|
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:{
|
|
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.");
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import{resolve}from"node:path";import{isDeepStrictEqual}from"node:util";import{isPlatformTransportFailure,createMetric,getMetricByCode,getMetricById,listMetrics,updateMetric}from"../../core/api-client.js";import{CliErrors}from"../../errors.js";import{METRIC_ENDPOINT_PREFIX,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";import{activeContractReview}from"./diagnostics.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.")
|
|
2
|
+
;const before=id?await getMetricById(ctx.appCode,id):await getMetricByCode(ctx.appCode,code);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.")}}const bindingToCheck=previous?.target.functionName===metric.target.functionName?undefined:metric.target.functionName;if(bindingToCheck&&!bindingToCheck.startsWith(METRIC_ENDPOINT_PREFIX)){throw CliErrors.validation(`New metric bindings require an ENDPOINT name starting with lowercase "${METRIC_ENDPOINT_PREFIX}". Received: ${bindingToCheck}.`)}return{before:before,metric:metric,bindingToCheck:bindingToCheck,changes:diffMetricPublication(previous,{code:code,...definition}),input:{
|
|
3
|
+
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}async function resultData(before,after,changes,dryRun,bindingToCheck){const warnings=["Updates take effect immediately. Concurrent publishing has no version-conflict protection."];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.");if(bindingToCheck){try{const references=await listMetrics(after.appCode,{functionName:bindingToCheck});const selfId="id"in after?after.id:before?.id;const others=references.filter(item=>item.id!==selfId).map(item=>item.code).sort();if(others.length)warnings.push(`ENDPOINT ${bindingToCheck} is also bound to: ${others.join(", ")}.`)}catch(error){
|
|
4
|
+
warnings.push(`ENDPOINT ${bindingToCheck} binding lookup incomplete. ${error instanceof Error?error.message:"Could not read all references."}`)}}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){const{before:before,input:input,changes:changes,bindingToCheck:bindingToCheck}=await prepare(ctx);return{method:"POST",url:`/api/studio/metric/v1/${before?"update":"create"}`,
|
|
5
|
+
data:await resultData(before,input,changes,true,bindingToCheck)}},async execute(ctx){const{before:before,input:input,changes:changes,metric:metric,bindingToCheck:bindingToCheck}=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)){if(writeError)throw failure(writeError)
|
|
6
|
+
;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=await resultData(before,after,changes,false,bindingToCheck);if(writeError)data.warnings.push("Write response was unavailable; readback confirms the requested current state, not attribution to this request.");const review=await activeContractReview(metric,after.id);data.warnings.push(...review.warnings);return{ok:true,data:{...data,...review.evidence&&{evidence:review.evidence}},message:`Published metric ${input.code}`}}};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{readFile}from"node:fs/promises";import{basename}from"node:path";import{METRIC_ENDPOINT_PREFIX}from"./shared.js";import{listMetrics}from"../../core/api-client.js";const schemaSides=["inputSchema","outputSchema"];async function candidateWarnings(source,endpoint){const doc=/\/\*\*((?:[^*]|\*(?!\/))*)\*\/\s*export\s+default\s+(?:async\s+)?function\s+[\w$]+\s*\(/.exec(source)?.[1]??"";const lines=doc.split(/\r?\n/).map(line=>line.replace(/^\s*\*?\s*/,""));const body=lines.join("\n");const tags=[...body.matchAll(/^@(\w+)\b/gm)];const contract={};const problems=[];const declared=new Set;for(const[i,tag]of tags.entries()){const side=schemaSides.find(name=>name===tag[1]);if(!side)continue;if(declared.has(side))problems.push("Duplicate @"+side+" declaration.");declared.add(side);try{contract[side]=JSON.parse(body.slice(tag.index+tag[0].length,tags[i+1]?.index).trim())}catch{problems.push("@"+side+" must contain a JSON object.")}}
|
|
2
|
+
if(!declared.has("outputSchema")&&(!/^@returns?\s*\{/m.test(body)||/^@returns?\s*\{\s*(?:Object|Promise\s*<\s*Object\s*>)\s*\}/im.test(body))){problems.push("No output fields are declared in the return type.")}if(!declared.has("outputSchema")){problems.push("/outputSchema/examples: local preflight cannot verify a complete success example from the return type. Provide it in @outputSchema.examples.")}const sides=schemaSides.filter(side=>Object.hasOwn(contract,side));const{declaredSchemaWarnings:declaredSchemaWarnings}=await(import("./diagnostics.js"));return[...problems.map(problem=>endpoint+": "+problem),...declaredSchemaWarnings(endpoint,contract,sides)]}export async function metricPushPreflight(appCode,fn,source){if(fn.type!=="ENDPOINT"||!basename(fn.filePath).startsWith(METRIC_ENDPOINT_PREFIX))return[];try{const bindings=await listMetrics(appCode,{functionName:fn.name});if(!bindings.length)return[]}catch(error){const reason=error instanceof Error?error.message:String(error)
|
|
3
|
+
;return[fn.name+": Metric binding lookup incomplete: "+reason]}try{return await candidateWarnings(source??await readFile(fn.filePath,"utf8"),fn.name)}catch{return[fn.name+": Candidate source preflight could not be completed."]}}
|
|
@@ -1,2 +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}})}export function requireMetricId(record){
|
|
2
|
-
throw CliErrors.apiError("Invalid metric record ID; expected a positive decimal string.")}return record.id}
|
|
1
|
+
import{readFile}from"node:fs/promises";import{CliError,CliErrors}from"../../errors.js";export const METRIC_ENDPOINT_PREFIX="metric";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){
|
|
2
|
+
if(typeof record.id!=="string"||!/^[1-9][0-9]*$/.test(record.id)){throw CliErrors.apiError("Invalid metric record ID; expected a positive decimal string.")}return record.id}
|
|
@@ -1 +1,2 @@
|
|
|
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
|
|
1
|
+
import{resolve}from"node:path";import{metricCommand}from"./shared.js";import{readMetricJson}from"./contract.js";import{validateMetricPublication}from"./definition.js";import{APPCODE_FLAG_OPTIONAL}from"../../commands/common/flags.js";import{activeContractReview,reviewContract}from"./diagnostics.js";import{readCloudMetric}from"./detail.js";import{CliErrors}from"../../errors.js";export const metricValidate={...metricCommand,command:"validate",auth:"optional",description:"Validate a published metric by code or review a candidate definition file",flags:[APPCODE_FLAG_OPTIONAL,{name:"code",type:"string",description:"Exact code of a published metric in the selected app"},{name:"file",type:"string",description:"Candidate metric definition JSON file"}],async execute(ctx){const file=ctx.str("file");const code=ctx.str("code");if(Boolean(code)===Boolean(file))throw CliErrors.validation("Supply exactly one of --code or --file.");const appCode=ctx.str("appcode")||undefined;if(code){
|
|
2
|
+
const selectedApp=appCode||ctx.appCode;if(!selectedApp)throw CliErrors.validation("Select an application with --appcode to validate a published metric.");const{metric:metric,warning:warning,detailError:detailError}=await readCloudMetric(selectedApp,code);const review=warning?{warnings:[warning],detailError:detailError}:reviewContract(metric,metric.contract);return{ok:true,data:{code:code,appCode:selectedApp,verification:"cloud-definition",...review}}}const{metric:metric}=validateMetricPublication(await readMetricJson(resolve(file)),appCode);if(!appCode&&!metric.contract){return{ok:true,data:{valid:true,verification:"definition-structure",warnings:[metric.code+" ("+metric.target.functionName+"): no local contract. Use --appcode to check the active binding."]}}}const review=appCode?await activeContractReview(metric):reviewContract(metric,metric.contract);return{ok:true,data:{valid:true,verification:"definition-structure",...review}}}};
|
package/lib/core/api-client.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ export declare function clearActiveCookie(): void;
|
|
|
7
7
|
export declare function isPlatformTransportFailure(error: unknown): boolean;
|
|
8
8
|
export declare function getPlatformErrorCode(error: unknown): string | undefined;
|
|
9
9
|
export declare function getPlatformHttpStatus(error: unknown): number | undefined;
|
|
10
|
+
export declare function getPlatformErrorData(error: unknown): unknown;
|
|
10
11
|
export interface DevelopmentFileUploadResponse {
|
|
11
12
|
fileName?: string | null;
|
|
12
13
|
filePath?: string | null;
|
|
@@ -263,6 +264,8 @@ export interface BffScript {
|
|
|
263
264
|
scriptContent?: string;
|
|
264
265
|
version?: number;
|
|
265
266
|
dependencyRefs?: string;
|
|
267
|
+
/** Studio sets this on a saved version when static dependency inference failed. */
|
|
268
|
+
dependenciesIncomplete?: boolean;
|
|
266
269
|
enableTransaction?: boolean;
|
|
267
270
|
datasetId?: number | null;
|
|
268
271
|
operationType?: string | null;
|
|
@@ -1322,8 +1325,9 @@ export interface MetricListFilters {
|
|
|
1322
1325
|
code?: string;
|
|
1323
1326
|
keyword?: string;
|
|
1324
1327
|
categoryPath?: string[];
|
|
1328
|
+
functionName?: string;
|
|
1325
1329
|
}
|
|
1326
|
-
/**
|
|
1330
|
+
/** Read every page before exposing a complete metric catalog. */
|
|
1327
1331
|
export declare function listMetrics(appCode: string, filters?: MetricListFilters): Promise<MetricRecord[]>;
|
|
1328
1332
|
/** Exact saved-state lookup does not depend on target/contract availability. */
|
|
1329
1333
|
export declare function getMetricByCode(appCode: string, code: string): Promise<MetricRecord | null>;
|