@tora-editor/tora 0.1.0 → 0.2.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 +108 -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 +77 -9
- package/crates/packer/trusted/native-3d-meta.json +3 -2
- package/crates/packer/trusted/native-3d.js +181 -181
- package/crates/packer/trusted/native-meta.json +2 -2
- 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 +3 -2
- package/crates/packer/trusted/review-runtime.js +182 -182
- package/docs/TORA_AGENT_SETUP.md +24 -13
- package/docs/TORA_CREATION_API.md +29 -12
- package/docs/reference/CORE_AUTHORING.md +2 -1
- package/docs/reference/PLAYABLE_STARTERS.md +20 -0
- package/docs/reference/packs/3d.md +9 -3
- package/network-rules/mintegral-appgrowth-single-html.json +10 -10
- package/package.json +6 -6
- package/packages/creative-project/project-v21.schema.json +264 -8
- package/scripts/lean/editor/review-editor.css +10 -0
- package/scripts/lean/editor/review-editor.js +117 -1
- package/scripts/lean/native/agent-tools.mjs +7 -7
- package/scripts/lean/native/api.mjs +16 -5
- 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/author-expansion-proofs.mjs +2 -99
- package/scripts/lean/native/author-fps.mjs +545 -0
- package/scripts/lean/native/author-primitive-proofs.mjs +5 -4
- package/scripts/lean/native/build-cache.mjs +2 -2
- package/scripts/lean/native/cc0-inputs.mjs +24 -0
- package/scripts/lean/native/cc0-staging.mjs +28 -8
- package/scripts/lean/native/check-harvest-outcome-audio.mjs +7 -8
- package/scripts/lean/native/check-salvage.mjs +8 -5
- package/scripts/lean/native/compiler.mjs +9 -3
- package/scripts/lean/native/contracts.mjs +11 -8
- package/scripts/lean/native/creative-qa.mjs +305 -122
- package/scripts/lean/native/demos.mjs +47 -3
- package/scripts/lean/native/document.mjs +36 -10
- package/scripts/lean/native/export-budget.mjs +75 -0
- package/scripts/lean/native/glb-loader.mjs +468 -0
- package/scripts/lean/native/intake-creator-tools.mjs +83 -30
- package/scripts/lean/native/local-bundle.mjs +5 -3
- package/scripts/lean/native/mcp-server.mjs +33 -46
- package/scripts/lean/native/media-validate.mjs +124 -0
- package/scripts/lean/native/native-bin.mjs +3 -3
- package/scripts/lean/native/outcome-playthrough.mjs +97 -0
- package/scripts/lean/native/prepare-fps-assets.mjs +330 -0
- package/scripts/lean/native/project-bundle.mjs +3 -3
- package/scripts/lean/native/remote-cc0-fetcher.mjs +403 -197
- package/scripts/lean/native/review-agent-tools.mjs +2 -2
- package/scripts/lean/native/review.mjs +3 -0
- package/scripts/lean/native/runtime.mjs +242 -56
- package/scripts/lean/native/schema.mjs +7 -5
- package/scripts/lean/native/service.mjs +159 -32
- package/scripts/lean/native/stage-3d.mjs +343 -40
- package/scripts/lean/native/starters.mjs +436 -0
- package/scripts/lean/native/verify.mjs +1 -1
- package/scripts/lean/native/win-cues.mjs +96 -0
- package/skills/tora-playables/SKILL.md +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Structural schema generated from the same property and behavior vocabulary as the editor. */
|
|
2
|
-
import {contracts,behaviors,limits} from './contracts.mjs';
|
|
2
|
+
import {contracts,behaviors,limits,mesh3dSlots} from './contracts.mjs';
|
|
3
3
|
const obj=(properties,optional=[])=>({type:'object',additionalProperties:false,properties,required:Object.keys(properties).filter(k=>!optional.includes(k))});
|
|
4
4
|
const str={type:'string',maxLength:512},id={type:'string',pattern:'^[a-z][a-z0-9_.-]{0,95}$'},num={type:'number',minimum:-9007199254740991,maximum:9007199254740991},scalar={oneOf:[num,{type:'boolean'},str]},array=(items,maxItems)=>({type:'array',items,maxItems});
|
|
5
5
|
const node=obj({id,x:{type:'number',minimum:-4096,maximum:4096},y:{type:'number',minimum:-4096,maximum:4096},holdSeconds:{type:'number',minimum:0,maximum:60},cost:{type:'number',minimum:0,maximum:1e6}},['holdSeconds','cost']);
|
|
@@ -25,12 +25,13 @@ const event={oneOf:[
|
|
|
25
25
|
obj({kind:{const:'swipe'},componentId:id,direction:{enum:['up','down','left','right']}},['direction']),
|
|
26
26
|
obj({kind:{const:'pathArrive'},componentId:id,nodeId:id},['nodeId']),obj({kind:{const:'jointBreak'},componentId:id,behaviorId:id}),
|
|
27
27
|
obj({kind:{const:'contactBegin'},componentId:id,otherId:id},['otherId']),
|
|
28
|
+
obj({kind:{const:'modelAnimationEnd'},componentId:id,clipName:{type:'string',maxLength:96}},['clipName']),
|
|
28
29
|
...['sceneEnter','sceneExit'].map(kind=>obj({kind:{const:kind},sceneId:id})),
|
|
29
30
|
obj({kind:{const:'timer'},behaviorId:id}),obj({kind:{const:'variableChange'},variableId:id}),
|
|
30
31
|
]};
|
|
31
32
|
for(const variant of event.oneOf){variant.properties={id,...variant.properties};variant.required.unshift('id');}
|
|
32
33
|
const action={oneOf:[
|
|
33
|
-
obj({kind:{const:'setComponent'},componentId:id,key:str,value:scalar,valueVariableId:id},['value','valueVariableId']),obj({kind:{const:'setAsset'},componentId:id,assetId:id}),obj({kind:{const:'copyMatchAsset'},componentId:id,boardId:id}),
|
|
34
|
+
obj({kind:{const:'setComponent'},componentId:id,key:str,value:scalar,valueVariableId:id},['value','valueVariableId']),obj({kind:{const:'setAsset'},componentId:id,assetId:id,slotId:{enum:mesh3dSlots}},['slotId']),obj({kind:{const:'copyMatchAsset'},componentId:id,boardId:id}),
|
|
34
35
|
...['resetMatch','hintMatch','clearStrokes','resetMask'].map(kind=>obj({kind:{const:kind},componentId:id})),
|
|
35
36
|
...['set','add'].map(kind=>obj({kind:{const:kind},variableId:id,value:kind==='add'?num:scalar})),
|
|
36
37
|
obj({kind:{const:'spawn'},prototypeId:id,x:num,y:num}),obj({kind:{const:'spawnAt'},prototypeId:id,targetComponentId:id,offsetX:num,offsetY:num,at:{enum:['target','self','other','midpoint','pointer']},jitterX:{type:'number',minimum:0,maximum:1024},jitterY:{type:'number',minimum:0,maximum:1024},count:{type:'integer',minimum:1,maximum:16},countVariableId:id},['at','jitterX','jitterY','count','countVariableId']),
|
|
@@ -45,11 +46,12 @@ const action={oneOf:[
|
|
|
45
46
|
obj({kind:{const:'random'},variableId:id,min:num,max:num,integer:{type:'boolean'}},['integer']),
|
|
46
47
|
obj({kind:{const:'modifyInstanceState'},target:{enum:['self','other','component']},componentId:id,field:{enum:['hp','value','tag']},op:{enum:['add','sub','set']},value:scalar,variableId:id},['componentId','value','variableId']),
|
|
47
48
|
obj({kind:{const:'launchToward'},componentId:id,targetMode:{enum:['pointer','component','nearest-team','angle-variable']},targetComponentId:id,team:{enum:['neutral','player','enemy','hazard','pickup']},angleVariableId:id,speed:{type:'number',minimum:1,maximum:4000},speedVariableId:id,orientToVelocity:{type:'boolean'}},['targetComponentId','team','angleVariableId','speed','speedVariableId','orientToVelocity']),
|
|
48
|
-
obj({kind:{const:'despawn'},target:{enum:['self','other','both']}},['target']),...['restart','store'].map(kind=>obj({kind:{const:kind}})),obj({kind:{const:'changeScene'},sceneId:id}),
|
|
49
|
+
obj({kind:{const:'despawn'},target:{enum:['self','other','both']}},['target']),...['restart','store'].map(kind=>obj({kind:{const:kind}})),obj({kind:{const:'changeScene'},sceneId:id,delaySeconds:{type:'number',minimum:0,maximum:limits.sceneChangeDelaySeconds}},['delaySeconds']),
|
|
49
50
|
obj({kind:{const:'cameraShake'},intensity:num,seconds:num}),obj({kind:{const:'screenFlash'},color:descriptor({type:'color'}),opacity:num,seconds:num}),
|
|
50
51
|
obj({kind:{const:'floatingText'},text:str,componentId:id,color:descriptor({type:'color'}),fontSize:num,risePx:num,seconds:num}),
|
|
51
52
|
obj({kind:{const:'raycast3d'},stageId:id,mode:{enum:['crosshair','pointer']},maxDistance:{type:'number',minimum:1,maximum:500},targetTeam:{enum:['any','neutral','player','enemy','hazard','pickup']}},['mode','maxDistance','targetTeam']),
|
|
52
|
-
obj({kind:{const:'spawnAt3d'},prototypeId:id,x:{type:'number',minimum:-500,maximum:500},y:{type:'number',minimum:-500,maximum:500},z:{type:'number',minimum:-500,maximum:500},jitterX:{type:'number',minimum:0,maximum:100},jitterZ:{type:'number',minimum:0,maximum:100},count:{type:'integer',minimum:1,maximum:16}},['jitterX','jitterZ','count']),
|
|
53
|
+
obj({kind:{const:'spawnAt3d'},prototypeId:id,fromComponentId:id,fromTeam:{enum:['any','neutral','player','enemy','hazard','pickup']},x:{type:'number',minimum:-500,maximum:500},y:{type:'number',minimum:-500,maximum:500},z:{type:'number',minimum:-500,maximum:500},offsetX:{type:'number',minimum:-50,maximum:50},offsetY:{type:'number',minimum:-50,maximum:50},offsetZ:{type:'number',minimum:-50,maximum:50},jitterX:{type:'number',minimum:0,maximum:100},jitterZ:{type:'number',minimum:0,maximum:100},count:{type:'integer',minimum:1,maximum:16}},['fromComponentId','fromTeam','x','y','z','offsetX','offsetY','offsetZ','jitterX','jitterZ','count']),
|
|
54
|
+
obj({kind:{const:'playModelAnimation'},componentId:id,clipName:{type:'string',maxLength:96},loop:{enum:['repeat','once','pingpong']},speed:{type:'number',minimum:0,maximum:4},fadeSeconds:{type:'number',minimum:0,maximum:2},restart:{type:'boolean'}},['loop','speed','fadeSeconds','restart']),
|
|
53
55
|
...['animate','stopAnimation','emit','playAudio'].map(kind=>obj({kind:{const:kind},behaviorId:id})),
|
|
54
56
|
]};
|
|
55
|
-
export const nativeSchema={$schema:'https://json-schema.org/draft/2020-12/schema',$id:'urn:tora:creative-project:2.1.0',title:'Creative Project 2.1 native scene',...obj({schemaVersion:{const:'2.1.0'},projectId:id,revisionId:{type:'string',minLength:1,maxLength:128},generationOrigin:{const:'human-authored'},creativeBrief:obj({goal:{type:'string',minLength:1,maxLength:2048},language:{const:'en'}}),base:obj({kind:{const:'native-scene'},runtimeId:{const:'tora-native'},runtimeVersion:{const:'1.0.0'},width:{type:'number',minimum:240,maximum:2048},height:{type:'number',minimum:240,maximum:2048},startScene:id,storeUrl:{type:'string',pattern:'^$|^https://(play\\.google\\.com/store/apps/details\\?id=[a-zA-Z0-9._-]+|apps\\.apple\\.com/[a-zA-Z0-9/._?=&-]+)$'}}),scenes:{...array(obj({id,label:{type:'string',maxLength:80},role:{enum:['interactive','end-card']}}),16),minItems:1},components:array({oneOf:Object.values(contracts).map(c=>obj({id,label:{type:'string',maxLength:80},contract:{const:c.id},sceneId:id,parentId:id,order:num,transform:matrix,parameters:specs(c.properties),assetSlots:array(obj({slotId:{const:'source'},assetId:id}),1),prototype:{type:'boolean'}},['parentId']))},limits.components),variables:array({oneOf:['number','boolean','string'].map(type=>obj({id,label:{type:'string',maxLength:80},type:{const:type},initial:type==='number'?num:type==='boolean'?{type}:str}))},limits.variables),gameplay:array({oneOf:Object.entries(behaviors).map(([kind,params])=>obj({id,componentId:id,kind:{const:kind},parameters:specs(params)}))},limits.gameplay),events:array(event,384),eventBindings:array(obj({id,eventId:id,condition:ref('Condition'),actions:{...array(action,32),minItems:1}},['condition']),limits.eventBindings),assets:array(obj({id,hash:{type:'string',pattern:'^sha256:[a-f0-9]{64}$'},mime:{enum:['image/png','image/jpeg','audio/wav','audio/mpeg','model/tora-mesh']},bytes:{type:'integer',minimum:1,maximum:1048576},rights:{type:'string',minLength:1,maxLength:2048},provenance:{type:'string',minLength:1,maxLength:2048}},['provenance']),256),tombstones:{...array(id,4096),uniqueItems:true}}),$defs:{Condition:condition}};
|
|
57
|
+
export const nativeSchema={$schema:'https://json-schema.org/draft/2020-12/schema',$id:'urn:tora:creative-project:2.1.0',title:'Creative Project 2.1 native scene',...obj({schemaVersion:{const:'2.1.0'},projectId:id,revisionId:{type:'string',minLength:1,maxLength:128},generationOrigin:{const:'human-authored'},creativeBrief:obj({goal:{type:'string',minLength:1,maxLength:2048},language:{const:'en'}}),base:obj({kind:{const:'native-scene'},runtimeId:{const:'tora-native'},runtimeVersion:{const:'1.0.0'},width:{type:'number',minimum:240,maximum:2048},height:{type:'number',minimum:240,maximum:2048},startScene:id,storeUrl:{type:'string',pattern:'^$|^https://(play\\.google\\.com/store/apps/details\\?id=[a-zA-Z0-9._-]+|apps\\.apple\\.com/[a-zA-Z0-9/._?=&-]+)$'}}),scenes:{...array(obj({id,label:{type:'string',maxLength:80},role:{enum:['interactive','end-card']}}),16),minItems:1},components:array({oneOf:Object.values(contracts).map(c=>obj({id,label:{type:'string',maxLength:80},contract:{const:c.id},sceneId:id,parentId:id,order:num,transform:matrix,parameters:specs(c.properties),assetSlots:c.id==='native.mesh3d.v1'?array(obj({slotId:{enum:mesh3dSlots},assetId:id}),4):array(obj({slotId:{const:'source'},assetId:id}),1),prototype:{type:'boolean'}},['parentId']))},limits.components),variables:array({oneOf:['number','boolean','string'].map(type=>obj({id,label:{type:'string',maxLength:80},type:{const:type},initial:type==='number'?num:type==='boolean'?{type}:str}))},limits.variables),gameplay:array({oneOf:Object.entries(behaviors).map(([kind,params])=>obj({id,componentId:id,kind:{const:kind},parameters:specs(params)}))},limits.gameplay),events:array(event,384),eventBindings:array(obj({id,eventId:id,condition:ref('Condition'),actions:{...array(action,32),minItems:1}},['condition']),limits.eventBindings),assets:array(obj({id,hash:{type:'string',pattern:'^sha256:[a-f0-9]{64}$'},mime:{enum:['image/png','image/jpeg','audio/wav','audio/mpeg','model/tora-mesh','model/gltf-binary']},bytes:{type:'integer',minimum:1,maximum:1048576},rights:{type:'string',minLength:1,maxLength:2048},provenance:{type:'string',minLength:1,maxLength:2048}},['provenance']),256),tombstones:{...array(id,4096),uniqueItems:true}}),$defs:{Condition:condition}};
|
|
@@ -1,10 +1,15 @@
|
|
|
1
|
-
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} from 'node:fs/promises';
|
|
2
5
|
import {resolve,dirname} 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';
|
|
@@ -12,6 +17,15 @@ import {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
|
+
const runTool=promisify(execFile);
|
|
22
|
+
const MODEL_FIT_LADDER=Object.freeze([
|
|
23
|
+
{maxTextureSide:256,targetBytes:180000},
|
|
24
|
+
{maxTextureSide:192,targetBytes:110000},
|
|
25
|
+
{maxTextureSide:128,targetBytes:64000},
|
|
26
|
+
{maxTextureSide:96,targetBytes:36000},
|
|
27
|
+
]);
|
|
28
|
+
const IMAGE_FIT_SIDES=Object.freeze([512,384,256,160]);
|
|
15
29
|
const PREAPPLY_AUDIO_BLOCKERS=new Set(['audio-role-mismatch','audio-valence-mismatch','audio-win-loss-duplicate','audio-contour-mismatch','audio-clipping']);
|
|
16
30
|
export const contentHash=p=>hash('tora-v2-hash/1\ndocument-content\n'+canonical(projectContent(p)));
|
|
17
31
|
export function requireCreativeQa(report){
|
|
@@ -65,7 +79,7 @@ export class NativeService{
|
|
|
65
79
|
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
80
|
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
81
|
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}={}){
|
|
82
|
+
async transact(id,envelope,{guard,record,registeredAssets=[]}={}){
|
|
69
83
|
const preview=await this.preview(id,envelope);
|
|
70
84
|
check(envelope.previewDigest===preview.previewDigest,'E_NATIVE_PREVIEW_STALE');
|
|
71
85
|
const project=preview.project;
|
|
@@ -87,6 +101,7 @@ export class NativeService{
|
|
|
87
101
|
await writeFile(resolve(folder,'playable.html'),artifact.html,{flag:'wx'});
|
|
88
102
|
await writeFile(resolve(folder,'manifest.json'),JSON.stringify(artifact.manifest),{flag:'wx'});
|
|
89
103
|
const revision={revisionId:project.revisionId,contentHash:contentHash(project)};
|
|
104
|
+
await saveRevisionLineage(resolve(this.store.root,id),project,envelope.expected.revisionId,registeredAssets);
|
|
90
105
|
state.hashes={...state.hashes,[revision.revisionId]:revision.contentHash};
|
|
91
106
|
state.revisions=[...new Set([...(state.revisions??state.history),revision.revisionId])];
|
|
92
107
|
state.history=state.history.slice(0,state.index+1);
|
|
@@ -98,28 +113,132 @@ export class NativeService{
|
|
|
98
113
|
}
|
|
99
114
|
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
115
|
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
|
|
116
|
+
async fitToTarget(id,project,assets,target){
|
|
117
|
+
const projectRoot=resolve(this.store.root,id),origContentHash=contentHash(project);
|
|
118
|
+
try{return await compileNative(project,{assets,target,sourceContentHash:origContentHash});}
|
|
119
|
+
catch(error){if(error.message!=='E_UPLOAD_SIZE')throw error;}
|
|
120
|
+
const used=new Set(references([project.components,project.gameplay,project.events,project.eventBindings]));
|
|
121
|
+
let workingAssets=assets.filter(a=>used.has(a.id)).map(a=>({...a}));
|
|
122
|
+
const droppedUnused=assets.filter(a=>!used.has(a.id)).map(a=>a.id);
|
|
123
|
+
const steps=[];
|
|
124
|
+
const makeProject=()=>({...project,assets:workingAssets.map(asset=>{const copy={...asset};delete copy.data;return copy;})});
|
|
125
|
+
const makeReport=()=>({fitTargetBudget:true,policy:'fit-v1',droppedUnused,steps});
|
|
126
|
+
if(droppedUnused.length){
|
|
127
|
+
try{return await compileNative(makeProject(),{assets:workingAssets,target,sourceContentHash:origContentHash,optimizationReport:makeReport()});}
|
|
128
|
+
catch(error){if(error.message!=='E_UPLOAD_SIZE')throw error;}
|
|
129
|
+
}
|
|
130
|
+
const lineage=await readRevisionLineage(projectRoot,project.revisionId);
|
|
131
|
+
const stageRoot=resolve(projectRoot,'sources/assets');
|
|
132
|
+
await mkdir(stageRoot,{recursive:true});
|
|
133
|
+
const stage=await mkdtemp(resolve(stageRoot,'.fit-'));
|
|
134
|
+
try{
|
|
135
|
+
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);
|
|
136
|
+
let stepIndex=0;
|
|
137
|
+
for(const tier of MODEL_FIT_LADDER){
|
|
138
|
+
for(const assetId of modelIds){
|
|
139
|
+
const idx=workingAssets.findIndex(a=>a.id===assetId);
|
|
140
|
+
if(idx<0)continue;
|
|
141
|
+
const current=workingAssets[idx],entry=lineage[assetId];
|
|
142
|
+
let sourceBytes=Buffer.from(current.data,'base64'),source='delivery-fallback',ext='.glb';
|
|
143
|
+
if(entry?.masterAvailable&&entry?.originalHash){
|
|
144
|
+
try{
|
|
145
|
+
sourceBytes=await readOriginal(projectRoot,entry.originalHash);
|
|
146
|
+
source='master';
|
|
147
|
+
ext=modelSourceTypes.get(entry.originalMime)??'.glb';
|
|
148
|
+
}catch(err){if(err.code!=='ENOENT')throw err;}
|
|
149
|
+
}
|
|
150
|
+
const inName=`in-${stepIndex}${ext}`,outName=`out-${stepIndex}.glb`;
|
|
151
|
+
stepIndex++;
|
|
152
|
+
await writeFile(resolve(stage,inName),sourceBytes);
|
|
153
|
+
const tool=requireNativeTool('optimize-3d');
|
|
154
|
+
const opts={mode:'auto',maxTextureSide:tier.maxTextureSide,targetBytes:tier.targetBytes,preserveNamedNodes:true};
|
|
155
|
+
await runTool(tool.command,[...tool.prefixArgs,stage,inName,outName,JSON.stringify(opts)],{timeout:120000,maxBuffer:1048576});
|
|
156
|
+
const fitted=await readFile(resolve(stage,outName));
|
|
157
|
+
if(fitted.length>=current.bytes)continue;
|
|
158
|
+
const fittedHash=hash(fitted);
|
|
159
|
+
workingAssets[idx]={...current,data:fitted.toString('base64'),bytes:fitted.length,hash:fittedHash,mime:'model/gltf-binary'};
|
|
160
|
+
steps.push({assetId,kind:'model',source,fromBytes:current.bytes,toBytes:fitted.length,fittedHash,maxTextureSide:tier.maxTextureSide,targetBytes:tier.targetBytes});
|
|
161
|
+
try{return await compileNative(makeProject(),{assets:workingAssets,target,sourceContentHash:origContentHash,optimizationReport:makeReport()});}
|
|
162
|
+
catch(error){if(error.message!=='E_UPLOAD_SIZE')throw error;}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
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);
|
|
166
|
+
for(const maxSide of IMAGE_FIT_SIDES){
|
|
167
|
+
for(const assetId of imageIds){
|
|
168
|
+
const idx=workingAssets.findIndex(a=>a.id===assetId);
|
|
169
|
+
if(idx<0)continue;
|
|
170
|
+
const current=workingAssets[idx],entry=lineage[assetId];
|
|
171
|
+
let sourceBytes=Buffer.from(current.data,'base64'),source='delivery-fallback',srcMime=current.mime;
|
|
172
|
+
if(entry?.masterAvailable&&entry?.originalHash){
|
|
173
|
+
try{
|
|
174
|
+
sourceBytes=await readOriginal(projectRoot,entry.originalHash);
|
|
175
|
+
source='master';
|
|
176
|
+
srcMime=entry.originalMime??current.mime;
|
|
177
|
+
}catch(err){if(err.code!=='ENOENT')throw err;}
|
|
178
|
+
}
|
|
179
|
+
const ext=srcMime==='image/jpeg'?'.jpg':'.png',inName=`img-${stepIndex}${ext}`,prepOutDir=`imgout-${stepIndex}`,optOut=`imgopt-${stepIndex}`;
|
|
180
|
+
stepIndex++;
|
|
181
|
+
await writeFile(resolve(stage,inName),sourceBytes);
|
|
182
|
+
const prepTool=requireNativeTool('prep');
|
|
183
|
+
const prepReport=JSON.parse((await runTool(prepTool.command,[...prepTool.prefixArgs,stage,inName,prepOutDir,JSON.stringify({outputPrefix:'fit',maxSide})],{timeout:60000,maxBuffer:1048576})).stdout);
|
|
184
|
+
const preppedRel=`${prepOutDir}/${prepReport.outputs[0].file}`;
|
|
185
|
+
const optTool=requireNativeTool('optimize');
|
|
186
|
+
const optReport=JSON.parse((await runTool(optTool.command,[...optTool.prefixArgs,stage,preppedRel,optOut,JSON.stringify({mode:'auto',preserveResolution:false})],{timeout:60000,maxBuffer:1048576})).stdout);
|
|
187
|
+
const fitted=await readFile(resolve(stage,optOut));
|
|
188
|
+
if(fitted.length>=current.bytes)continue;
|
|
189
|
+
const fittedHash=hash(fitted);
|
|
190
|
+
workingAssets[idx]={...current,data:fitted.toString('base64'),bytes:fitted.length,hash:fittedHash,mime:optReport.mime??current.mime};
|
|
191
|
+
steps.push({assetId,kind:'image',source,fromBytes:current.bytes,toBytes:fitted.length,fittedHash,maxSide});
|
|
192
|
+
try{return await compileNative(makeProject(),{assets:workingAssets,target,sourceContentHash:origContentHash,optimizationReport:makeReport()});}
|
|
193
|
+
catch(error){if(error.message!=='E_UPLOAD_SIZE')throw error;}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}finally{await rm(stage,{recursive:true,force:true});}
|
|
197
|
+
return compileNative(makeProject(),{assets:workingAssets,target,sourceContentHash:origContentHash,optimizationReport:makeReport()});
|
|
198
|
+
}
|
|
199
|
+
async build(id,project,target='standalone-browser-draft',{fitTargetBudget=false}={}){
|
|
200
|
+
const assets=await lowerAssets(resolve(this.store.root,id),project.assets),runtimeHash=hash(projectUses3d(project)?await runtime3dBundle():await runtimeBundle()),key=buildCacheKey({project,target,runtimeHash,fitPolicyKey:fitTargetBudget?'fit-v1':'standard',deliveredAssetHashes:assets.map(a=>a.hash)});
|
|
201
|
+
return this.buildCache.getOrBuild(key,()=>fitTargetBudget?this.fitToTarget(id,project,assets,target):compileNative(project,{assets,target}));
|
|
104
202
|
}
|
|
105
203
|
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
|
-
|
|
204
|
+
async upload(id,{expected,asset,provenance},source){
|
|
205
|
+
const result=await this.uploadBatch(id,{expected,assets:[{...asset,...(provenance?{provenance}:{})}]},source);
|
|
206
|
+
const {assets,...revision}=result;
|
|
207
|
+
return {...revision,asset:assets[0]};
|
|
208
|
+
}
|
|
209
|
+
async uploadBatch(id,{expected,assets},source={}){
|
|
108
210
|
check(Array.isArray(assets)&&assets.length>=1&&assets.length<=32,'E_NATIVE_ARGUMENT');
|
|
109
211
|
check(expected&&exact(expected,['revisionId','contentHash']),'E_NATIVE_ENVELOPE');
|
|
110
212
|
const ids=assets.map(item=>item?.id);
|
|
111
213
|
check(new Set(ids).size===ids.length,'E_NATIVE_DUPLICATE');
|
|
112
214
|
const current=await this.read(id);
|
|
113
215
|
check(expected.revisionId===current.revisionId&&expected.contentHash===current.contentHash,'E_NATIVE_STALE');
|
|
114
|
-
assertSingleVisualStyleFamily(current.project.assets,assets);
|
|
115
216
|
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
|
|
217
|
+
const registered=await mapWithConcurrency(assets,4,async (item,index)=>{
|
|
218
|
+
const {provenance,sourceHash,useOriginal,...input}=item;
|
|
219
|
+
const filePath=source.filePaths?.[index];
|
|
220
|
+
check([Boolean(filePath),Boolean(input.data),Boolean(sourceHash),useOriginal===true].filter(Boolean).length===1,'E_NATIVE_ASSET');
|
|
221
|
+
const opts=provenance?{provenance}:{};
|
|
222
|
+
if(filePath)return registerSourceFromFile(projectRoot,source.workspaceRoot,filePath,input,{...opts,preparedProvenance:resolvePreparedProvenance});
|
|
223
|
+
if(sourceHash||useOriginal){
|
|
224
|
+
const lineage=(await readRevisionLineage(projectRoot,expected.revisionId))[input.id];
|
|
225
|
+
const originalHash=sourceHash??lineage?.originalHash;
|
|
226
|
+
if(!originalHash||useOriginal&&!lineage?.masterAvailable)throw Error('E_ASSET_ORIGINAL_UNAVAILABLE');
|
|
227
|
+
if(useOriginal)input.mime=lineage.originalMime;
|
|
228
|
+
const bytes=await readOriginal(projectRoot,originalHash).catch(error=>{
|
|
229
|
+
if(error.code==='ENOENT')throw Error('E_ASSET_ORIGINAL_UNAVAILABLE',{cause:error});
|
|
230
|
+
throw error;
|
|
231
|
+
});
|
|
232
|
+
check(hash(bytes)===originalHash,'E_NATIVE_ASSET_HASH');
|
|
233
|
+
if(!provenance&&lineage?.originalHash===originalHash){
|
|
234
|
+
opts.provenance=current.project.assets.find(asset=>asset.id===input.id)?.provenance;
|
|
235
|
+
}
|
|
236
|
+
if(lineage?.dependencyManifestHash&&lineage.originalHash===originalHash)opts.dependencyManifestHash=lineage.dependencyManifestHash;
|
|
237
|
+
return registerSourceBytes(projectRoot,input,bytes,opts);
|
|
238
|
+
}
|
|
239
|
+
return registerSource(projectRoot,input,opts);
|
|
122
240
|
});
|
|
241
|
+
assertSingleVisualStyleFamily(current.project.assets,registered);
|
|
123
242
|
const existingIds=new Set(current.project.assets.map(a=>a.id));
|
|
124
243
|
const operations=registered.map(metadata=>{
|
|
125
244
|
const {optimization,...record}=metadata;void optimization;
|
|
@@ -127,47 +246,55 @@ export class NativeService{
|
|
|
127
246
|
});
|
|
128
247
|
const envelope={format:'tora-transaction-1',expected,operations};
|
|
129
248
|
const preview=await this.preview(id,envelope);
|
|
130
|
-
const committed=await this.transact(id,{...envelope,previewDigest:preview.previewDigest});
|
|
249
|
+
const committed=await this.transact(id,{...envelope,previewDigest:preview.previewDigest},{registeredAssets:registered});
|
|
131
250
|
return {...committed,assets:registered.map(({optimization,...record})=>({...record,...(optimization?{optimization}:{})}))};
|
|
132
251
|
}
|
|
133
|
-
async runQa(id,{revisionId,target='standalone-browser-draft',outputDir,motionFilmstrip=true,recordVideo=false}={}){
|
|
252
|
+
async runQa(id,{revisionId,target='standalone-browser-draft',outputDir,motionFilmstrip=true,recordVideo=false,artifact:prebuiltArtifact,fitTargetBudget=false,reuseVideoReceipt=false}={}){
|
|
134
253
|
assertNetworkTarget(target);
|
|
135
254
|
const current=await this.read(id,revisionId),effectiveRevisionId=current.revisionId;
|
|
136
|
-
const qaDirSuffix=recordVideo?'-video':motionFilmstrip?'':'-nomotion';
|
|
255
|
+
const qaDirSuffix=(fitTargetBudget?'-fit':'')+(recordVideo?'-video':motionFilmstrip?'':'-nomotion');
|
|
137
256
|
const resolvedOut=resolve(outputDir??resolve(this.store.root,id,'qa',effectiveRevisionId,target+qaDirSuffix));
|
|
138
|
-
const artifact=await this.build(id,current.project,target);
|
|
257
|
+
const artifact=prebuiltArtifact??await this.build(id,current.project,target,{fitTargetBudget});
|
|
258
|
+
const artifactHash=artifact.manifest.artifactHash;
|
|
139
259
|
const isDefaultRunner=this.qaRunner===defaultQaRunner;
|
|
140
260
|
const cacheEnabled=this.useVerifyCache??isDefaultRunner;
|
|
141
|
-
const scenario=qaScenarioTag({motionFilmstrip,recordVideo});
|
|
142
261
|
let receiptKey;
|
|
143
262
|
if(cacheEnabled){
|
|
144
263
|
const browserVersion=await getPlaywrightBrowserVersion();
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
264
|
+
const keyFor=video=>this.verifyCache.receiptKey({
|
|
265
|
+
artifactHash,checkerVersion:`${CREATIVE_QA_CHECKER_VERSION}:${browserVersion}`,kind:'creative-qa',host:target,
|
|
266
|
+
scenario:qaScenarioTag({motionFilmstrip,recordVideo:video})+(fitTargetBudget?';fit=1':''),
|
|
267
|
+
});
|
|
268
|
+
receiptKey=keyFor(recordVideo);
|
|
269
|
+
const candidateKeys=[receiptKey,...(reuseVideoReceipt&&!recordVideo?[keyFor(true)]:[])];
|
|
270
|
+
for(const key of candidateKeys){
|
|
271
|
+
const cached=await this.verifyCache.read(key);
|
|
272
|
+
if(cached?.report?.ok!==true||cached.report.format!==CREATIVE_QA_FORMAT||typeof cached.outputDir!=='string')continue;
|
|
148
273
|
if(await verifyAndCopyQaArtifacts(cached.outputDir,resolvedOut,cached.report,{motionFilmstrip,recordVideo,isDefaultRunner})){
|
|
149
|
-
return {...cached.report,cacheHit:true};
|
|
274
|
+
return {...cached.report,artifactHash,outputDir:resolvedOut,cacheHit:true};
|
|
150
275
|
}
|
|
151
276
|
}
|
|
152
277
|
}
|
|
153
278
|
const browser=isDefaultRunner&&this.browserProvider?await this.browserProvider():undefined;
|
|
154
279
|
const report=await this.qaRunner({html:artifact.html,outputDir:resolvedOut,network:target,motionFilmstrip,recordVideo,...(browser?{browser}:{})});
|
|
280
|
+
const stampedReport={...report,artifactHash};
|
|
155
281
|
if(cacheEnabled&&report?.ok===true&&receiptKey&&qaReportSatisfiesOptions(report,{motionFilmstrip,recordVideo,isDefaultRunner})){
|
|
156
|
-
await this.verifyCache.write(receiptKey,{report,outputDir:resolvedOut});
|
|
282
|
+
await this.verifyCache.write(receiptKey,{report:stampedReport,outputDir:resolvedOut});
|
|
157
283
|
}
|
|
158
|
-
return {...
|
|
284
|
+
return {...stampedReport,outputDir:resolvedOut,cacheHit:false};
|
|
159
285
|
}
|
|
160
|
-
async export(id,{revisionId,target}){check(typeof revisionId==='string','E_NATIVE_ARGUMENT');assertNetworkTarget(target);const {project,accepted}=await this.read(id,revisionId),artifact=await this.build(id,project,target),outputDir=resolve(this.store.root,id,'qa',revisionId,target),creativeQa=requireCreativeQa(await this.runQa(id,{revisionId,target,outputDir}));return {...artifact,creativeQa,manifest:{...artifact.manifest,accepted,creativeQa:{format:CREATIVE_QA_FORMAT,ok:true,blockers:0,warnings:creativeQa.warnings.length},checks:[...artifact.manifest.checks,'creative-qa']}};}
|
|
161
|
-
async exportBatch(id,{revisionId,targets,outputDir}){
|
|
286
|
+
async export(id,{revisionId,target,fitTargetBudget=false}){check(typeof revisionId==='string','E_NATIVE_ARGUMENT');assertNetworkTarget(target);const {project,accepted}=await this.read(id,revisionId),artifact=await this.build(id,project,target,{fitTargetBudget}),outputDir=resolve(this.store.root,id,'qa',revisionId,target+(fitTargetBudget?'-fit':'')),creativeQa=requireCreativeQa(await this.runQa(id,{revisionId,target,outputDir,artifact,fitTargetBudget,reuseVideoReceipt:true}));check(creativeQa.artifactHash===artifact.manifest.artifactHash,'E_CREATIVE_QA_HASH_MISMATCH');return {...artifact,creativeQa,manifest:{...artifact.manifest,accepted,creativeQa:{format:CREATIVE_QA_FORMAT,ok:true,blockers:0,warnings:creativeQa.warnings.length,artifactHash:creativeQa.artifactHash},checks:[...artifact.manifest.checks,'creative-qa']}};}
|
|
287
|
+
async exportBatch(id,{revisionId,targets,outputDir,fitTargetBudget=false}){
|
|
162
288
|
check(Array.isArray(targets)&&targets.length>=1&&targets.length<=8&&new Set(targets).size===targets.length,'E_NATIVE_ARGUMENT');
|
|
163
289
|
check(typeof outputDir==='string'&&outputDir.length>0,'E_AGENT_OUTPUT');
|
|
164
290
|
for(const target of targets)assertNetworkTarget(target);
|
|
165
291
|
const current=await this.read(id,revisionId),resolvedDir=resolve(outputDir);
|
|
166
|
-
const built=await mapWithConcurrency(targets,4,async target=>({target,artifact:await this.build(id,current.project,target)}));
|
|
292
|
+
const built=await mapWithConcurrency(targets,4,async target=>({target,artifact:await this.build(id,current.project,target,{fitTargetBudget})}));
|
|
167
293
|
const verified=[];
|
|
168
294
|
for(const {target,artifact}of built){
|
|
169
|
-
const qaDir=resolve(this.store.root,id,'qa',current.revisionId,target);
|
|
170
|
-
const creativeQa=requireCreativeQa(await this.runQa(id,{revisionId:current.revisionId,target,outputDir:qaDir}));
|
|
295
|
+
const qaDir=resolve(this.store.root,id,'qa',current.revisionId,target+(fitTargetBudget?'-fit':''));
|
|
296
|
+
const creativeQa=requireCreativeQa(await this.runQa(id,{revisionId:current.revisionId,target,outputDir:qaDir,artifact,fitTargetBudget,reuseVideoReceipt:true}));
|
|
297
|
+
check(creativeQa.artifactHash===artifact.manifest.artifactHash,'E_CREATIVE_QA_HASH_MISMATCH');
|
|
171
298
|
verified.push({target,artifact,creativeQa});
|
|
172
299
|
}
|
|
173
300
|
await mkdir(resolvedDir,{recursive:true});
|