@tora-editor/tora 0.1.0 → 0.3.0
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 +107 -58
- package/assets/free-audio/arcade-pop/audio/loss.wav +0 -0
- package/assets/free-audio/arcade-pop/audio/reward.wav +0 -0
- package/assets/free-audio/arcade-pop/audio/win.wav +0 -0
- package/assets/free-audio/arcade-pop/source/INFO.txt +11 -11
- package/assets/kenney-food-starter/License.txt +28 -0
- package/assets/kenney-food-starter/burger.glb +0 -0
- package/assets/kenney-food-starter/frying-pan.glb +0 -0
- package/assets/kenney-food-starter/plan.json +61 -0
- package/assets/kenney-food-starter/plate.glb +0 -0
- package/assets/kenney-food-starter/pot.glb +0 -0
- package/assets/kenney-harvest/audio/victory.wav +0 -0
- package/assets/kenney-harvest/source/music-jingles/OGG/jingles_NES/jingles_NES03.ogg +0 -0
- package/assets/kenney-harvest/source/music-jingles/OGG/jingles_PIZZA/jingles_PIZZA03.ogg +0 -0
- package/assets/kenney-harvest/source/music-jingles/license.txt +14 -0
- package/bin/tora.mjs +322 -28
- package/crates/packer/trusted/native-3d-meta.json +4 -3
- package/crates/packer/trusted/native-3d.js +181 -181
- package/crates/packer/trusted/native-meta.json +3 -3
- package/crates/packer/trusted/native.js +5 -5
- package/crates/packer/trusted/release-manifest.json +17 -17
- package/crates/packer/trusted/review-runtime-meta.json +4 -3
- package/crates/packer/trusted/review-runtime.js +182 -182
- package/docs/MIGRATION_0_3.md +39 -0
- package/docs/NATIVE_AGENT_TOOLS.md +12 -363
- package/docs/TORA_AGENT_SETUP.md +24 -95
- package/docs/TORA_CREATION_API.md +63 -348
- package/docs/reference/CORE_AUTHORING.md +10 -3
- package/docs/reference/PLAYABLE_STARTERS.md +20 -0
- package/docs/reference/packs/3d.md +11 -3
- package/network-rules/mintegral-appgrowth-single-html.json +10 -10
- package/package.json +6 -6
- package/packages/creative-project/project-v21.schema.json +372 -9
- package/scripts/lean/editor/entry.js +11 -6
- package/scripts/lean/editor/project-launcher.js +116 -0
- package/scripts/lean/editor/quick-edit-panel.js +479 -0
- package/scripts/lean/editor/review-editor.css +256 -68
- package/scripts/lean/editor/review-editor.js +1834 -1086
- package/scripts/lean/editor-state.mjs +6 -0
- package/scripts/lean/editor.mjs +6 -3
- package/scripts/lean/matrix.mjs +5 -0
- package/scripts/lean/native/agent-tools.mjs +39 -62
- package/scripts/lean/native/api.mjs +161 -136
- package/scripts/lean/native/asset-catalog.mjs +7 -6
- package/scripts/lean/native/asset-lineage.mjs +54 -0
- package/scripts/lean/native/asset-prep.mjs +173 -40
- package/scripts/lean/native/assets.mjs +107 -11
- package/scripts/lean/native/audio-assets.mjs +30 -0
- package/scripts/lean/native/browser-pool.mjs +34 -0
- package/scripts/lean/native/build-cache.mjs +38 -7
- package/scripts/lean/native/cc0-inputs.mjs +24 -0
- package/scripts/lean/native/cc0-staging.mjs +28 -8
- package/scripts/lean/native/compiler.mjs +9 -3
- package/scripts/lean/native/contracts.mjs +16 -11
- package/scripts/lean/native/creative-qa.mjs +365 -128
- package/scripts/lean/native/demos.mjs +53 -18
- package/scripts/lean/native/document.mjs +50 -12
- package/scripts/lean/native/export-budget.mjs +75 -0
- package/scripts/lean/native/local-bundle.mjs +7 -3
- package/scripts/lean/native/mcp-server.mjs +42 -74
- package/scripts/lean/native/media-validate.mjs +124 -0
- package/scripts/lean/native/modules/harvest-restore.mjs +3 -284
- package/scripts/lean/native/modules/sort-puzzle.mjs +51 -0
- package/scripts/lean/native/modules/star-salvage.mjs +3 -368
- package/scripts/lean/native/native-bin.mjs +3 -3
- package/scripts/lean/native/outcome-playthrough.mjs +97 -0
- package/scripts/lean/native/project-bundle.mjs +6 -5
- package/scripts/lean/native/project-index.mjs +0 -2
- package/scripts/lean/native/qa-adapters.mjs +10 -0
- package/scripts/lean/native/quick-edit.mjs +328 -0
- package/scripts/lean/native/remote-cc0-fetcher.mjs +403 -197
- package/scripts/lean/native/review.mjs +205 -571
- package/scripts/lean/native/schema-vocabulary.mjs +10 -0
- package/scripts/lean/native/schema.mjs +7 -5
- package/scripts/lean/native/scope.mjs +45 -0
- package/scripts/lean/native/service.mjs +378 -79
- package/scripts/lean/native/starters.mjs +563 -0
- package/scripts/lean/native/variant-adapters.mjs +8 -0
- package/scripts/lean/native/variants-core.mjs +186 -0
- package/scripts/lean/native/variants.mjs +63 -0
- package/scripts/lean/native/win-cues.mjs +96 -0
- package/skills/tora-playables/SKILL.md +1 -1
- package/scripts/lean/editor/review-intake.js +0 -837
- package/scripts/lean/model-client.mjs +0 -119
- package/scripts/lean/native/author-expansion-proofs.mjs +0 -240
- package/scripts/lean/native/author-games.mjs +0 -160
- package/scripts/lean/native/author-harvest.mjs +0 -74
- package/scripts/lean/native/author-primitive-proofs.mjs +0 -874
- package/scripts/lean/native/author-salvage.mjs +0 -71
- package/scripts/lean/native/chat-compose.mjs +0 -287
- package/scripts/lean/native/check-harvest-outcome-audio.mjs +0 -191
- package/scripts/lean/native/check-salvage.mjs +0 -197
- package/scripts/lean/native/compatibility.mjs +0 -34
- package/scripts/lean/native/concept.mjs +0 -633
- package/scripts/lean/native/draw-stroke.mjs +0 -26
- package/scripts/lean/native/erase-mask.mjs +0 -18
- package/scripts/lean/native/harvest-recipe.mjs +0 -21
- package/scripts/lean/native/instance-steering.mjs +0 -24
- package/scripts/lean/native/intake-creator-agent.mjs +0 -98
- package/scripts/lean/native/intake-creator-tools.mjs +0 -165
- package/scripts/lean/native/interaction-gestures.mjs +0 -45
- package/scripts/lean/native/match-board.mjs +0 -138
- package/scripts/lean/native/modules/index.mjs +0 -54
- package/scripts/lean/native/modules/tap-collect.mjs +0 -54
- package/scripts/lean/native/path-network.mjs +0 -132
- package/scripts/lean/native/physics-2d.mjs +0 -154
- package/scripts/lean/native/physics-3d.mjs +0 -259
- package/scripts/lean/native/prepare-audio-collections.mjs +0 -112
- package/scripts/lean/native/prepare-game-audio.mjs +0 -372
- package/scripts/lean/native/prepare-golf-3d-assets.py +0 -177
- package/scripts/lean/native/prepare-golf-assets.py +0 -211
- package/scripts/lean/native/prepare-harvest-audio.mjs +0 -83
- package/scripts/lean/native/prepare-harvest-images.mjs +0 -31
- package/scripts/lean/native/prepare-primitive-images.py +0 -25
- package/scripts/lean/native/prepare-space-salvage-images.mjs +0 -89
- package/scripts/lean/native/prepare-traffic-assets.py +0 -329
- package/scripts/lean/native/presentation.mjs +0 -335
- package/scripts/lean/native/review-agent-tools.mjs +0 -561
- package/scripts/lean/native/review-connection.mjs +0 -303
- package/scripts/lean/native/review-fields.mjs +0 -24
- package/scripts/lean/native/review-intake.mjs +0 -385
- package/scripts/lean/native/review-intents.mjs +0 -217
- package/scripts/lean/native/review-provider.mjs +0 -580
- package/scripts/lean/native/review-receipts.mjs +0 -76
- package/scripts/lean/native/review-resolver.mjs +0 -429
- package/scripts/lean/native/review-targets.mjs +0 -35
- package/scripts/lean/native/runtime.mjs +0 -1623
- package/scripts/lean/native/salvage-recipe.mjs +0 -20
- package/scripts/lean/native/stage-3d.mjs +0 -818
- package/scripts/lean/native/verify.mjs +0 -4
- package/scripts/lean/scene-document.mjs +0 -48
|
@@ -1,18 +1,48 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import {execFile} from 'node:child_process';
|
|
2
|
+
import {promisify} from 'node:util';
|
|
3
|
+
import {Buffer} from 'node:buffer';
|
|
4
|
+
import {writeFile,mkdir,mkdtemp,readFile,copyFile,rm,rename,stat} from 'node:fs/promises';
|
|
5
|
+
import {resolve,dirname,relative,isAbsolute,sep} from 'node:path';
|
|
3
6
|
import {randomUUID} from 'node:crypto';
|
|
4
7
|
import {canonical,projectContent} from '../../../packages/creative-project/src/canonical.mjs';
|
|
5
|
-
import {check,exact,applyOperations,validateDocument} from './document.mjs';
|
|
8
|
+
import {check,exact,applyOperations,validateDocument,references} from './document.mjs';
|
|
6
9
|
import {compileNative,hash,projectUses3d,runtime3dBundle,runtimeBundle} from './compiler.mjs';
|
|
7
|
-
import {lowerAssets,readOriginal,registerSource,safeFile} from './assets.mjs';
|
|
10
|
+
import {lowerAssets,modelSourceTypes,readOriginal,registerSource,registerSourceBytes,registerSourceFromFile,safeFile} from './assets.mjs';
|
|
11
|
+
import {readRevisionLineage,saveRevisionLineage} from './asset-lineage.mjs';
|
|
12
|
+
import {resolvePreparedProvenance} from './asset-prep.mjs';
|
|
8
13
|
import {capabilities} from './contracts.mjs';
|
|
9
14
|
import {CREATIVE_QA_CHECKER_VERSION,CREATIVE_QA_FORMAT,getPlaywrightBrowserVersion,runStaticPreflight} from './creative-qa.mjs';
|
|
10
15
|
import {isAudioMime} from './media-validate.mjs';
|
|
11
|
-
import {assertNetworkTarget} from './network-targets.mjs';
|
|
16
|
+
import {acceptsTargetBytes,assertNetworkTarget} from './network-targets.mjs';
|
|
12
17
|
import {NativeBuildCache,VerificationReceiptCache,buildCacheKey} from './build-cache.mjs';
|
|
13
18
|
import {mapWithConcurrency} from './concurrency.mjs';
|
|
14
19
|
import {assertSingleVisualStyleFamily} from './cc0-staging.mjs';
|
|
20
|
+
import {requireNativeTool} from './native-bin.mjs';
|
|
21
|
+
import {closeSharedBrowser,defaultQaConcurrency,getSharedBrowser} from './browser-pool.mjs';
|
|
22
|
+
import {exportBudget} from './export-budget.mjs';
|
|
23
|
+
import {playableHTML} from './html.mjs';
|
|
24
|
+
import {createPresetOverlay,extractLocalizableStrings,materializeVariant,readVariants,updateVariants,validateVariantStore,variantStoreHash,visibleStringVariables} from './variants.mjs';
|
|
25
|
+
import {qaAdapterForProject} from './qa-adapters.mjs';
|
|
26
|
+
import {variantAdapterForProject} from './variant-adapters.mjs';
|
|
27
|
+
import {withProjectFileLock} from '../editor-state.mjs';
|
|
28
|
+
const runTool=promisify(execFile);
|
|
29
|
+
const checkerHashCache=new Map();
|
|
30
|
+
async function nativeBinaryHash(commandPath){
|
|
31
|
+
const info=await stat(commandPath),cached=checkerHashCache.get(commandPath);
|
|
32
|
+
if(cached&&cached.mtimeMs===info.mtimeMs&&cached.size===info.size)return cached.digest;
|
|
33
|
+
const digest=hash(await readFile(commandPath));
|
|
34
|
+
checkerHashCache.set(commandPath,{mtimeMs:info.mtimeMs,size:info.size,digest});
|
|
35
|
+
return digest;
|
|
36
|
+
}
|
|
37
|
+
const MODEL_FIT_LADDER=Object.freeze([
|
|
38
|
+
{maxTextureSide:256,targetBytes:180000},
|
|
39
|
+
{maxTextureSide:192,targetBytes:110000},
|
|
40
|
+
{maxTextureSide:128,targetBytes:64000},
|
|
41
|
+
{maxTextureSide:96,targetBytes:36000},
|
|
42
|
+
]);
|
|
43
|
+
const IMAGE_FIT_SIDES=Object.freeze([512,384,256,160]);
|
|
15
44
|
const PREAPPLY_AUDIO_BLOCKERS=new Set(['audio-role-mismatch','audio-valence-mismatch','audio-win-loss-duplicate','audio-contour-mismatch','audio-clipping']);
|
|
45
|
+
let sharedBatchJobs=0;
|
|
16
46
|
export const contentHash=p=>hash('tora-v2-hash/1\ndocument-content\n'+canonical(projectContent(p)));
|
|
17
47
|
export function requireCreativeQa(report){
|
|
18
48
|
if(report?.ok)return report;
|
|
@@ -33,39 +63,107 @@ function qaReportSatisfiesOptions(report,{motionFilmstrip=true,recordVideo=false
|
|
|
33
63
|
}
|
|
34
64
|
return true;
|
|
35
65
|
}
|
|
66
|
+
function evidenceFiles(report){return [...(report.screenshots??[]),...(report.contactSheets??[]),...(report.motionFilmstrips??[]),...(report.video?[report.video]:[])];}
|
|
67
|
+
function evidencePath(root,path){
|
|
68
|
+
if(typeof path!=='string'||isAbsolute(path))throw Error('E_QA_EVIDENCE_PATH');
|
|
69
|
+
const srcRoot=resolve(root),resolved=resolve(srcRoot,path),rel=relative(srcRoot,resolved);
|
|
70
|
+
if(!rel||rel==='..'||rel.startsWith('..'+sep))throw Error('E_QA_EVIDENCE_PATH');
|
|
71
|
+
return resolved;
|
|
72
|
+
}
|
|
36
73
|
async function verifyAndCopyQaArtifacts(cachedOutputDir,targetOutputDir,report,options={}){
|
|
37
74
|
if(!qaReportSatisfiesOptions(report,options))return false;
|
|
38
|
-
const files=
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
];
|
|
44
|
-
for(const entry of files){
|
|
45
|
-
if(!entry?.path||!entry?.sha256)return false;
|
|
46
|
-
try{
|
|
47
|
-
const bytes=await readFile(resolve(cachedOutputDir,entry.path));
|
|
75
|
+
const files=evidenceFiles(report);
|
|
76
|
+
try{
|
|
77
|
+
for(const entry of files){
|
|
78
|
+
if(!entry?.path||!entry?.sha256)return false;
|
|
79
|
+
const bytes=await readFile(evidencePath(cachedOutputDir,entry.path));
|
|
48
80
|
if(hash(bytes)!==entry.sha256)return false;
|
|
49
|
-
}
|
|
50
|
-
|
|
81
|
+
}
|
|
82
|
+
await readFile(evidencePath(cachedOutputDir,'report.json'));
|
|
83
|
+
}catch{return false;}
|
|
51
84
|
const srcRoot=resolve(cachedOutputDir),dstRoot=resolve(targetOutputDir);
|
|
52
85
|
if(srcRoot!==dstRoot){
|
|
53
86
|
await mkdir(dstRoot,{recursive:true});
|
|
54
87
|
for(const entry of files){
|
|
55
|
-
const dst=
|
|
88
|
+
const dst=evidencePath(dstRoot,entry.path);
|
|
56
89
|
await mkdir(dirname(dst),{recursive:true});
|
|
57
|
-
await copyFile(
|
|
90
|
+
await copyFile(evidencePath(srcRoot,entry.path),dst);
|
|
58
91
|
}
|
|
59
|
-
await copyFile(
|
|
92
|
+
await copyFile(evidencePath(srcRoot,'report.json'),evidencePath(dstRoot,'report.json'));
|
|
60
93
|
}
|
|
61
94
|
return true;
|
|
62
95
|
}
|
|
96
|
+
async function copyFailedQaArtifacts(source,target,report){
|
|
97
|
+
await mkdir(target,{recursive:true});
|
|
98
|
+
for(const entry of evidenceFiles(report)){
|
|
99
|
+
if(!entry?.path)continue;
|
|
100
|
+
try{const bytes=await readFile(evidencePath(source,entry.path));if(entry.sha256&&hash(bytes)!==entry.sha256)throw Error('E_QA_EVIDENCE_HASH');const destination=evidencePath(target,entry.path);await mkdir(dirname(destination),{recursive:true});await writeFile(destination,bytes);}
|
|
101
|
+
catch(error){if(error.code!=='ENOENT')throw error;}
|
|
102
|
+
}
|
|
103
|
+
await copyFile(evidencePath(source,'report.json'),evidencePath(target,'report.json'));return target;
|
|
104
|
+
}
|
|
105
|
+
async function writeAtomic(path,bytes){
|
|
106
|
+
await mkdir(dirname(path),{recursive:true});const temporary=resolve(dirname(path),'.'+randomUUID()+'.tmp');
|
|
107
|
+
try{await writeFile(temporary,bytes,{flag:'wx'});await rename(temporary,path);}finally{await rm(temporary,{force:true});}
|
|
108
|
+
}
|
|
109
|
+
function deliveryFilename(id,artifact,target){
|
|
110
|
+
if(artifact.archiveFilename)return artifact.archiveFilename;
|
|
111
|
+
return target==='standalone-browser-draft'?`${id}-draft.html`:'index.html';
|
|
112
|
+
}
|
|
113
|
+
function artifactCheckFailure(report,cause){
|
|
114
|
+
const error=Error('E_ARTIFACT_CHECK',{cause});error.code='E_ARTIFACT_CHECK';error.artifactCheck=report;return error;
|
|
115
|
+
}
|
|
116
|
+
function expectedCopyFor(project,variant){
|
|
117
|
+
if(!variant?.language)return undefined;
|
|
118
|
+
const checks={opening:new Set(),'after-first-input':new Set(),'end-card':new Set(),timeout:new Set()},components=new Map(project.components.map(component=>[component.id,component])),sceneStates=new Map(project.scenes.map(scene=>[scene.id,scene.role==='end-card'?(/fail|loss|timeout/i.test(scene.id)?'timeout':'end-card'):'opening']));
|
|
119
|
+
const effectivelyVisible=component=>{for(let current=component;current;current=components.get(current.parentId))if(current.parameters.visible===false)return false;return true;};
|
|
120
|
+
const rendered=component=>component?.parameters.text?.replace(/\{\{([a-z0-9_.-]+)\}\}/g,(_,key)=>String(project.variables.find(variable=>variable.id===key)?.initial??''));
|
|
121
|
+
const descendants=id=>{const ids=new Set([id]);for(let changed=true;changed;){changed=false;for(const component of project.components)if(component.parentId&&ids.has(component.parentId)&&!ids.has(component.id)){ids.add(component.id);changed=true;}}return ids;};
|
|
122
|
+
const phaseOutcome=value=>{if(!value||typeof value!=='object')return false;if(/(?:^|\.)phase$/.test(value.variableId??'')&&['cta','payoff'].includes(value.value))return true;return Object.values(value).some(phaseOutcome);};
|
|
123
|
+
const descriptor=qaAdapterForProject(project),canCheckEndCard=project.scenes.some(scene=>scene.role==='end-card')||Boolean(descriptor?.qa?.playToEndCard),canCheckTimeout=[...sceneStates.values()].includes('timeout')||Boolean(descriptor?.qa?.deadlineBehaviorId&&descriptor?.qa?.phaseVariable);
|
|
124
|
+
const stateFor=(binding,component)=>{
|
|
125
|
+
const event=project.events.find(item=>item.id===binding.eventId),sceneState=sceneStates.get(component?.sceneId)??'opening',transition=binding.actions.find(action=>action.kind==='changeScene');
|
|
126
|
+
if(transition){const state=sceneStates.get(transition.sceneId)??sceneState;return state==='end-card'&&!canCheckEndCard||state==='timeout'&&!canCheckTimeout?null:state;}
|
|
127
|
+
if(event?.kind==='timer'&&(/deadline|timeout/i.test(event.behaviorId??'')||binding.actions.some(action=>action.kind==='set'&&/(?:^|\.)phase$/.test(action.variableId??'')&&action.value==='cta')))return canCheckTimeout?'timeout':null;
|
|
128
|
+
if(event?.kind==='variableChange'&&(phaseOutcome(binding.condition)||binding.actions.some(action=>action.kind==='set'&&/(?:^|\.)phase$/.test(action.variableId??'')&&['cta','payoff'].includes(action.value))))return canCheckEndCard?'end-card':null;
|
|
129
|
+
if(['variableChange','timer'].includes(event?.kind))return null;
|
|
130
|
+
return sceneState;
|
|
131
|
+
};
|
|
132
|
+
const revealed=new Map(),hidden=new Map(),overrides=new Map();
|
|
133
|
+
for(const binding of project.eventBindings){
|
|
134
|
+
for(const action of binding.actions)if(action.kind==='setComponent'){
|
|
135
|
+
const component=components.get(action.componentId),state=stateFor(binding,component);
|
|
136
|
+
if(action.key==='visible'){
|
|
137
|
+
const states=action.value===true?revealed:hidden;for(const id of descendants(action.componentId)){if(!states.has(id))states.set(id,new Set());states.get(id).add(state);}
|
|
138
|
+
}
|
|
139
|
+
if(action.key==='text'){if(!overrides.has(action.componentId))overrides.set(action.componentId,new Set());overrides.get(action.componentId).add(state);}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
for(const id of Object.keys(variant.texts??{})){
|
|
143
|
+
const component=components.get(id);if(!component)continue;const text=rendered(component);if(!text?.trim())continue;
|
|
144
|
+
const states=revealed.get(id);if(states)for(const state of states)if(state&&!overrides.get(id)?.has(state)&&!hidden.get(id)?.has(state))checks[state].add(text);
|
|
145
|
+
else {const state=sceneStates.get(component.sceneId)??'opening';if(effectivelyVisible(component)&&!hidden.get(id)?.has(state))checks[state].add(text);}
|
|
146
|
+
}
|
|
147
|
+
const visibleVariables=new Set(project.components.filter(component=>component.contract==='native.text.v1').flatMap(component=>[...component.parameters.text.matchAll(/\{\{([a-z0-9_.-]+)\}\}/g)].map(match=>match[1])));
|
|
148
|
+
for(const binding of project.eventBindings)for(const action of binding.actions){
|
|
149
|
+
if(typeof action.value!=='string'||!action.value.trim()||action.value.includes('{{'))continue;
|
|
150
|
+
const isText=action.kind==='setComponent'&&action.key==='text',isVisibleVariable=action.kind==='set'&&visibleVariables.has(action.variableId);if(!isText&&!isVisibleVariable)continue;
|
|
151
|
+
const event=project.events.find(item=>item.id===binding.eventId),component=components.get(action.componentId),state=stateFor(binding,component);
|
|
152
|
+
if(isVisibleVariable&&['click','timer'].includes(event?.kind)){
|
|
153
|
+
const linked=project.components.filter(component=>component.contract==='native.text.v1'&&component.parameters.text.includes('{{'+action.variableId+'}}'));
|
|
154
|
+
if(state&&linked.some(component=>revealed.get(component.id)?.has(state)||effectivelyVisible(component)&&!hidden.get(component.id)?.has(state)))checks[state].add(action.value);continue;
|
|
155
|
+
}
|
|
156
|
+
if(isText&&state&&!hidden.get(action.componentId)?.has(state)&&(effectivelyVisible(component)||revealed.get(action.componentId)?.has(state)))checks[state].add(action.value);
|
|
157
|
+
}
|
|
158
|
+
const result=Object.fromEntries(Object.entries(checks).filter(([,values])=>values.size).map(([state,values])=>[state,[...values]]));
|
|
159
|
+
return Object.keys(result).length?result:undefined;
|
|
160
|
+
}
|
|
63
161
|
export class NativeService{
|
|
64
162
|
constructor(store,history,{qaRunner=defaultQaRunner,browserProvider,useVerifyCache}={}){this.store=store;this.history=history;this.qaRunner=qaRunner;this.browserProvider=browserProvider;this.useVerifyCache=useVerifyCache;this.buildCache=new NativeBuildCache();this.verifyCache=new VerificationReceiptCache(store.root);}
|
|
65
163
|
async create(input){check(input?.id!=='compose'&&/^[a-z][a-z0-9-]{1,47}$/.test(input?.id)&&exact(input,['id','name','kind','androidUrl']),'E_NATIVE_ARGUMENT');await this.store.createNative(input);return this.read(input.id);}
|
|
66
164
|
async read(id,revisionId){const base=await this.store.open(id);check(base.project.base.kind==='native-scene','E_NATIVE_KIND');const journal=await this.history.readRevisionJournal(id);revisionId??=journal.history[journal.index];check(revisionId==='initial'||/^rev-[a-f0-9-]{36}$/.test(revisionId),'E_NATIVE_REVISION');check((journal.revisions??journal.history).includes(revisionId)||journal.accepted.includes(revisionId),'E_NATIVE_NOT_FOUND');const project=revisionId==='initial'?base.project:validateDocument(JSON.parse((await safeFile(resolve(this.store.root,id,'revisions',revisionId,'project.json'))).toString()));check(project.projectId===id&&project.revisionId===revisionId,'E_NATIVE_REVISION');const digest=contentHash(project);if(journal.hashes?.[revisionId])check(journal.hashes[revisionId]===digest,'E_NATIVE_HASH');return {project,revisionId,contentHash:digest,accepted:journal.accepted.includes(revisionId),workingRevision:journal.history[journal.index],editorUrl:'/?project='+id,capabilities:capabilities()};}
|
|
67
165
|
async preview(id,envelope){check(exact(envelope,['format','expected','operations','previewDigest'])&&envelope.format==='tora-transaction-1'&&exact(envelope.expected,['revisionId','contentHash']),'E_NATIVE_ENVELOPE');const current=await this.read(id);check(envelope.expected.revisionId===current.revisionId&&envelope.expected.contentHash===current.contentHash,'E_NATIVE_STALE');const result=applyOperations(current.project,envelope.operations);result.effects.changed=Object.fromEntries(['scenes','components','variables','gameplay','events','eventBindings','assets'].map(key=>[key,[...new Set([...current.project[key],...result.project[key]].map(x=>x.id))].filter(id=>JSON.stringify(current.project[key].find(x=>x.id===id))!==JSON.stringify(result.project[key].find(x=>x.id===id)))]));result.effects.affectedBindings=result.project.eventBindings.filter(b=>result.effects.changed.events.includes(b.eventId)).map(b=>b.id);result.effects.assetReferences=current.project.components.filter(c=>result.effects.removed.includes(c.id)).flatMap(c=>c.assetSlots.map(a=>({componentId:c.id,assetId:a.assetId,remainingReferences:result.project.components.filter(x=>x.assetSlots.some(s=>s.assetId===a.assetId)).length,assetRetained:true})));const digest=hash(canonical({expected:envelope.expected,operations:envelope.operations,effects:result.effects,resultHash:contentHash(result.project)}));return {...result,previewDigest:digest,expected:envelope.expected};}
|
|
68
|
-
async transact(id,envelope,{guard,record}={}){
|
|
166
|
+
async transact(id,envelope,{guard,record,registeredAssets=[]}={}){
|
|
69
167
|
const preview=await this.preview(id,envelope);
|
|
70
168
|
check(envelope.previewDigest===preview.previewDigest,'E_NATIVE_PREVIEW_STALE');
|
|
71
169
|
const project=preview.project;
|
|
@@ -87,6 +185,7 @@ export class NativeService{
|
|
|
87
185
|
await writeFile(resolve(folder,'playable.html'),artifact.html,{flag:'wx'});
|
|
88
186
|
await writeFile(resolve(folder,'manifest.json'),JSON.stringify(artifact.manifest),{flag:'wx'});
|
|
89
187
|
const revision={revisionId:project.revisionId,contentHash:contentHash(project)};
|
|
188
|
+
await saveRevisionLineage(resolve(this.store.root,id),project,envelope.expected.revisionId,registeredAssets);
|
|
90
189
|
state.hashes={...state.hashes,[revision.revisionId]:revision.contentHash};
|
|
91
190
|
state.revisions=[...new Set([...(state.revisions??state.history),revision.revisionId])];
|
|
92
191
|
state.history=state.history.slice(0,state.index+1);
|
|
@@ -98,28 +197,134 @@ export class NativeService{
|
|
|
98
197
|
}
|
|
99
198
|
async navigate(id,{expected,action}){const current=await this.read(id);check(expected?.revisionId===current.revisionId&&expected.contentHash===current.contentHash,'E_NATIVE_STALE');check(['undo','redo','save'].includes(action),'E_NATIVE_ARGUMENT');await this.history.commitRevision(id,current.revisionId,async state=>{const index=state.index+(action==='undo'?-1:action==='redo'?1:0);check(state.history[index],'E_NATIVE_HISTORY_BOUNDARY');state.index=index;return {state,value:true};});return this.read(id);}
|
|
100
199
|
async accept(id,{revisionId,contentHash:expected}){const current=await this.read(id,revisionId);check(current.contentHash===expected,'E_NATIVE_STALE');await this.history.commitRevision(id,current.workingRevision,async state=>{state.accepted=[...new Set([...state.accepted,revisionId])];return {state,value:true};});return {revisionId,contentHash:expected,accepted:true};}
|
|
101
|
-
async
|
|
102
|
-
const
|
|
103
|
-
return
|
|
200
|
+
async fitToTarget(id,project,assets,target){
|
|
201
|
+
const projectRoot=resolve(this.store.root,id),origContentHash=contentHash(project);
|
|
202
|
+
try{return await compileNative(project,{assets,target,sourceContentHash:origContentHash});}
|
|
203
|
+
catch(error){if(error.message!=='E_UPLOAD_SIZE')throw error;}
|
|
204
|
+
const used=new Set(references([project.components,project.gameplay,project.events,project.eventBindings]));
|
|
205
|
+
let workingAssets=assets.filter(a=>used.has(a.id)).map(a=>({...a}));
|
|
206
|
+
const droppedUnused=assets.filter(a=>!used.has(a.id)).map(a=>a.id);
|
|
207
|
+
const steps=[];
|
|
208
|
+
const makeProject=()=>({...project,assets:workingAssets.map(asset=>{const copy={...asset};delete copy.data;return copy;})});
|
|
209
|
+
const makeReport=()=>({fitTargetBudget:true,policy:'fit-v1',droppedUnused,steps});
|
|
210
|
+
if(droppedUnused.length){
|
|
211
|
+
try{return await compileNative(makeProject(),{assets:workingAssets,target,sourceContentHash:origContentHash,optimizationReport:makeReport()});}
|
|
212
|
+
catch(error){if(error.message!=='E_UPLOAD_SIZE')throw error;}
|
|
213
|
+
}
|
|
214
|
+
const lineage=await readRevisionLineage(projectRoot,project.revisionId);
|
|
215
|
+
const stageRoot=resolve(projectRoot,'sources/assets');
|
|
216
|
+
await mkdir(stageRoot,{recursive:true});
|
|
217
|
+
const stage=await mkdtemp(resolve(stageRoot,'.fit-'));
|
|
218
|
+
try{
|
|
219
|
+
const modelIds=workingAssets.filter(a=>a.mime==='model/gltf-binary').sort((a,b)=>b.bytes-a.bytes||a.id.localeCompare(b.id)).map(a=>a.id);
|
|
220
|
+
let stepIndex=0;
|
|
221
|
+
for(const tier of MODEL_FIT_LADDER){
|
|
222
|
+
for(const assetId of modelIds){
|
|
223
|
+
const idx=workingAssets.findIndex(a=>a.id===assetId);
|
|
224
|
+
if(idx<0)continue;
|
|
225
|
+
const current=workingAssets[idx],entry=lineage[assetId];
|
|
226
|
+
let sourceBytes=Buffer.from(current.data,'base64'),source='delivery-fallback',ext='.glb';
|
|
227
|
+
if(entry?.masterAvailable&&entry?.originalHash){
|
|
228
|
+
try{
|
|
229
|
+
sourceBytes=await readOriginal(projectRoot,entry.originalHash);
|
|
230
|
+
source='master';
|
|
231
|
+
ext=modelSourceTypes.get(entry.originalMime)??'.glb';
|
|
232
|
+
}catch(err){if(err.code!=='ENOENT')throw err;}
|
|
233
|
+
}
|
|
234
|
+
const inName=`in-${stepIndex}${ext}`,outName=`out-${stepIndex}.glb`;
|
|
235
|
+
stepIndex++;
|
|
236
|
+
await writeFile(resolve(stage,inName),sourceBytes);
|
|
237
|
+
const tool=requireNativeTool('optimize-3d');
|
|
238
|
+
const opts={mode:'auto',maxTextureSide:tier.maxTextureSide,targetBytes:tier.targetBytes,preserveNamedNodes:true};
|
|
239
|
+
await runTool(tool.command,[...tool.prefixArgs,stage,inName,outName,JSON.stringify(opts)],{timeout:120000,maxBuffer:1048576});
|
|
240
|
+
const fitted=await readFile(resolve(stage,outName));
|
|
241
|
+
if(fitted.length>=current.bytes)continue;
|
|
242
|
+
const fittedHash=hash(fitted);
|
|
243
|
+
workingAssets[idx]={...current,data:fitted.toString('base64'),bytes:fitted.length,hash:fittedHash,mime:'model/gltf-binary'};
|
|
244
|
+
steps.push({assetId,kind:'model',source,fromBytes:current.bytes,toBytes:fitted.length,fittedHash,maxTextureSide:tier.maxTextureSide,targetBytes:tier.targetBytes});
|
|
245
|
+
try{return await compileNative(makeProject(),{assets:workingAssets,target,sourceContentHash:origContentHash,optimizationReport:makeReport()});}
|
|
246
|
+
catch(error){if(error.message!=='E_UPLOAD_SIZE')throw error;}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const imageIds=workingAssets.filter(a=>(a.mime==='image/png'||a.mime==='image/jpeg')&&a.bytes>32768).sort((a,b)=>b.bytes-a.bytes||a.id.localeCompare(b.id)).map(a=>a.id);
|
|
250
|
+
for(const maxSide of IMAGE_FIT_SIDES){
|
|
251
|
+
for(const assetId of imageIds){
|
|
252
|
+
const idx=workingAssets.findIndex(a=>a.id===assetId);
|
|
253
|
+
if(idx<0)continue;
|
|
254
|
+
const current=workingAssets[idx],entry=lineage[assetId];
|
|
255
|
+
let sourceBytes=Buffer.from(current.data,'base64'),source='delivery-fallback',srcMime=current.mime;
|
|
256
|
+
if(entry?.masterAvailable&&entry?.originalHash){
|
|
257
|
+
try{
|
|
258
|
+
sourceBytes=await readOriginal(projectRoot,entry.originalHash);
|
|
259
|
+
source='master';
|
|
260
|
+
srcMime=entry.originalMime??current.mime;
|
|
261
|
+
}catch(err){if(err.code!=='ENOENT')throw err;}
|
|
262
|
+
}
|
|
263
|
+
const ext=srcMime==='image/jpeg'?'.jpg':'.png',inName=`img-${stepIndex}${ext}`,prepOutDir=`imgout-${stepIndex}`,optOut=`imgopt-${stepIndex}`;
|
|
264
|
+
stepIndex++;
|
|
265
|
+
await writeFile(resolve(stage,inName),sourceBytes);
|
|
266
|
+
const prepTool=requireNativeTool('prep');
|
|
267
|
+
const prepReport=JSON.parse((await runTool(prepTool.command,[...prepTool.prefixArgs,stage,inName,prepOutDir,JSON.stringify({outputPrefix:'fit',maxSide})],{timeout:60000,maxBuffer:1048576})).stdout);
|
|
268
|
+
const preppedRel=`${prepOutDir}/${prepReport.outputs[0].file}`;
|
|
269
|
+
const optTool=requireNativeTool('optimize');
|
|
270
|
+
const optReport=JSON.parse((await runTool(optTool.command,[...optTool.prefixArgs,stage,preppedRel,optOut,JSON.stringify({mode:'auto',preserveResolution:false})],{timeout:60000,maxBuffer:1048576})).stdout);
|
|
271
|
+
const fitted=await readFile(resolve(stage,optOut));
|
|
272
|
+
if(fitted.length>=current.bytes)continue;
|
|
273
|
+
const fittedHash=hash(fitted);
|
|
274
|
+
workingAssets[idx]={...current,data:fitted.toString('base64'),bytes:fitted.length,hash:fittedHash,mime:optReport.mime??current.mime};
|
|
275
|
+
steps.push({assetId,kind:'image',source,fromBytes:current.bytes,toBytes:fitted.length,fittedHash,maxSide});
|
|
276
|
+
try{return await compileNative(makeProject(),{assets:workingAssets,target,sourceContentHash:origContentHash,optimizationReport:makeReport()});}
|
|
277
|
+
catch(error){if(error.message!=='E_UPLOAD_SIZE')throw error;}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}finally{await rm(stage,{recursive:true,force:true});}
|
|
281
|
+
return compileNative(makeProject(),{assets:workingAssets,target,sourceContentHash:origContentHash,optimizationReport:makeReport()});
|
|
282
|
+
}
|
|
283
|
+
async build(id,project,target='standalone-browser-draft',{fitTargetBudget=false,preLoweredAssets}={}){
|
|
284
|
+
const assets=preLoweredAssets??await lowerAssets(resolve(this.store.root,id),project.assets);
|
|
285
|
+
check(Array.isArray(assets)&&assets.length===project.assets.length&&assets.every((asset,index)=>asset.id===project.assets[index].id&&asset.hash===project.assets[index].hash&&asset.bytes===project.assets[index].bytes&&asset.mime===project.assets[index].mime&&typeof asset.data==='string'),'E_NATIVE_ASSET');
|
|
286
|
+
const runtimeHash=hash(projectUses3d(project)?await runtime3dBundle():await runtimeBundle()),key=buildCacheKey({project,target,runtimeHash,fitPolicyKey:fitTargetBudget?'fit-v1':'standard',deliveredAssetHashes:assets.map(a=>a.hash)});
|
|
287
|
+
return this.buildCache.getOrBuild(key,()=>fitTargetBudget?this.fitToTarget(id,project,assets,target):compileNative(project,{assets,target}));
|
|
104
288
|
}
|
|
105
289
|
async render(id,revisionId){check(typeof revisionId==='string','E_NATIVE_ARGUMENT');const {project}=await this.read(id,revisionId),assets=await lowerAssets(resolve(this.store.root,id),project.assets),artifact=await compileNative(project,{assets});return {assets,artifact:artifact.manifest};}
|
|
106
|
-
async upload(id,{expected,asset,provenance}
|
|
107
|
-
|
|
290
|
+
async upload(id,{expected,asset,provenance},source){
|
|
291
|
+
const result=await this.uploadBatch(id,{expected,assets:[{...asset,...(provenance?{provenance}:{})}]},source);
|
|
292
|
+
const {assets,...revision}=result;
|
|
293
|
+
return {...revision,asset:assets[0]};
|
|
294
|
+
}
|
|
295
|
+
async uploadBatch(id,{expected,assets},source={}){
|
|
108
296
|
check(Array.isArray(assets)&&assets.length>=1&&assets.length<=32,'E_NATIVE_ARGUMENT');
|
|
109
297
|
check(expected&&exact(expected,['revisionId','contentHash']),'E_NATIVE_ENVELOPE');
|
|
110
298
|
const ids=assets.map(item=>item?.id);
|
|
111
299
|
check(new Set(ids).size===ids.length,'E_NATIVE_DUPLICATE');
|
|
112
300
|
const current=await this.read(id);
|
|
113
301
|
check(expected.revisionId===current.revisionId&&expected.contentHash===current.contentHash,'E_NATIVE_STALE');
|
|
114
|
-
assertSingleVisualStyleFamily(current.project.assets,assets);
|
|
115
302
|
const projectRoot=resolve(this.store.root,id);
|
|
116
|
-
const registered=await mapWithConcurrency(assets,4,async item=>{
|
|
117
|
-
const input=
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
return
|
|
303
|
+
const registered=await mapWithConcurrency(assets,4,async (item,index)=>{
|
|
304
|
+
const {provenance,sourceHash,useOriginal,...input}=item;
|
|
305
|
+
const filePath=source.filePaths?.[index];
|
|
306
|
+
check([Boolean(filePath),Boolean(input.data),Boolean(sourceHash),useOriginal===true].filter(Boolean).length===1,'E_NATIVE_ASSET');
|
|
307
|
+
const opts=provenance?{provenance}:{};
|
|
308
|
+
if(filePath)return registerSourceFromFile(projectRoot,source.workspaceRoot,filePath,input,{...opts,preparedProvenance:resolvePreparedProvenance});
|
|
309
|
+
if(sourceHash||useOriginal){
|
|
310
|
+
const lineage=(await readRevisionLineage(projectRoot,expected.revisionId))[input.id];
|
|
311
|
+
const originalHash=sourceHash??lineage?.originalHash;
|
|
312
|
+
if(!originalHash||useOriginal&&!lineage?.masterAvailable)throw Error('E_ASSET_ORIGINAL_UNAVAILABLE');
|
|
313
|
+
if(useOriginal)input.mime=lineage.originalMime;
|
|
314
|
+
const bytes=await readOriginal(projectRoot,originalHash).catch(error=>{
|
|
315
|
+
if(error.code==='ENOENT')throw Error('E_ASSET_ORIGINAL_UNAVAILABLE',{cause:error});
|
|
316
|
+
throw error;
|
|
317
|
+
});
|
|
318
|
+
check(hash(bytes)===originalHash,'E_NATIVE_ASSET_HASH');
|
|
319
|
+
if(!provenance&&lineage?.originalHash===originalHash){
|
|
320
|
+
opts.provenance=current.project.assets.find(asset=>asset.id===input.id)?.provenance;
|
|
321
|
+
}
|
|
322
|
+
if(lineage?.dependencyManifestHash&&lineage.originalHash===originalHash)opts.dependencyManifestHash=lineage.dependencyManifestHash;
|
|
323
|
+
return registerSourceBytes(projectRoot,input,bytes,opts);
|
|
324
|
+
}
|
|
325
|
+
return registerSource(projectRoot,input,opts);
|
|
122
326
|
});
|
|
327
|
+
assertSingleVisualStyleFamily(current.project.assets,registered);
|
|
123
328
|
const existingIds=new Set(current.project.assets.map(a=>a.id));
|
|
124
329
|
const operations=registered.map(metadata=>{
|
|
125
330
|
const {optimization,...record}=metadata;void optimization;
|
|
@@ -127,57 +332,151 @@ export class NativeService{
|
|
|
127
332
|
});
|
|
128
333
|
const envelope={format:'tora-transaction-1',expected,operations};
|
|
129
334
|
const preview=await this.preview(id,envelope);
|
|
130
|
-
const committed=await this.transact(id,{...envelope,previewDigest:preview.previewDigest});
|
|
335
|
+
const committed=await this.transact(id,{...envelope,previewDigest:preview.previewDigest},{registeredAssets:registered});
|
|
131
336
|
return {...committed,assets:registered.map(({optimization,...record})=>({...record,...(optimization?{optimization}:{})}))};
|
|
132
337
|
}
|
|
133
|
-
async runQa(id,{revisionId,target='standalone-browser-draft',outputDir,motionFilmstrip=true,recordVideo=false}={}){
|
|
134
|
-
assertNetworkTarget(target);
|
|
135
|
-
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
const artifact=await this.build(id,
|
|
139
|
-
const isDefaultRunner=this.qaRunner===defaultQaRunner;
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
338
|
+
async runQa(id,{revisionId,target='standalone-browser-draft',outputDir,motionFilmstrip=true,recordVideo=false,artifact:prebuiltArtifact,fitTargetBudget=false,reuseVideoReceipt=false,variantId,project:projectOverride,variant,expectedCopyChecks,preLoweredAssets,confirmReviewed,browserProvider}={}){
|
|
339
|
+
assertNetworkTarget(target);const current=await this.read(id,revisionId);let selected;
|
|
340
|
+
if(!projectOverride&&variantId)selected=await this.selectVariant(id,current,variantId);
|
|
341
|
+
const project=projectOverride??selected?.project??current.project;
|
|
342
|
+
variant??=selected?.variant;expectedCopyChecks??=expectedCopyFor(project,variant);
|
|
343
|
+
const artifact=prebuiltArtifact??await this.build(id,project,target,{fitTargetBudget,preLoweredAssets}),artifactHash=artifact.manifest.artifactHash,packagedCheck=confirmReviewed!==undefined?await this.verifyPackagedArtifact(id,artifact,target,{confirmReviewed}):undefined;
|
|
344
|
+
const isDefaultRunner=this.qaRunner===defaultQaRunner,cacheEnabled=this.useVerifyCache??isDefaultRunner;
|
|
345
|
+
const qaRoot=resolve(this.store.root,id,'qa'),byArtifactRoot=resolve(qaRoot,'by-artifact');await mkdir(byArtifactRoot,{recursive:true});
|
|
346
|
+
let browserVersion,receiptKey,scenarioHash;
|
|
347
|
+
const scenario=qaScenarioTag({motionFilmstrip,recordVideo})+(fitTargetBudget?';fit=1':'')+(expectedCopyChecks?';copy='+hash(canonical(expectedCopyChecks)):'');
|
|
348
|
+
if(cacheEnabled)browserVersion=await getPlaywrightBrowserVersion();
|
|
349
|
+
const checkerVersion=`${CREATIVE_QA_CHECKER_VERSION}:${browserVersion??'not-loaded'}`;
|
|
350
|
+
scenarioHash=hash(canonical({artifactHash,target,checkerVersion,scenario}));
|
|
351
|
+
const immutableDir=resolve(byArtifactRoot,`${artifactHash.slice(7,23)}-${scenarioHash.slice(7,19)}`),resolvedOut=resolve(outputDir??immutableDir);
|
|
352
|
+
const keyFor=video=>this.verifyCache.receiptKey({artifactHash,checkerVersion:`${CREATIVE_QA_CHECKER_VERSION}:${browserVersion}`,kind:'creative-qa',host:target,scenario:qaScenarioTag({motionFilmstrip,recordVideo:video})+(fitTargetBudget?';fit=1':'')+(expectedCopyChecks?';copy='+hash(canonical(expectedCopyChecks)):''),qaTier:'full'});
|
|
143
353
|
if(cacheEnabled){
|
|
144
|
-
|
|
145
|
-
receiptKey
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
if(await verifyAndCopyQaArtifacts(cached.outputDir,resolvedOut,cached.report,{motionFilmstrip,recordVideo,isDefaultRunner})){
|
|
149
|
-
return {...cached.report,cacheHit:true};
|
|
150
|
-
}
|
|
354
|
+
receiptKey=keyFor(recordVideo);
|
|
355
|
+
for(const key of [receiptKey,...(reuseVideoReceipt&&!recordVideo?[keyFor(true)]:[])]){
|
|
356
|
+
const cached=await this.verifyCache.read(key);
|
|
357
|
+
if(cached?.report?.ok!==true||cached.report.format!==CREATIVE_QA_FORMAT||typeof cached.outputDir!=='string'||!resolve(cached.outputDir).startsWith(byArtifactRoot+sep))continue;
|
|
358
|
+
if(await verifyAndCopyQaArtifacts(cached.outputDir,resolvedOut,cached.report,{motionFilmstrip,recordVideo,isDefaultRunner}))return {...cached.report,artifactHash,outputDir:resolvedOut,immutableOutputDir:cached.outputDir,cacheHit:true,...(packagedCheck?{artifactCheck:packagedCheck}:{})};
|
|
151
359
|
}
|
|
152
360
|
}
|
|
153
|
-
const
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
await
|
|
179
|
-
|
|
361
|
+
const stage=await mkdtemp(resolve(qaRoot,'.stage-'));
|
|
362
|
+
try{
|
|
363
|
+
let report,lastError;
|
|
364
|
+
for(let attempt=0;attempt<2;attempt++){
|
|
365
|
+
const browser=isDefaultRunner&&(this.browserProvider??browserProvider)?await (this.browserProvider??browserProvider)():undefined;
|
|
366
|
+
try{report=await this.qaRunner({html:artifact.html,project,outputDir:stage,network:target,motionFilmstrip,recordVideo,...(expectedCopyChecks?{expectedCopyChecks}:{}),...(browser?{browser}:{})});lastError=undefined;break;}
|
|
367
|
+
catch(error){lastError=error;if(!isDefaultRunner||attempt||!/disconnect|closed|crash/i.test(error?.message??''))throw error;}
|
|
368
|
+
}
|
|
369
|
+
if(lastError)throw lastError;
|
|
370
|
+
let stampedReport={...report,artifactHash};await writeFile(resolve(stage,'report.json'),JSON.stringify(report));
|
|
371
|
+
if(report?.ok!==true||!qaReportSatisfiesOptions(report,{motionFilmstrip,recordVideo,isDefaultRunner})){const failureDir=await copyFailedQaArtifacts(stage,outputDir?resolvedOut:resolve(qaRoot,'failures',randomUUID()),report);return {...stampedReport,outputDir:failureDir,cacheHit:false,...(packagedCheck?{artifactCheck:packagedCheck}:{})};}
|
|
372
|
+
if(!await verifyAndCopyQaArtifacts(stage,stage,report,{motionFilmstrip,recordVideo,isDefaultRunner}))throw Error('E_QA_EVIDENCE_HASH');
|
|
373
|
+
await withProjectFileLock(resolve(byArtifactRoot,'.publish.lock'),async()=>{
|
|
374
|
+
try{await rename(stage,immutableDir);}
|
|
375
|
+
catch(error){
|
|
376
|
+
if(!['EEXIST','ENOTEMPTY','EPERM'].includes(error.code))throw error;
|
|
377
|
+
let existing;try{existing=JSON.parse(await readFile(resolve(immutableDir,'report.json'),'utf8'));}catch{existing=null;}
|
|
378
|
+
if(existing?.ok===true&&await verifyAndCopyQaArtifacts(immutableDir,immutableDir,existing,{motionFilmstrip,recordVideo,isDefaultRunner})){report=existing;stampedReport={...report,artifactHash};}
|
|
379
|
+
else{
|
|
380
|
+
const corrupt=resolve(byArtifactRoot,'.corrupt-'+randomUUID());await rename(immutableDir,corrupt);
|
|
381
|
+
try{await rename(stage,immutableDir);await rm(corrupt,{recursive:true,force:true});}catch(publishError){await rename(corrupt,immutableDir).catch(()=>{});throw publishError;}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if(cacheEnabled&&receiptKey){await this.verifyCache.write(receiptKey,{report:stampedReport,outputDir:immutableDir});await this.verifyCache.pruneOrphanedArtifactDirs(byArtifactRoot);}
|
|
385
|
+
});
|
|
386
|
+
if(!await verifyAndCopyQaArtifacts(immutableDir,resolvedOut,stampedReport,{motionFilmstrip,recordVideo,isDefaultRunner}))throw Error('E_QA_EVIDENCE_HASH');
|
|
387
|
+
return {...stampedReport,outputDir:resolvedOut,immutableOutputDir:immutableDir,cacheHit:false,...(packagedCheck?{artifactCheck:packagedCheck}:{})};
|
|
388
|
+
}finally{await rm(stage,{recursive:true,force:true});}
|
|
389
|
+
}
|
|
390
|
+
async verifyPackagedArtifact(id,artifact,target,{confirmReviewed}={}){
|
|
391
|
+
const networkTarget=assertNetworkTarget(target);if(networkTarget.hostKind==='browser')return {technicalStatus:'PASS',ruleVerificationStatus:'not-applicable',ruleReviewStatus:'not-applicable',status:'DRAFT',cacheHit:false};
|
|
392
|
+
check(confirmReviewed===undefined||typeof confirmReviewed==='string'&&/^\d{4}-\d{2}-\d{2}$/.test(confirmReviewed),'E_NATIVE_ARGUMENT');
|
|
393
|
+
const payload=Buffer.from(artifact.archiveBytes??artifact.html),artifactHash=artifact.manifest.artifactHash,filename=deliveryFilename(id,artifact,target);
|
|
394
|
+
check(hash(payload)===artifactHash,'E_ARTIFACT_CHECK');
|
|
395
|
+
const tool=requireNativeTool('cli'),checkerVersion=await nativeBinaryHash(tool.command),reviewedOn=new Date().toISOString().slice(0,10),key=this.verifyCache.receiptKey({artifactHash,checkerVersion,artifactCheckVersion:'playable-artifact-check-1',kind:'packaged-artifact',host:target,scenario:canonical({confirmReviewed:confirmReviewed??'',reviewedOn}),qaTier:'full'});
|
|
396
|
+
const valid=cached=>cached?.artifactHash===artifactHash&&cached.filename===filename&&cached.report?.technicalStatus==='PASS'&&cached.report.fileBytes===payload.length&&(!confirmReviewed||cached.report.status==='STATIC_PASS');
|
|
397
|
+
const cached=await this.verifyCache.read(key);if(valid(cached))return {...cached,cacheHit:true};
|
|
398
|
+
const qaRoot=resolve(this.store.root,id,'qa');await mkdir(qaRoot,{recursive:true});const stage=await mkdtemp(resolve(qaRoot,'.artifact-'));
|
|
399
|
+
try{
|
|
400
|
+
const stagedPath=resolve(stage,filename);await writeFile(stagedPath,payload,{flag:'wx'});
|
|
401
|
+
const args=[...tool.prefixArgs,'artifact','check',stagedPath,'--network',target,...(confirmReviewed?['--confirm-reviewed',confirmReviewed]:[]),'--json'];
|
|
402
|
+
let stdout,exitCode=0;try{stdout=(await runTool(tool.command,args,{timeout:120000,maxBuffer:4*1024*1024})).stdout;}catch(error){stdout=error.stdout;exitCode=typeof error.code==='number'?error.code:-1;if(!stdout)throw artifactCheckFailure(null,error);}
|
|
403
|
+
let report;try{report=JSON.parse(stdout);}catch(error){throw artifactCheckFailure(null,error);}
|
|
404
|
+
if(exitCode===5||report.technicalStatus!=='PASS'||![0,6].includes(exitCode)||confirmReviewed&&(exitCode!==0||report.status!=='STATIC_PASS'))throw artifactCheckFailure(report);
|
|
405
|
+
check(report.fileBytes===payload.length,'E_ARTIFACT_CHECK');
|
|
406
|
+
const result={artifactHash,filename,checkerVersion,report,ruleReviewStatus:report.status,ruleVerificationStatus:networkTarget.ruleVerificationStatus};
|
|
407
|
+
await this.verifyCache.write(key,result);return {...result,cacheHit:false};
|
|
408
|
+
}finally{await rm(stage,{recursive:true,force:true});}
|
|
409
|
+
}
|
|
410
|
+
async selectVariant(id,current,variantId){
|
|
411
|
+
if(variantId===undefined||variantId==='base')return {project:globalThis.structuredClone(current.project),variant:undefined,store:await readVariants(resolve(this.store.root,id),current.project)};
|
|
412
|
+
const store=await readVariants(resolve(this.store.root,id),current.project),variant=store.variants.find(item=>item.id===variantId);check(variant,'E_NATIVE_NOT_FOUND');
|
|
413
|
+
const report=validateVariantStore(store,current.project,{failOnOrphans:false,failOnIncomplete:false});
|
|
414
|
+
const issues=[...report.orphans,...report.incomplete].filter(item=>item.variantId===variantId);check(!issues.length,'E_NATIVE_VARIANT',{issues});
|
|
415
|
+
return {project:materializeVariant(current.project,variant),variant,store};
|
|
416
|
+
}
|
|
417
|
+
async listVariants(id){
|
|
418
|
+
const current=await this.read(id),store=await readVariants(resolve(this.store.root,id),current.project),validation=validateVariantStore(store,current.project,{failOnOrphans:false,failOnIncomplete:false}),localizable=extractLocalizableStrings(current.project),visible=visibleStringVariables(current.project);
|
|
419
|
+
localizable.variables=Object.fromEntries(current.project.variables.filter(variable=>variable.type==='string'&&visible.has(variable.id)).map(variable=>[variable.id,variable.initial]));
|
|
420
|
+
return {...store,hash:variantStoreHash(store),diagnostics:[...validation.diagnostics,...validation.orphans,...validation.incomplete],localizable,baseRevisionId:current.revisionId,baseContentHash:current.contentHash};
|
|
421
|
+
}
|
|
422
|
+
async upsertVariant(id,variant,{expectedVariantRevision}={}){
|
|
423
|
+
const current=await this.read(id),store=await updateVariants(resolve(this.store.root,id),current.project,expectedVariantRevision,current=>{const index=current.variants.findIndex(item=>item.id===variant?.id);if(index<0)current.variants.push(variant);else current.variants[index]=variant;return current;});
|
|
424
|
+
return {...store,hash:variantStoreHash(store),variant:store.variants.find(item=>item.id===variant.id)};
|
|
425
|
+
}
|
|
426
|
+
async deleteVariant(id,variantId,{expectedVariantRevision}={}){
|
|
427
|
+
const current=await this.read(id);check(typeof variantId==='string'&&variantId!=='base','E_NATIVE_ARGUMENT');
|
|
428
|
+
const store=await updateVariants(resolve(this.store.root,id),current.project,expectedVariantRevision,current=>{check(current.variants.some(item=>item.id===variantId),'E_NATIVE_NOT_FOUND');current.variants=current.variants.filter(item=>item.id!==variantId);return current;});return {...store,hash:variantStoreHash(store)};
|
|
429
|
+
}
|
|
430
|
+
async diffVariant(id,variantId,{revisionId}={}){const current=await this.read(id,revisionId),selected=await this.selectVariant(id,current,variantId);return {projectId:id,variantId:variantId??'base',variant:selected.variant,project:selected.project,baseRevisionId:current.revisionId,baseContentHash:current.contentHash,variantStoreHash:variantStoreHash(selected.store)};}
|
|
431
|
+
async createPresetVariant(id,input){
|
|
432
|
+
const {action,expectedVariantRevision,...presetInput}=input;void action;
|
|
433
|
+
const current=await this.read(id),descriptor=variantAdapterForProject(current.project),useModulePreset=presetInput.preset!=='locale'&&descriptor?.variantPreset,generated=useModulePreset?descriptor.variantPreset(presetInput.preset):{},base=createPresetOverlay(current.project,presetInput),overlay={...generated};delete overlay.id;delete overlay.label;delete overlay.preset;
|
|
434
|
+
const variant=useModulePreset?{id:base.id,label:base.label,preset:base.preset,...overlay}:{...base,...overlay};
|
|
435
|
+
return this.upsertVariant(id,variant,{expectedVariantRevision});
|
|
436
|
+
}
|
|
437
|
+
async estimateBudget(id,{target='standalone-browser-draft',variantId,revisionId,fitTargetBudget=false}={}){
|
|
438
|
+
const networkTarget=assertNetworkTarget(target),current=await this.read(id,revisionId),selected=await this.selectVariant(id,current,variantId),project=selected.project,assets=await lowerAssets(resolve(this.store.root,id),project.assets),runtime=projectUses3d(project)?await runtime3dBundle():await runtimeBundle(),runtimeHash=hash(runtime),key=buildCacheKey({project,target,runtimeHash,fitPolicyKey:fitTargetBudget?'fit-v1':'standard',deliveredAssetHashes:assets.map(asset=>asset.hash)}),cached=this.buildCache.peek(key);
|
|
439
|
+
const measured=cached?.manifest?.budget,html=measured?null:playableHTML({...project,assets},runtime,target==='standalone-browser-draft'?{}:{network:target}),budget=measured??exportBudget(project,assets,runtime,networkTarget,Buffer.byteLength(html),Buffer.byteLength(html)),status=!acceptsTargetBytes(networkTarget,budget.totalBytes)?'over':networkTarget.maxBytes!==null&&budget.totalBytes>=networkTarget.maxBytes*.95?'tight':'ok';
|
|
440
|
+
return {...budget,target,variantId:variantId??'base',fitTargetBudget,measurement:measured?'measured':'estimated',...(measured||networkTarget.packaging!=='zip'?{}:{estimateBasis:'uncompressed-html'}),status,unusedAssetCount:budget.perAsset.filter(asset=>asset.unused).length,topAssets:[...budget.perAsset].sort((a,b)=>b.rawBytes-a.rawBytes||a.id.localeCompare(b.id)).slice(0,3)};
|
|
441
|
+
}
|
|
442
|
+
async verifyExportEntry(id,current,project,target,{fitTargetBudget=false,confirmReviewed,preLoweredAssets,variant,expectedCopyChecks,browserProvider}={}){
|
|
443
|
+
const artifact=await this.build(id,project,target,{fitTargetBudget,preLoweredAssets}),[artifactCheck,creativeQaResult]=await Promise.all([this.verifyPackagedArtifact(id,artifact,target,{confirmReviewed}),this.runQa(id,{revisionId:current.revisionId,target,artifact,fitTargetBudget,reuseVideoReceipt:true,project,variant,preLoweredAssets,expectedCopyChecks,browserProvider})]),creativeQa=requireCreativeQa(creativeQaResult);
|
|
444
|
+
check(creativeQa.artifactHash===artifact.manifest.artifactHash,'E_CREATIVE_QA_HASH_MISMATCH');
|
|
445
|
+
const checks=[...artifact.manifest.checks,'creative-qa',...(target==='standalone-browser-draft'?[]:['rust-artifact-check'])];
|
|
446
|
+
return {target,artifact,creativeQa,artifactCheck,manifest:{...artifact.manifest,...(variant?{variantId:variant.id}:{}),accepted:current.accepted,creativeQa:{format:CREATIVE_QA_FORMAT,ok:true,blockers:0,warnings:creativeQa.warnings.length,artifactHash:creativeQa.artifactHash,evidencePath:creativeQa.immutableOutputDir},artifactCheck:{technicalStatus:artifactCheck.report?.technicalStatus??'PASS',ruleReviewStatus:artifactCheck.ruleReviewStatus,ruleVerificationStatus:artifactCheck.ruleVerificationStatus,artifactHash:artifact.manifest.artifactHash},checks}};
|
|
447
|
+
}
|
|
448
|
+
async export(id,{revisionId,target,fitTargetBudget=false,variantId,confirmReviewed}){
|
|
449
|
+
check(typeof revisionId==='string','E_NATIVE_ARGUMENT');assertNetworkTarget(target);const current=await this.read(id,revisionId),selected=await this.selectVariant(id,current,variantId),verified=await this.verifyExportEntry(id,current,selected.project,target,{fitTargetBudget,confirmReviewed,variant:selected.variant});return {...verified.artifact,creativeQa:verified.creativeQa,artifactCheck:verified.artifactCheck,manifest:verified.manifest};
|
|
450
|
+
}
|
|
451
|
+
async exportBatch(id,{revisionId,targets,outputDir,fitTargetBudget=false,confirmReviewed,variantId}){
|
|
452
|
+
check(Array.isArray(targets)&&targets.length>=1&&targets.length<=8&&new Set(targets).size===targets.length,'E_NATIVE_ARGUMENT');check(typeof outputDir==='string'&&outputDir.length>0,'E_AGENT_OUTPUT');for(const target of targets)assertNetworkTarget(target);
|
|
453
|
+
const current=await this.read(id,revisionId),selected=await this.selectVariant(id,current,variantId),preLoweredAssets=await lowerAssets(resolve(this.store.root,id),current.project.assets),resolvedDir=resolve(outputDir),browserProvider=this.browserProvider??getSharedBrowser;
|
|
454
|
+
if(!this.browserProvider)sharedBatchJobs++;
|
|
455
|
+
try{
|
|
456
|
+
const verified=await mapWithConcurrency(targets,defaultQaConcurrency(),target=>this.verifyExportEntry(id,current,selected.project,target,{fitTargetBudget,confirmReviewed,preLoweredAssets,variant:selected.variant,browserProvider}));
|
|
457
|
+
const exports=[];for(const row of verified){const filename=deliveryFilename(id,row.artifact,row.target),output=resolve(resolvedDir,row.target,filename);await writeAtomic(output,row.artifact.archiveBytes??row.artifact.html);exports.push({target:row.target,output,artifactHash:row.artifact.manifest.artifactHash,bytes:row.artifact.manifest.bytes,packaging:row.artifact.manifest.packaging,cacheHit:Boolean(row.creativeQa.cacheHit),artifactCheck:{technicalStatus:row.artifactCheck.report?.technicalStatus??'PASS',ruleReviewStatus:row.artifactCheck.ruleReviewStatus},evidencePath:row.creativeQa.immutableOutputDir});}
|
|
458
|
+
return {status:'EXPORTED',projectId:id,variantId:variantId??'base',expected:{revisionId:current.revisionId,contentHash:current.contentHash},outputDir:resolvedDir,exports};
|
|
459
|
+
}finally{if(!this.browserProvider&&--sharedBatchJobs===0)await closeSharedBrowser();}
|
|
460
|
+
}
|
|
461
|
+
async exportVariantMatrix(id,{revisionId,variants,targets,outputDir,fitTargetBudget=false,confirmReviewed,onProgress,expectedCopyChecks}={}){
|
|
462
|
+
check(Array.isArray(variants)&&variants.length>=1&&variants.length<=128&&new Set(variants).size===variants.length&&Array.isArray(targets)&&targets.length>=1&&targets.length<=8&&new Set(targets).size===targets.length,'E_NATIVE_ARGUMENT');check(typeof outputDir==='string'&&outputDir.length>0,'E_AGENT_OUTPUT');for(const target of targets)assertNetworkTarget(target);
|
|
463
|
+
const current=await this.read(id,revisionId),store=await readVariants(resolve(this.store.root,id),current.project),validation=validateVariantStore(store,current.project,{failOnOrphans:false,failOnIncomplete:false});check(validation.valid,'E_NATIVE_VARIANT',validation);
|
|
464
|
+
const resolvedIds=[];
|
|
465
|
+
for(const requested of variants){
|
|
466
|
+
if(requested==='all')for(const item of store.variants){if(!resolvedIds.includes(item.id))resolvedIds.push(item.id);}
|
|
467
|
+
else if(!resolvedIds.includes(requested))resolvedIds.push(requested);
|
|
180
468
|
}
|
|
181
|
-
|
|
469
|
+
check(resolvedIds.length>=1&&resolvedIds.length<=128,'E_NATIVE_ARGUMENT');
|
|
470
|
+
const pinned={baseRevisionId:current.revisionId,baseContentHash:current.contentHash,variantStoreRevision:store.revision,variantStoreHash:variantStoreHash(store)},materializedVariants=resolvedIds.map(variantId=>{
|
|
471
|
+
if(variantId==='base')return {variantId:'base',variant:undefined,project:globalThis.structuredClone(current.project)};
|
|
472
|
+
const variant=store.variants.find(item=>item.id===variantId);check(variant,'E_NATIVE_NOT_FOUND');
|
|
473
|
+
return {variantId,variant,project:materializeVariant(current.project,variant)};
|
|
474
|
+
}),preLoweredAssets=await lowerAssets(resolve(this.store.root,id),current.project.assets),jobs=materializedVariants.flatMap(({variantId,variant,project})=>targets.map(target=>({variantId,variant,project,target}))),resolvedDir=resolve(outputDir),browserProvider=this.browserProvider??getSharedBrowser;
|
|
475
|
+
if(!this.browserProvider)sharedBatchJobs++;
|
|
476
|
+
try{
|
|
477
|
+
const entries=await mapWithConcurrency(jobs,defaultQaConcurrency(),async job=>{onProgress?.({status:'started',variantId:job.variantId,target:job.target});try{const verified=await this.verifyExportEntry(id,current,job.project,job.target,{fitTargetBudget,confirmReviewed,preLoweredAssets,variant:job.variant,expectedCopyChecks:expectedCopyChecks?.[job.variantId],browserProvider});onProgress?.({status:'passed',variantId:job.variantId,target:job.target});return {...job,status:'PASS',...verified};}catch(error){onProgress?.({status:'failed',variantId:job.variantId,target:job.target,error:error.message});return {...job,status:'FAIL',error:error.message,creativeQa:error.creativeQa,artifactCheck:error.artifactCheck};}});
|
|
478
|
+
const passing=entries.filter(entry=>entry.status==='PASS'),exports=[];for(const entry of passing){const folder=resolve(resolvedDir,entry.variantId,entry.target),filename=deliveryFilename(id,entry.artifact,entry.target),output=resolve(folder,filename);await writeAtomic(output,entry.artifact.archiveBytes??entry.artifact.html);exports.push({variantId:entry.variantId,target:entry.target,output,artifactHash:entry.artifact.manifest.artifactHash,bytes:entry.artifact.manifest.bytes,evidencePath:entry.creativeQa.immutableOutputDir,artifactCheck:{technicalStatus:entry.artifactCheck.report?.technicalStatus??'PASS',ruleReviewStatus:entry.artifactCheck.ruleReviewStatus}});}
|
|
479
|
+
const failures=entries.filter(entry=>entry.status==='FAIL').map(entry=>({variantId:entry.variantId,target:entry.target,error:entry.error,blockers:entry.creativeQa?.blockers??entry.artifactCheck?.findings??[]})),summary={format:'tora-variant-matrix-1',status:failures.length?'FAILED':'EXPORTED',projectId:id,...pinned,outputDir:resolvedDir,exports,failures,entries:entries.map(entry=>({variantId:entry.variantId,target:entry.target,status:entry.status,artifactHash:entry.artifact?.manifest.artifactHash,error:entry.error}))};await writeAtomic(resolve(resolvedDir,'matrix-summary.json'),JSON.stringify(summary));return summary;
|
|
480
|
+
}finally{if(!this.browserProvider&&--sharedBatchJobs===0)await closeSharedBrowser();}
|
|
182
481
|
}
|
|
183
482
|
}
|