@tbox.cn/app-toolkit 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2
- import { existsSync, readFileSync } from 'node:fs';
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { createAppToolkit, type AppToolkit } from '../src/factory.js';
5
5
  import { AppToolkitError } from '../src/core/errors.js';
@@ -153,8 +153,10 @@ describe('写核心管线(FX-1c)', () => {
153
153
  it('T5 严格校验失败次序(A1):400 VALIDATION_FAILED + message 直通 + 凭据零落盘 + integrations 零变更', async () => {
154
154
  h.app.dispose();
155
155
  h = harness({ rejectMarker: '__reject__' });
156
+ // marker 藏 config 值位(zod 放行内层自由键、由 zod 本体拦截——节点顶层未知键已被
157
+ // assertNodeKeys 静态防线前置 400,见 D4;本用例锁定 zod 拒绝发生于凭据落盘之前)
156
158
  await expect(
157
- h.tk.writeServiceIntegration('parking.query', { provider: 'joycity', __reject__: true } as never, {
159
+ h.tk.writeServiceIntegration('parking.query', { provider: 'joycity', config: { __reject__: true } }, {
158
160
  credentials: { type: 'api-key', values: { apiKey: 'X' } },
159
161
  }),
160
162
  ).rejects.toMatchObject({
@@ -402,3 +404,140 @@ describe('孤儿凭据写后对账(PUT 路径追平——finalize 单点)',
402
404
  expect(nodiff.issues.some((i) => i.code === 'ORPHANED_CREDENTIAL')).toBe(false);
403
405
  });
404
406
  });
407
+
408
+ describe('降级写批(0.8.2 contractsTier——version null 放行 / blocked 保持 503)', () => {
409
+ /** 未安装态模块声明(declare.owns 归属键——服务身份判据命中) */
410
+ const moduleManifest = JSON.stringify({
411
+ schemaVersion: 1,
412
+ id: 'module-parking',
413
+ version: '0.1.0',
414
+ kind: 'business',
415
+ declare: { owns: [{ service: 'parking.query' }] },
416
+ });
417
+
418
+ it('D1 未安装:三 PUT + DELETE 降级成功——STRICT_VALIDATION_SKIPPED warning 随行 + 落盘正确', async () => {
419
+ const app = createTempApp('tbox-degrade-a-');
420
+ writeAppFile(app.appDir, 'packages/module-parking/tbox.module.json', moduleManifest);
421
+ const tk = createAppToolkit(app.appDir);
422
+ // 服务写(身份判据归属键命中;骨架物化 + 降级双 warning 并存)
423
+ const putSvc = await tk.writeServiceIntegration('parking.query', { provider: 'mock' });
424
+ expect(putSvc.written).toBe(true);
425
+ const skip = putSvc.issues.find((i) => i.code === 'STRICT_VALIDATION_SKIPPED');
426
+ expect(skip?.severity).toBe('warning');
427
+ expect(skip?.message).toMatch(/未安装/);
428
+ expect(putSvc.issues.some((i) => i.code === 'SKELETON_MATERIALIZED')).toBe(true);
429
+ expect(JSON.parse(readFileSync(join(app.appDir, INTEGRATIONS_FILE), 'utf8'))).toMatchObject({
430
+ services: { 'parking.query': { provider: 'mock' } },
431
+ });
432
+ // 模块写(v6 modules[owner] 键降级落盘——装 v6 contracts 后语义生效)
433
+ const putMod = await tk.writeModuleIntegration('module-parking', { provider: 'wanda' });
434
+ expect(putMod.written).toBe(true);
435
+ expect(putMod.issues.some((i) => i.code === 'STRICT_VALIDATION_SKIPPED')).toBe(true);
436
+ expect(JSON.parse(readFileSync(join(app.appDir, INTEGRATIONS_FILE), 'utf8'))).toMatchObject({
437
+ modules: { 'module-parking': { provider: 'wanda' } },
438
+ });
439
+ // root 写
440
+ const putApp = await tk.writeAppIntegration({ provider: 'mock' });
441
+ expect(putApp.written).toBe(true);
442
+ expect(putApp.issues.some((i) => i.code === 'STRICT_VALIDATION_SKIPPED')).toBe(true);
443
+ // DELETE 降级
444
+ const del = await tk.deleteServiceIntegration('parking.query');
445
+ expect(del.written).toBe(true);
446
+ app.dispose();
447
+ });
448
+
449
+ it('D2 源码态未构建(候选在场无产物):降级放行 + message 构建指引', async () => {
450
+ const app = createTempApp('tbox-degrade-b-');
451
+ // 手动候选:package.json 在场、dist/src 双缺(writeFakeContractsPackage withDist:false 落
452
+ // src/runtime.ts——vitest TS-host 可导入不构成未构建态,故手动构造 'none' 产物态)
453
+ const cand = join(app.appDir, 'apps', 'server', 'node_modules', '@tbox.cn', 'app-contracts');
454
+ mkdirSync(cand, { recursive: true });
455
+ writeFileSync(
456
+ join(cand, 'package.json'),
457
+ `${JSON.stringify({ name: '@tbox.cn/app-contracts', version: '0.13.0', type: 'module' }, null, 2)}\n`,
458
+ );
459
+ writeAppFile(app.appDir, 'packages/module-parking/tbox.module.json', moduleManifest);
460
+ const tk = createAppToolkit(app.appDir);
461
+ const put = await tk.writeServiceIntegration('parking.query', { provider: 'mock' });
462
+ expect(put.written).toBe(true);
463
+ const skip = put.issues.find((i) => i.code === 'STRICT_VALIDATION_SKIPPED');
464
+ expect(skip?.message).toMatch(/build 后重试/);
465
+ app.dispose();
466
+ });
467
+
468
+ it('D3 dryRun 对称(降级态彩排):零落盘 + files 预览 + warning 随行', async () => {
469
+ const app = createTempApp('tbox-degrade-c-');
470
+ writeAppFile(app.appDir, 'packages/module-parking/tbox.module.json', moduleManifest);
471
+ const tk = createAppToolkit(app.appDir);
472
+ const dry = await tk.writeServiceIntegration('parking.query', { provider: 'mock' }, { dryRun: true });
473
+ expect(dry.written).toBe(false);
474
+ expect(dry.files).toContain(INTEGRATIONS_FILE);
475
+ expect(existsSync(join(app.appDir, INTEGRATIONS_FILE))).toBe(false);
476
+ expect(dry.issues.some((i) => i.code === 'STRICT_VALIDATION_SKIPPED')).toBe(true);
477
+ app.dispose();
478
+ });
479
+
480
+ it('D4 键集纪律两态一致(assertNodeKeys 单点):降级态未知键 400 唯一防线;ok 态同码先行', async () => {
481
+ // 降级态(未安装)
482
+ const app = createTempApp('tbox-degrade-d-');
483
+ writeAppFile(app.appDir, 'packages/module-parking/tbox.module.json', moduleManifest);
484
+ const tk = createAppToolkit(app.appDir);
485
+ // 服务节点未知键(fields 单键粒度——原 applyModule 行为保持)
486
+ await expect(tk.writeServiceIntegration('parking.query', { provider: 'mock', typoKey: 1 } as never))
487
+ .rejects.toMatchObject({ code: 'VALIDATION_FAILED', httpStatus: 400, fields: ['typoKey'] });
488
+ // 实例位未知键
489
+ await expect(tk.writeServiceIntegration('parking.query', { instances: { '*': { typoKey: 1 } } } as never))
490
+ .rejects.toMatchObject({ code: 'VALIDATION_FAILED', fields: ['typoKey'] });
491
+ // root 未知键
492
+ await expect(tk.writeAppIntegration({ typoKey: 1 } as never))
493
+ .rejects.toMatchObject({ code: 'VALIDATION_FAILED', fields: ['typoKey'] });
494
+ // 模块位未知键(既有纪律迁移 assertNodeKeys——同码保持)
495
+ await expect(tk.writeModuleIntegration('module-parking', { typoKey: 1 } as never))
496
+ .rejects.toMatchObject({ code: 'VALIDATION_FAILED', fields: ['typoKey'] });
497
+ app.dispose();
498
+ // ok 态:静态防线先于 zod(同码 400)
499
+ const h2 = harness();
500
+ await expect(h2.tk.writeServiceIntegration('parking.query', { typoKey: 1 } as never))
501
+ .rejects.toMatchObject({ code: 'VALIDATION_FAILED', httpStatus: 400 });
502
+ h2.app.dispose();
503
+ });
504
+
505
+ it('D5 evaluate 门控严选保持(tier !== \'ok\' → 503):未安装态 evaluateIntegrationServices 拒绝(求值产物即求值结果,无降级语义)', async () => {
506
+ const app = createTempApp('tbox-degrade-e-');
507
+ writeAppFile(app.appDir, 'packages/module-parking/tbox.module.json', moduleManifest);
508
+ const tk = createAppToolkit(app.appDir);
509
+ await expect(
510
+ tk.evaluateIntegrationServices({
511
+ integrations: { services: {} },
512
+ suppliedProviders: {},
513
+ demandedServices: [],
514
+ } as never),
515
+ ).rejects.toMatchObject({ code: 'CONTRACTS_NOT_RESOLVED', httpStatus: 503 });
516
+ app.dispose();
517
+ });
518
+
519
+ it('I1 两 internals 写面摘门(行为不随 contracts 状态分叉):未安装态 ensureMockBindings 物化 + writeIntegrationsConfig 透传成功', async () => {
520
+ const app = createTempApp('tbox-degrade-f-');
521
+ // local:true 槽(ensureMockBindings 派生源——单厂商 terse 形态)
522
+ writeAppFile(app.appDir, 'packages/module-x/tbox.module.json', JSON.stringify({
523
+ schemaVersion: 1,
524
+ id: 'module-x',
525
+ version: '0.1.0',
526
+ kind: 'business',
527
+ declare: {
528
+ owns: [{ service: 'ghost.owned' }],
529
+ consumes: [],
530
+ providers: { slots: [{ service: 'ghost.owned', provider: 'mock', implementation: 'mock.ghost', credentialType: '-', local: true }] },
531
+ },
532
+ }));
533
+ const tk = createAppToolkit(app.appDir);
534
+ // ensureMockBindings:integrations.json 缺席 + local 槽 → 物化 mock 绑定(原 blanket 503 门已摘)
535
+ const mb = await tk.ensureMockBindings();
536
+ expect(mb).toMatchObject({ generated: true, reason: 'generated', services: ['ghost.owned'] });
537
+ expect(existsSync(join(app.appDir, INTEGRATIONS_FILE))).toBe(true);
538
+ // writeIntegrationsConfig:文件级整写透传(零校验零门——形状兼容性责任在调用方)
539
+ await tk.writeIntegrationsConfig({ provider: 'mock', services: {} });
540
+ expect(JSON.parse(readFileSync(join(app.appDir, INTEGRATIONS_FILE), 'utf8'))).toMatchObject({ provider: 'mock' });
541
+ app.dispose();
542
+ });
543
+ });
@@ -1 +0,0 @@
1
- import{existsSync as l,readdirSync as x,realpathSync as m}from"fs";import{join as c}from"path";import{pathToFileURL as F}from"url";import{existsSync as T,readFileSync as k,statSync as M}from"fs";function p(){let n=new Map,e=0;function r(t){if(!T(t))return null;let i=M(t);return`${i.mtimeMs}:${i.size}`}return{read(t,i){let o=r(t);if(o===null){n.delete(t);return}let s=n.get(t);if(s&&s.fingerprint===o)return s.value;e+=1;let a=i(k(t,"utf8"));return n.set(t,{fingerprint:o,value:a}),a},invalidate(t){if(t===void 0){n.clear();return}for(let i of t)n.delete(i)},get parseCount(){return e}}}var g=["resolveEffectiveService","buildSupplyLookup","moduleDomainOf","normalizeInstances","RESOURCE_TYPE_IDS"],N="parseIntegrationsConfig",O="OWNERSHIP_BINDING_V6",v={version:null,evaluation:!1,strictValidation:!1,ownershipBindingV6:!1,module:{},notes:[]};function C(n){let e=[n];for(let r of["apps","packages"]){let t=c(n,r);if(!l(t))continue;let i=x(t,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);r==="apps"?i.sort((o,s)=>o==="server"?-1:s==="server"?1:o.localeCompare(s)):i.sort((o,s)=>o.localeCompare(s));for(let o of i)e.push(c(t,o))}return e}var d=new Map,h=p();function y(n){return h.read(n,e=>{let r=JSON.parse(e);return typeof r.version=="string"?r.version:null})??null}function b(n){if(!l(n))return"gone";let e;try{e=m(n)}catch{e=n}return l(c(e,"dist","runtime.js"))?"dist":l(c(e,"src","runtime.ts"))?"src":"none"}function R(n){let e=c(n,"package.json");return{pkgPath:e,candidateDir:n,version:y(e),artifact:b(n)}}function E(n){for(let e of C(n)){let r=c(e,"node_modules","@tbox.cn","app-contracts"),t=c(r,"package.json");if(l(t))return{pkgPath:t,candidateDir:r,version:y(t),artifact:b(r)}}return null}function u(n){return n===null?"none":`${n.pkgPath}|${n.version??"null"}|${n.artifact}`}function _(n,e){let r=E(n);if(u(r)!==u(e.first))return!1;if(e.resolved===null)return!0;let t=r!==null&&r.candidateDir===e.resolved.candidateDir?r:R(e.resolved.candidateDir);return u(t)===u(e.resolved)}async function $(n,e){if(!l(n))return null;let r;try{r=m(n)}catch{return null}let i=[c(r,"dist","runtime.js"),c(r,"src","runtime.ts")].find(s=>l(s)),o=h.read(c(n,"package.json"),s=>{let a=JSON.parse(s);return typeof a.version=="string"?a.version:null})??null;if(i===void 0)return e.push(`contracts ${o??"(版本未知)"} 探测命中但无构建产物(dist/runtime.js 缺失)——workspace 源码态未构建:执行 pnpm --filter @tbox.cn/app-contracts build 后重试`),null;try{let s=o!==null?`?v=${encodeURIComponent(o)}`:"",a=await import(F(i).href+s),f=g.every(w=>a[w]!==void 0),P=a[N]!==void 0,S=a[O]===!0;return{version:o,evaluation:f,strictValidation:P,ownershipBindingV6:S,module:a,notes:f?[]:[`${i} 命中但求值面具名导出缺席(${g.join("/")})——契约包形态异常`]}}catch(s){return e.push(`contracts ${o??"(版本未知)"} 构建产物导入失败(${s instanceof Error?s.message:String(s)})——workspace 源码态未构建或产物损坏:执行 pnpm --filter @tbox.cn/app-contracts build 后重试`),null}}function L(n){let e=d.get(n);if(e&&_(n,e))return e.promise;let r=E(n),t={promise:Promise.resolve({...v}),first:r,resolved:r};return t.promise=(async()=>{let i=[];for(let o of C(n)){let s=c(o,"node_modules","@tbox.cn","app-contracts"),a=await $(s,i);if(a)return a.version!==null&&!a.strictValidation&&a.notes.push(`contracts ${a.version} 无严格校验面(需 ≥0.9.0)——升级应用 @tbox.cn/app-contracts 依赖后可用`),t.resolved=R(s),a}return t.resolved=null,i.length===0&&i.push("contracts 不可解析(未安装)——检查应用依赖安装后重试"),{...v,notes:i}})(),d.set(n,t),t.promise}function H(n){n===void 0?d.clear():d.delete(n)}export{p as a,L as b,H as c};
@@ -1 +0,0 @@
1
- import{b as a,c as b}from"./chunk-WUULQDOV.js";export{b as invalidateContractsResolver,a as resolveContractsForApp};