@youzan-cloud/zan-saas-cli 0.1.0-beta.4 → 0.1.0-beta.7

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.
@@ -101,12 +101,13 @@ function commandContract(path, command) {
101
101
  if (['schema', 'doctor', 'skills.list', 'skills.read'].includes(path)) {
102
102
  return { kind: 'system', risk: 'read', availability: 'available' };
103
103
  }
104
- if (['auth.status', 'auth.whoami', 'shop.list', 'shop.current'].includes(path)) {
104
+ if (['auth.status', 'auth.whoami', 'shop.list', 'shop.current', 'shop.resolve'].includes(path)) {
105
105
  return { kind: 'system', risk: 'read', availability: 'available' };
106
106
  }
107
107
  // Login and logout change the local credential and the server-side session; shop use and clear
108
108
  // change the saved context.
109
- if (['install', 'auth.login', 'auth.logout', 'shop.use', 'shop.clear'].includes(path)) {
109
+ if (['install', 'auth.login', 'auth.logout', 'shop.use', 'shop.clear',
110
+ 'shop.session.init', 'shop.unit.use'].includes(path)) {
110
111
  return { kind: 'system', risk: 'low', availability: 'available' };
111
112
  }
112
113
  if (path === 'api') return { kind: 'raw-api', risk: 'unknown', availability: 'available' };
@@ -22,9 +22,16 @@ const { commandSchema } = require('../execution/command-schema');
22
22
  const { commandContract, commandPath } = require('./command-paths');
23
23
  const { configureContextHelp, isContextHelp } = require('./context-help');
24
24
  const { configureParserPolicy } = require('./parser-policy');
25
+ const { bindApiContext, runWithApiSession } = require('../transport/api');
25
26
 
26
- function createProgram({ catalog = openRegistry(), root = nativeRoot, rootSkills = skillsRoot,
27
- eagerDomains = false, context = contextInput(process.env) } = {}) {
27
+ function createProgram(settings = {}) {
28
+ const { catalog = openRegistry(), root = nativeRoot, rootSkills = skillsRoot,
29
+ eagerDomains = false } = settings;
30
+ const injected = settings.context !== undefined;
31
+ let context;
32
+ let contextError;
33
+ try { context = injected ? settings.context : contextInput(process.env); }
34
+ catch (error) { contextError = error; context = {}; }
28
35
  const { domains, skills, businessCommandCount } = catalog.manifest;
29
36
  const domainNames = new Set(domains.map(domain => domain.name));
30
37
  const loadedDomains = new Set();
@@ -62,7 +69,7 @@ function createProgram({ catalog = openRegistry(), root = nativeRoot, rootSkills
62
69
  program.addCommand(createDoctorCommand(businessCommandCount));
63
70
  program.addCommand(createApiCommand());
64
71
  program.addCommand(createAuthCommand());
65
- program.addCommand(createShopCommand());
72
+ program.addCommand(createShopCommand(undefined, { context: injected ? context : undefined }));
66
73
  program.addCommand(createSkillsCommand(skills, rootSkills));
67
74
  program.addCommand(createInstallCommand());
68
75
  function configureSystemErrors(command) {
@@ -83,6 +90,11 @@ function createProgram({ catalog = openRegistry(), root = nativeRoot, rootSkills
83
90
  program.hook('preAction', (_parent, command) => {
84
91
  if (isContextHelp(command)) return;
85
92
  const contract = commandContract(commandPath(command), command);
93
+ if ((['atomic', 'task'].includes(contract.kind) && !command.opts().dryRun) ||
94
+ contract.kind === 'raw-api') {
95
+ if (contextError) throw contextError;
96
+ bindApiContext(contextState.context);
97
+ }
86
98
  if (['atomic', 'task'].includes(contract.kind)) {
87
99
  const details = commandSchema(command)?.error?.properties?.details;
88
100
  const stages = details?.properties?.stage?.enum;
@@ -112,7 +124,7 @@ function createProgram({ catalog = openRegistry(), root = nativeRoot, rootSkills
112
124
  快速开始:
113
125
  1. 登录:zan-saas auth login,按提示在浏览器完成授权
114
126
  2. 查看当前店铺:zan-saas shop current;已有有效上下文时沿用
115
- 3. 需要选店时:zan-saas shop list,按用户指定的店名或选择执行 zan-saas shop use <kdtId>
127
+ 3. 宿主会话先 shop session init;账号选店用 shop use,连锁内切换用 shop unit use,临时查询用 shop resolve
116
128
  4. 阅读使用指引:zan-saas skills read zan-saas
117
129
 
118
130
  查询命令:
@@ -128,6 +140,10 @@ function createProgram({ catalog = openRegistry(), root = nativeRoot, rootSkills
128
140
  if (eagerDomains) {
129
141
  for (const domain of domains) loadDomain(domain.name);
130
142
  }
143
+ const parseAsync = program.parseAsync;
144
+ program.parseAsync = function (...args) {
145
+ return runWithApiSession(() => parseAsync.apply(this, args));
146
+ };
131
147
  return program;
132
148
  }
133
149
 
@@ -9,7 +9,7 @@
9
9
  "availability": "available",
10
10
  "at": "all",
11
11
  "module": "access/role/list/command.js",
12
- "fingerprint": "1f1a25bdb5f2252635920dd6f154e7692cefbe5c37bf5c164aff4c0c73a23313"
12
+ "fingerprint": "55180dff4d111eee0ae67c4987b71a5ebe0557061228774a5cc9f0b88880d8aa"
13
13
  },
14
14
  {
15
15
  "path": "access.staff-perms.get",
@@ -45,7 +45,7 @@
45
45
  "availability": "available",
46
46
  "at": "all",
47
47
  "module": "customer/customer-tag/list/command.js",
48
- "fingerprint": "60e6f754b729a536d83aa3c01a5f0069a2bdb3d927129cdc4497e6f04cff2b47"
48
+ "fingerprint": "9847ca5a4011dc084d074f434c0cd4ad24633e12fe6f79395a1dfb173927bd0b"
49
49
  },
50
50
  {
51
51
  "path": "customer.segment.list",
@@ -3,7 +3,7 @@
3
3
  const { withTargetShopDefault } = require('../../../../../execution/target-shop-default');
4
4
 
5
5
  const { Command } = require('commander');
6
- const { requestApi, ApiConfigurationError } = require('../../../../../transport/api');
6
+ const { requestApi, snapshotApiEnvironment, ApiConfigurationError } = require('../../../../../transport/api');
7
7
  const { validateCommandValue } = require('../../../../../execution/command-schema');
8
8
  const schema = require('./schema.json');
9
9
 
@@ -47,7 +47,7 @@ async function listCustomerTags(options, context) {
47
47
  }
48
48
  let response;
49
49
  try {
50
- response = await requestApi(request);
50
+ response = await requestApi(request, await snapshotApiEnvironment(undefined, input.kdtId));
51
51
  } catch (error) {
52
52
  if (error instanceof ApiConfigurationError) throw failure('configuration', 'configuration');
53
53
  throw failure('transport', 'request', 'unknown');
@@ -36,7 +36,7 @@
36
36
  "availability": "available",
37
37
  "at": "all",
38
38
  "module": "member/level/get/command.js",
39
- "fingerprint": "75de5b4aeab1b821d50cbb285011f9dfe06fbc94cecb0d74c98768ce8d74ac0a"
39
+ "fingerprint": "23c8774db6b4525aa8fc978babee0b64da63498f21a0e261f06fa63c7ffaa78d"
40
40
  },
41
41
  {
42
42
  "path": "member.level.list",
@@ -9,7 +9,7 @@
9
9
  "availability": "available",
10
10
  "at": "shop",
11
11
  "module": "org/staff/get/command.js",
12
- "fingerprint": "0e6c6fd91988b916f4d5690677c712059ec65f7d6ce003eed7d7192ce61f6d96"
12
+ "fingerprint": "e73deac7efdda9b214eca98fea4e1d71d44d5a82e8b6cf71126f337c5b5b0a33"
13
13
  },
14
14
  {
15
15
  "path": "org.staff-role.get",
@@ -18,7 +18,7 @@
18
18
  "availability": "available",
19
19
  "at": "shop",
20
20
  "module": "org/staff-role/get/command.js",
21
- "fingerprint": "cfa719f5122449c0a57e5db59bfd760d17d717f95088c9d886586b53304a7041"
21
+ "fingerprint": "b5c0e152bc037639379c99eac78a26ed716f5e7fbddd5bc0e485011a4d05b22b"
22
22
  },
23
23
  {
24
24
  "path": "org.unit.get",
@@ -27,7 +27,7 @@
27
27
  "availability": "available",
28
28
  "at": "all",
29
29
  "module": "org/unit/get/command.js",
30
- "fingerprint": "d11775de4f1c6d7500310c3f8b373bee7e829ab5afe586ae617037571b4d0597"
30
+ "fingerprint": "4e4a8b3143a619cc50c80afd33bef1d42bd68896abc3bc7f250be26911be3a68"
31
31
  },
32
32
  {
33
33
  "path": "org.unit.list",
@@ -36,7 +36,7 @@
36
36
  "availability": "available",
37
37
  "at": "hq",
38
38
  "module": "org/unit/list/command.js",
39
- "fingerprint": "6bee5cdcffb1893319280f50f9b49e752d16dbadcae5413bce3bbfcf476a9fc6"
39
+ "fingerprint": "6b1636404484b8d0823d04fe1b3ee4d8e28afc91b6e1a6489264f84fe5f137bf"
40
40
  }
41
41
  ]
42
42
  }
@@ -32,7 +32,7 @@ function createApiCommand() {
32
32
  .option('--yes', '确认本次请求的未知副作用并发送')
33
33
  .addHelpText('after', `
34
34
  目标可以是已登记或未登记的 API,不接收任意 URL。
35
- 默认先使用 auth login 保存的个人凭证;受控环境配置 ZAN_SAAS_USER_ACCESS_TOKEN 时使用环境凭证。
35
+ 默认优先使用 auth login 保存的个人凭证;无个人记录时使用环境token。明确使用环境身份配置 ZAN_SAAS_AUTH_SOURCE=env。
36
36
  发送须 --yes,仅确认未知副作用,不证明服务端授权。
37
37
  退出0、HTTP 2xx 和 sent=true 只说明收到响应,不证明业务成功、异步完成或写入完成。
38
38
  body 是脱敏后的原始文本;即使 HTTP 200 正文含 success=false,也不按业务失败改变退出码。
@@ -19,23 +19,33 @@ function localTime(iso) {
19
19
  }
20
20
 
21
21
  const cloudAccountHint = '有赞云账号开通未确认,不影响本次个人登录。请先核对账号接口状态。';
22
+ function credentialLine(value) {
23
+ if (value.credentialSource === 'login') {
24
+ return `默认使用个人登录凭证${value.environmentTokenIgnored ? ',已忽略环境 token' : ''}。`;
25
+ }
26
+ if (value.credentialSource === 'env') return '本次配置使用环境 token;个人登录状态与环境凭证有效性分别判断。';
27
+ return value.credentialSource === 'missing' ? '当前没有选中的请求凭证。' : '';
28
+ }
22
29
 
23
30
  const text = {
24
31
  login: value => {
25
32
  const lines = [value.refreshExpiresAt
26
33
  ? `登录成功,凭证有效期至 ${localTime(value.refreshExpiresAt)}。` : '登录成功。'];
27
34
  if (value.cloudAccount?.ensured === false) lines.push(cloudAccountHint);
35
+ if (credentialLine(value)) lines.push(credentialLine(value));
28
36
  lines.push(value.shopId ? `当前店铺上下文:kdtId ${value.shopId}。` : '当前没有有效的店铺上下文。',
29
37
  shopSelectionHint);
30
38
  return lines.join('\n');
31
39
  },
32
40
  status: value => {
33
- if (!value.loggedIn) return `未登录(${value.server})。执行 zan-saas auth login 登录。`;
41
+ if (!value.loggedIn) return `未登录(${value.server})。执行 zan-saas auth login 登录。` +
42
+ (credentialLine(value) ? `\n${credentialLine(value)}` : '');
34
43
  const lines = [`已登录(${value.server})`];
35
44
  if (value.loginAt) lines.push(`登录时间:${localTime(value.loginAt)}`);
36
45
  if (value.refreshExpiresAt) lines.push(`有效期至:${localTime(value.refreshExpiresAt)}`);
37
46
  if (value.shopId) lines.push(`当前店铺:${value.shopId}`);
38
47
  else lines.push('当前没有有效的店铺上下文。');
48
+ if (credentialLine(value)) lines.push(credentialLine(value));
39
49
  lines.push(shopSelectionHint);
40
50
  return lines.join('\n');
41
51
  },
@@ -83,7 +93,8 @@ function createAuthCommand(impl = defaults) {
83
93
  --no-browser 只跳过自动打开浏览器,仍等待授权回调并保存个人凭证,默认超时5分钟。
84
94
  人机交接:Agent 启动命令并把输出的登录地址交给用户;用户在浏览器确认后,Agent 等待本命令回调,再执行 zan-saas auth status 确认。用户取消或超时后重新执行本命令。
85
95
  登录成功后执行 zan-saas shop current 查看当前店铺。
86
- 首次选店或需要切店时,先执行 zan-saas shop list,由用户选定 kdtId,再执行 zan-saas shop use <kdtId>。
96
+ 宿主会话首次使用执行 shop session init,恢复时加 --resume;账号选店、连锁组织切换及本次临时查询按共享指引分别处理。
97
+ 默认优先使用已保存的个人凭证;仅受控调用明确配置 ZAN_SAAS_AUTH_SOURCE=env 时使用环境 token。
87
98
  执行 zan-saas shop current 确认实际生效的店铺,再开始业务查询;切店无需重新登录。
88
99
  登录后尝试开通有赞云账号,未确认开通时不影响本次个人登录,应核对账号接口状态。
89
100
  浏览器授权完成后仍须成功换取并保存凭证;本命令失败时停止,不进入选店或业务查询。
@@ -2,6 +2,7 @@
2
2
 
3
3
  const { attachCommandSchema } = require('../../execution/command-schema');
4
4
  const { parserErrorModel } = require('../../execution/parser-error');
5
+ const shopModels = require('./shop-contracts');
5
6
 
6
7
  function object(properties, required = Object.keys(properties)) {
7
8
  return { type: 'object', additionalProperties: false, required, properties };
@@ -83,9 +84,11 @@ const skill = object({
83
84
  const serverField = { type: 'string', description: '授权服务地址的 origin,默认生产环境,ZAN_SAAS_OAUTH_BASE_URL 可覆盖;凭证按它分开保存。' };
84
85
  const time = { type: ['string', 'null'], description: 'ISO 8601 时间,服务端未返回有效期时为 null。' };
85
86
  const credentialStatus = object({
86
- loggedIn: { type: 'boolean', description: '本机保存个人凭证且已知刷新有效期未到期;未知有效期时保留已有登录记录。不表示环境覆盖凭证或服务端权限有效。' },
87
+ loggedIn: { type: 'boolean', description: '本机个人登录未标记需要重新登录,且已知刷新有效期未到期;未知有效期时保留已有记录。不表示环境token或服务端权限有效。' },
87
88
  server: serverField,
88
- clientId: text, tool: text, loginAt: time, accessExpiresAt: time, refreshExpiresAt: time
89
+ clientId: text, tool: text, loginAt: time, accessExpiresAt: time, refreshExpiresAt: time,
90
+ credentialSource: { enum: ['login', 'env', 'missing'], description: '按当前配置选中的凭证来源:个人登录、环境token或缺失。离线状态不证明服务端有效。' },
91
+ environmentTokenIgnored: { type: 'boolean', description: '已选个人登录且同时存在环境token时为true;环境token不会覆盖该登录。' }
89
92
  }, ['loggedIn', 'server']);
90
93
  const shopIdField = {
91
94
  type: ['string', 'null'], description: '业务命令当前使用的店铺 ID;没有有效上下文时为 null。'
@@ -108,7 +111,7 @@ const savedShop = object({
108
111
  context: { $ref: '#/definitions/context' }, shopName: { type: ['string', 'null'] }
109
112
  });
110
113
  const accountNote = '调用账号接口网关,不需要店铺;默认生产环境,ZAN_SAAS_ACCOUNT_API_BASE_URL 可覆盖,token 规则与业务命令相同。';
111
- const contextNote = '上下文优先级:环境变量 ZAN_SAAS_CONTEXT(即使无效)高于 shop use 保存的店铺;按授权服务地址分开保存。';
114
+ const contextNote = '上下文优先级:显式程序注入、ZAN_SAAS_CONTEXT、宿主会话保存位置;无会话ID时使用本机共享选择。无效显式输入不回退。';
112
115
 
113
116
  const contracts = {
114
117
  install: {
@@ -214,7 +217,7 @@ const contracts = {
214
217
  'token 写入 ~/.zan-saas/credentials.json(权限 0600),按授权服务地址分开保存;输出不含 token。',
215
218
  '用户取消或超时(5 分钟)时失败退出,不自动重试。',
216
219
  '登录后用短超时尝试开通有赞云账号,未确认时只记录 ensured: false,不因此要求重新登录。',
217
- '登录成功后用 shop current 查看当前店铺;首次选店或切换时用 shop list 查候选,按用户选择执行 shop use <kdtId>,再用 shop current 核对实际生效的上下文。',
220
+ '登录成功后按宿主生命周期初始化或恢复会话,再用 shop current 查看实际位置。账号选店、连锁内切换和临时目标分别读取 shop use、shop unit use、shop resolve 契约。',
218
221
  '浏览器授权完成不代表本命令成功;换取凭证失败时未保存新凭证,停止后续选店和业务请求,按错误核查版本、配置及授权服务路由。'
219
222
  ]
220
223
  },
@@ -232,8 +235,9 @@ const contracts = {
232
235
  server: serverField,
233
236
  localCredential: { enum: ['deleted', 'delete_failed'],
234
237
  description: 'deleted 表示当前个人凭证已在本机清除或已不存在;delete_failed 表示本地清理未成功。' },
235
- remoteRevocation: { enum: ['revoked', 'failed', 'unknown'],
236
- description: 'revoked 已取得撤销成功响应;failed 撤销接口返回失败,不推断会话仍有效;unknown 请求或响应未能确认。' },
238
+ remoteRevocation: { enum: ['revoked', 'failed', 'unknown', 'not_attempted'],
239
+ description: 'revoked 已确认撤销;failed 接口拒绝;unknown 无法确认结果;not_attempted 表示没有个人凭证可撤销。' },
240
+ localContext: { enum: ['delete_failed'], description: '选店记录清理失败时出现;凭证清理与远端撤销仍已分别尝试。' },
237
241
  httpStatus: { type: 'integer', minimum: 100, maximum: 599,
238
242
  description: '仅取得撤销接口失败 HTTP 响应时出现,不回显响应正文。' }
239
243
  }, ['command', 'server', 'localCredential', 'remoteRevocation'])
@@ -295,17 +299,17 @@ const contracts = {
295
299
  ]
296
300
  },
297
301
  'shop.use': {
298
- input: object({ kdtId: id }),
299
- output: object({
302
+ input: object({ kdtId: id, sessionOnly: { type: 'boolean', description: '只更新本会话,不更新最近位置;需要会话ID。' } }, ['kdtId']),
303
+ output: { oneOf: [object({
300
304
  context: { $ref: '#/definitions/context' }, shopName: { type: ['string', 'null'] },
301
305
  overriddenByEnv: { type: 'boolean', description: '为 true 时 ZAN_SAAS_CONTEXT 已设置,业务命令仍以它为准。' }
302
- }),
306
+ }), shopModels.chosenOutput('use_root')] },
303
307
  definitions: { context },
304
308
  notes: [
305
309
  accountNote,
306
310
  '先查询当前用户,再在其店铺列表中确认该店铺,只接受总部或单店;hq 与 shopId 都取该店铺 ID。',
307
- '当前用户在该店铺的员工账号已停用时拒绝;员工状态查询失败不阻止选择。',
308
- '上下文写入 ~/.zan-saas/context.json(权限 0600),不含凭证;本地上下文不是权限证明,服务端仍校验。',
311
+ '当前用户在该店铺的员工账号已停用时拒绝。共享模式员工状态查询失败保留旧兼容行为;会话模式要求核实成功,失败不保存选择。',
312
+ '无会话ID时写入 ~/.zan-saas/context.json;会话模式独立保存并默认更新供新会话继承的位置。上下文不含凭证,不证明权限。',
309
313
  '首次选择与切换店铺均使用本命令,无需重新登录;保存后用 shop current 确认实际店铺,overriddenByEnv 为 true 时不能声称当前上下文已切换。',
310
314
  contextNote
311
315
  ]
@@ -313,19 +317,23 @@ const contracts = {
313
317
  'shop.current': {
314
318
  input: empty,
315
319
  output: object({
316
- source: { enum: ['env', 'saved', 'missing'] },
320
+ source: { enum: ['env', 'saved', 'missing', 'program'] },
317
321
  status: { enum: ['ready', 'invalid', 'missing'] },
318
322
  context: nullableContext,
319
323
  saved: { anyOf: [savedShop, { type: 'null' }] },
320
- requestShopId: { type: ['string', 'null'], description: '环境变量 ZAN_SAAS_KDT_ID 的有效值;未设置或无效时为 null。不代表所有命令的最终请求店铺。' }
321
- }),
324
+ requestShopId: { type: ['string', 'null'], description: '环境变量 ZAN_SAAS_KDT_ID 的有效值;未设置或无效时为 null。不代表所有命令的最终请求店铺。' },
325
+ binding: shopModels.binding,
326
+ selection: { anyOf: [shopModels.selection, { type: 'null' }] }
327
+ }, ['source', 'status', 'context', 'saved', 'requestShopId']),
322
328
  definitions: { context },
323
329
  notes: ['只读本地文件和环境变量,不联网。requestShopId 是环境变量值;部分命令按其目标店铺设置请求头,具体以命令契约为准。', contextNote]
324
330
  },
325
331
  'shop.clear': {
326
- input: empty,
327
- output: object({ cleared: { type: 'boolean', description: '本地有保存的店铺并已删除时为 true。' }, server: serverField }),
328
- notes: ['只删除当前授权服务地址下保存的店铺,不联网,不影响 ZAN_SAAS_CONTEXT。']
332
+ input: object({ recent: { type: 'boolean', description: '同时清除该账号环境的最近位置;仅会话模式支持。' } }, []),
333
+ output: object({ cleared: { type: 'boolean', description: '已清除选中的店铺;重复清除为false。' }, server: serverField,
334
+ binding: shopModels.binding, currentChanged: { type: 'boolean' }, recentChanged: { type: 'boolean' } },
335
+ ['cleared', 'server']),
336
+ notes: ['会话模式保留cleared记录,避免重新继承;默认不影响其他会话或最近位置。原文件内改写,不删除或替换上下文文件。']
329
337
  },
330
338
  'skills.list': {
331
339
  input: empty,
@@ -356,7 +364,7 @@ const contracts = {
356
364
  }),
357
365
  notes: [
358
366
  '按明确的 API 名和版本发送 POST,可以是已登记或未登记的接口。风险未知,发送需 --yes;不继承领域命令的对象校验、风险分级和业务结果保证。',
359
- '默认发送到生产开放 API 网关,ZAN_SAAS_API_BASE_URL 可覆盖;默认使用 auth login 保存的凭证,受控环境配置 ZAN_SAAS_USER_ACCESS_TOKEN 时使用环境凭证;不接受任意目标 URL。',
367
+ '默认发送到生产开放 API 网关,ZAN_SAAS_API_BASE_URL 可覆盖。默认优先使用已存个人登录,仅无个人记录时使用环境token;显式 ZAN_SAAS_AUTH_SOURCE=env 可选择环境凭证,不接受任意目标 URL。',
360
368
  '退出0、HTTP 2xx 和 sent=true 只表示收到响应;即使正文报告业务失败也不改变退出码,不证明业务成功或写入完成。超时或断连时结果未知,不自动重试。',
361
369
  '不提供 --dry-run,不自动应用业务金额或日期转换。'
362
370
  ]
@@ -364,7 +372,7 @@ const contracts = {
364
372
  };
365
373
 
366
374
  function withSystemSchema(command, name) {
367
- const schema = { schemaVersion: 1, error, ...contracts[name] };
375
+ const schema = { schemaVersion: 1, error, ...(contracts[name] || shopModels.contracts[name]) };
368
376
  schema.error = { anyOf: [schema.error, structuredClone(parserErrorModel)] };
369
377
  attachCommandSchema(command, schema);
370
378
  return command;
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+
3
+ const object = properties => ({
4
+ type: 'object', additionalProperties: false, required: Object.keys(properties), properties
5
+ });
6
+ const id = { type: 'string', pattern: '^[1-9][0-9]*$', description: '正整数 ID 文本。' };
7
+ const nullableText = { type: ['string', 'null'], description: '已核实的名称或时间;缺失为 null。' };
8
+ const context = object({
9
+ userId: { type: 'string', minLength: 1, description: '已核实的账号 ID,不是客户或员工记录 ID。' },
10
+ hq: { ...id, description: '租户根组织 ID;单店取自身。' },
11
+ shopId: { ...id, description: '当前操作组织 ID,不自动代表全部连锁。' },
12
+ orgType: { enum: ['hq', 'shop'], description: '总部位置或受支持的非总部位置,不是详细组织角色。' }
13
+ });
14
+ const selection = object({
15
+ tenantRootKdtId: id, tenantName: nullableText, currentUnitKdtId: id, unitName: nullableText,
16
+ position: { enum: ['hq', 'shop'], description: '总部或非总部执行位置。' },
17
+ role: { type: ['integer', 'null'], minimum: 0, description: '有来源的组织角色:0单店、1总部、2001门店、2002网店;未知或未核实为null。' }
18
+ });
19
+ const binding = object({
20
+ mode: { enum: ['session', 'shared'], description: '宿主独立会话或本机共享选择。' },
21
+ sessionRef: { type: ['string', 'null'], description: '会话摘要短引用,共享模式为null。' },
22
+ state: { enum: ['uninitialized', 'needs_selection', 'ready', 'cleared', 'identity_pending', 'invalid'],
23
+ description: '分别为尚未初始化、待选店、就绪、已清除、待核实账号、无效。只有就绪的保存绑定提供上下文。' },
24
+ revision: { type: ['integer', 'null'], minimum: 1, maximum: Number.MAX_SAFE_INTEGER,
25
+ description: '绑定版本;无记录为null,冲突不覆盖较新选择。' },
26
+ origin: { enum: ['explicit', 'inherited', 'legacy_import', 'none'],
27
+ description: '明确选择、初始化继承、旧共享记录导入或无位置来源。' },
28
+ initializedAt: nullableText, selectedAt: nullableText
29
+ });
30
+ const nullable = value => ({ anyOf: [value, { type: 'null' }] });
31
+ const effect = action => object({
32
+ action: { const: action },
33
+ currentChanged: { type: 'boolean', description: '本次是否改变当前会话绑定。' },
34
+ recentChanged: { type: 'boolean', description: '本次是否改变供新会话继承的位置。' }
35
+ });
36
+ const chosenOutput = action => object({
37
+ context: nullable(context), selection: nullable(selection), binding, effect: effect(action)
38
+ });
39
+ const notes = [
40
+ '上下文及本地保存不证明员工权限;账号、组织关系和业务授权分别核验。失败后不自动换店、换身份或重放。',
41
+ '会话模式由宿主逐次注入 ZAN_SAAS_SESSION_ID。已有会话不跟随其他会话,查询和恢复不更新最近位置。'
42
+ ];
43
+ const switchInput = {
44
+ kdtId: id, sessionOnly: { type: 'boolean', description: '仅更新本会话,需要宿主会话标识;省略为false。' }
45
+ };
46
+ const optionalInput = properties => ({ ...object(properties), required: [] });
47
+ const contracts = {
48
+ 'shop.session.init': {
49
+ input: optionalInput({ resume: { type: 'boolean', description: '恢复原会话,缺记录则失败;省略为false。' } }),
50
+ output: chosenOutput('init'), notes: [...notes,
51
+ '显式初始化可核实当前账号并创建绑定。首次继承一次;无最近位置返回needs_selection;恢复已有记录不改时间和最近位置。']
52
+ },
53
+ 'shop.unit.use': {
54
+ input: { ...object(switchInput), required: ['kdtId'] },
55
+ output: chosenOutput('use_unit'), notes: [...notes,
56
+ '需要已初始化会话及当前租户。只支持已核实的当前连锁总部、门店或网店,不改变租户根。']
57
+ },
58
+ 'shop.resolve': {
59
+ input: { ...object({ kdtId: id, rootKdtId: { ...id, description: '目标所属根组织;省略时目标须为账号层根。' } }),
60
+ required: ['kdtId'] },
61
+ output: object({ context, selection, effect: effect('resolve'), revision: { type: 'null' } }),
62
+ notes: [...notes, '不保存当前位置。把返回context固定为本次任务每次调用的显式上下文;任务结束后丢弃。']
63
+ }
64
+ };
65
+
66
+ module.exports = { binding, selection, chosenOutput, contracts };