|
- import assert from 'node:assert/strict'
- import test from 'node:test'
- import { readFile } from 'node:fs/promises'
- import { createRequire } from 'node:module'
- const requireWeb = createRequire(new URL('../../unreal_tran_web/package.json', import.meta.url))
- const requirePrototype = createRequire(new URL('../../unreal_tran/package.json', import.meta.url))
- const { Window } = requirePrototype('happy-dom')
- const ts = requireWeb('typescript')
- const web = new URL('../../unreal_tran_web/src/', import.meta.url)
- const dataModule = source => `data:text/javascript;base64,${Buffer.from(source).toString('base64')}`
- async function compile(file, replacements = {}) {
- let source = await readFile(new URL(file, web), 'utf8')
- for (const [from, to] of Object.entries(replacements)) source = source.replaceAll(from, to)
- return dataModule(ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } }).outputText)
- }
- const { canUsePermission } = await import(await compile('config/roles.ts'))
- const { contentPermission, contentReviewPermission } = await import(await compile('utils/contentPermissions.ts'))
- test('content abilities use exact grants independently of teacher/admin/custom role names', () => {
- for (const code of ['admin', 'teacher', 'custom-author', 'student']) {
- assert.equal(canUsePermission('content.model.update', ['content.model.update'], [{ code, enabled: true, active: true }], 'SINGLE_ACTIVE'), true)
- assert.equal(canUsePermission('content.scene.update', ['content.model.update'], [{ code, enabled: true, active: true }], 'UNION'), false)
- assert.equal(canUsePermission('content.model.update', ['content.update'], [{ code, enabled: true, active: true }], 'UNION'), false)
- }
- })
- test('copy, delete, review, revoke and submit retain separate action grants', () => {
- assert.equal(contentPermission('GUIDE', 'create'), 'content.ofd.create')
- assert.equal(contentPermission('TRAINING', 'delete'), 'content.training.delete')
- for (const action of ['APPROVE', 'REJECT']) assert.equal(contentReviewPermission('GUIDE', action), 'content.ofd.review')
- assert.equal(contentReviewPermission('GUIDE', 'REVOKE'), 'content.ofd.publish')
- for (const action of ['SUBMIT', 'WITHDRAW', 'REVISE']) assert.equal(contentReviewPermission('GUIDE', action), 'content.ofd.update')
- })
-
- const authUrl = dataModule(`export const auth = { profile: { userId: 'reader', displayName: 'Actual user', permissions: [] }, activeRole: { code: 'admin' }, availableRoles: [], hasEffectiveRole: () => false, hasPermission(permission) { return this.profile.permissions.includes(permission) } }; export const useAuthStore = () => auth;`)
- const { auth } = await import(authUrl)
- const storageUrl = await compile('features/legacy-shared/scopedStorage.ts')
- const guideRuntime = await import(await compile('features/guide-legacy/runtime.ts', {
- './demo-src/asset-store.js': new URL('features/guide-legacy/demo-src/asset-store.js', web).href,
- './demo-src/content-list-store.js': new URL('features/guide-legacy/demo-src/content-list-store.js', web).href,
- '../legacy-shared/scopedStorage': storageUrl,
- '../../stores/auth': authUrl,
- }))
- test('OFD runtime uses the real session and rejects local create/update/delete without exact grants', async () => {
- const { createInitialOFDState } = await import(new URL('features/guide-legacy/demo-src/ofd-document.js', web))
- const context = guideRuntime.legacyGuideRuntimeContext()
- assert.equal(context.actor.id, 'reader')
- assert.equal(context.readOnly, true)
- assert.equal(context.can('content.create'), false)
- assert.equal(context.storage.length, 0, 'read-only initialization must not seed projects')
- assert.throws(() => context.contentStore.createOFDProject({ title: 'Denied' }), /权限/)
- auth.profile.permissions = ['content.ofd.create']
- const initial = createInitialOFDState()
- initial.project.name = 'Full initial payload'
- const created = context.contentStore.createOFDProject({ title: 'Created only', state: initial })
- assert.ok(created.id)
- assert.equal(created.author, 'Actual user')
- assert.throws(() => context.contentStore.saveOFDProjectState(created.id, created.state), /权限/)
- assert.throws(() => context.contentStore.deleteOFDProject(created.id), /权限/)
- auth.profile.permissions = ['content.ofd.delete']
- assert.equal(context.contentStore.deleteOFDProject(created.id), true)
- })
- const { canPerformOFDAction, createInitialOFDState } = await import(new URL('features/guide-legacy/demo-src/ofd-document.js', web))
- test('OFD lifecycle does not treat admin/teacher identity as a publish grant', () => {
- const state = createInitialOFDState()
- for (const role of ['admin', 'teacher']) assert.equal(canPerformOFDAction(state, 'publish', { role, permissions: [] }), false)
- assert.equal(canPerformOFDAction(state, 'publish', { role: 'custom', permissions: ['content.ofd.publish'] }), true)
- assert.equal(canPerformOFDAction(state, 'publish', { role: 'custom', permissions: ['content.ofd.update'] }), false)
- })
-
- const { installLegacyModelPermissions } = await import(await compile('features/editors/model/legacy-iframe-permissions.ts'))
- function modelFixture({ update = false, publish = false, create = false, createNew, document } = {}) {
- const calls = []
- const editor = {
- apiEditorHydrated: true, apiState: 'ready', apiSession: { project: { id: 'test', version: 7 }, lastSavedFingerprint: '' },
- saveProject: async () => { calls.push('save'); return {} },
- newProject: async () => { calls.push('local-new'); return true },
- publishToSceneLibrary: async () => { calls.push('save-and-publish'); return {} },
- saveRecoveryCopy: () => calls.push('recovery'),
- serializeProject: () => ({}), toast: message => calls.push(message),
- transform: { enabled: true, detach() {}, attach() { calls.push('transform') } },
- }
- const doc = document || { defaultView: { editorApp: editor }, body: {}, querySelector: () => null, querySelectorAll: () => [], addEventListener() {}, removeEventListener() {} }
- doc.defaultView.editorApp = editor
- const previousObserver = globalThis.MutationObserver
- globalThis.MutationObserver = class { observe() {} disconnect() {} }
- const bridge = installLegacyModelPermissions(doc, {
- canCreate: () => create, canUpdate: () => update, canPublish: () => publish,
- createNew: createNew || (async () => { calls.push('server-new'); return true }),
- publishSaved: async version => { calls.push(['publish-saved', version]); return { id: 'test', version: 8 } },
- })
- globalThis.MutationObserver = previousObserver
- return { editor, calls, bridge }
- }
- test('model iframe read-only bridge blocks autosave, recovery writes and transform attach', async () => {
- const { editor, calls, bridge } = modelFixture()
- assert.equal(await editor.saveProject(true, { automatic: true }), null)
- assert.equal(await editor.publishToSceneLibrary(), null)
- editor.saveRecoveryCopy()
- editor.transform.attach({})
- assert.deepEqual(calls, [])
- assert.equal(editor.transform.enabled, false)
- bridge.dispose()
- })
- test('model iframe publisher-only uses the loaded optimistic-lock version without saving', async () => {
- const { editor, calls, bridge } = modelFixture({ publish: true })
- const published = await editor.publishToSceneLibrary()
- assert.equal(published.version, 8)
- assert.deepEqual(calls[0], ['publish-saved', 7])
- assert.equal(calls.includes('save-and-publish'), false)
- bridge.dispose()
- })
-
- test('read-only model search, native clip selection and preview keyboard activation remain usable without enabling edits', t => {
- const window = new Window({ url: 'http://localhost/editor.html' })
- t.after(() => window.happyDOM.cancelAsync())
- const doc = window.document
- doc.body.innerHTML = '<div class="editor-shell"><input id="left-search"><select id="native-clip-select"><option>walk</option><option>run</option></select><button data-action="preview">Preview</button><input id="project-name"><input id="model-file-input" type="file"><div id="inspector"><input id="position-x"></div></div>'
- const { bridge } = modelFixture({ document: doc })
- t.after(() => bridge.dispose())
- const dispatch = (selector, type, key = '') => doc.querySelector(selector).dispatchEvent(type === 'keydown'
- ? new window.KeyboardEvent(type, { key, bubbles: true, cancelable: true })
- : new window.Event(type, { bubbles: true, cancelable: true }))
- for (const key of ['x', 'Backspace', 'Enter']) assert.equal(dispatch('#left-search', 'keydown', key), true, `search ${key}`)
- assert.equal(dispatch('#left-search', 'input'), true)
- assert.equal(dispatch('#native-clip-select', 'change'), true, 'a clip choice changes preview playback, not the saved project')
- assert.equal(dispatch('#left-search', 'drop'), false, 'read-only control exceptions must not enable resource drops')
- for (const key of ['Enter', ' ']) assert.equal(dispatch('[data-action="preview"]', 'keydown', key), true, `preview activation ${key}`)
- assert.equal(dispatch('#project-name', 'input'), false)
- assert.equal(dispatch('#position-x', 'change'), false)
- assert.equal(dispatch('#model-file-input', 'change'), false)
- assert.equal(dispatch('[data-action="preview"]', 'keydown', 'Delete'), false)
- })
- test('committed role switch prevents iframe unload recovery from writing discarded changes', async () => {
- const { editor, calls, bridge } = modelFixture({ update: true, publish: true })
- bridge.roleSwitchCommitted()
- editor.saveRecoveryCopy()
- assert.equal(await editor.saveProject(), null)
- assert.equal(await editor.publishToSceneLibrary(), null)
- assert.deepEqual(calls, [])
- bridge.dispose()
- })
-
- test('read-only model viewing skips automatic migration and recovery without modifying saved data', async () => {
- const { editor, bridge } = modelFixture()
- editor.apiDocumentNeedsMigrationSave = true
- assert.equal(editor.apiDocumentNeedsMigrationSave, false)
- assert.equal(await editor.saveProject(true), null)
- bridge.dispose()
- assert.equal(editor.apiDocumentNeedsMigrationSave, true, 'the host must restore the original runtime state on disposal')
- })
-
- const { ModelContentProjectSession } = await import(new URL('../../unreal_tran/src/model-content-api.js', import.meta.url))
- const { createBuiltInTestProject: createModelDocument, normalizeProjectDocument: normalizeModelDocument } = await import(new URL('../../unreal_tran/src/editor-project-io.js', import.meta.url))
-
- test('model host dirty check uses the complete saved iframe document, including depot environments', async () => {
- for (const environmentType of ['outdoor', 'workshop', 'depot']) {
- const document = normalizeModelDocument(createModelDocument())
- document.environment.environmentType = environmentType
- document.environment.objects = { 'environment-fixture': { position: [1, 2, 3], visible: false } }
- document.camera.position = [7, 8, 9]
- const session = new ModelContentProjectSession({ projectId: '7', client: {
- async request(_path, { json }) {
- return { ...session.project, ...structuredClone(json), id: '7', version: session.project.version + 1 }
- },
- } })
- session.project = { id: '7', type: 'MODEL', name: document.name, version: 1, coverUri: '', assets: [], dependencies: [] }
- await session.queueSave(document)
- const { editor, bridge } = modelFixture({ update: true })
- editor.apiSession = session
- editor.serializeProject = () => structuredClone(document)
- assert.equal(bridge.isDirty(), false, `${environmentType}: successful save must be clean`)
- document.model = { id: 'fixture-part', visible: false }
- assert.equal(bridge.isDirty(), true, `${environmentType}: real model edits must remain dirty`)
- await session.queueSave(document)
- assert.equal(bridge.isDirty(), false, `${environmentType}: saving the real edit clears dirty state`)
- document.environment.objects['environment-fixture'].position[0] = 10
- assert.equal(bridge.isDirty(), true, `${environmentType}: environment edits must remain dirty`)
- bridge.dispose()
- const readonly = modelFixture()
- readonly.editor.apiSession = session
- readonly.editor.serializeProject = () => structuredClone(document)
- assert.equal(readonly.bridge.isDirty(), false, 'read-only viewing must not prompt to save')
- readonly.bridge.dispose()
- }
- })
-
- test('model create-only permission uses host creation without resetting or saving the loaded project', async () => {
- const { editor, bridge, calls } = modelFixture({ create: true })
- assert.equal(await editor.newProject(), true)
- assert.deepEqual(calls, ['server-new'])
- assert.equal(await editor.saveProject(), null)
- bridge.dispose()
- assert.equal(await editor.newProject(), true)
- assert.deepEqual(calls, ['server-new', 'local-new'], 'disposing restores the original runtime method')
- })
-
- test('model new prevents concurrent creation and releases its guard after cancellation or failure', async () => {
- let settle, attempts = 0
- const { editor, bridge } = modelFixture({ create: true, createNew: () => {
- attempts += 1
- return new Promise((resolve, reject) => { settle = { resolve, reject } })
- } })
- const first = editor.newProject()
- assert.equal(await editor.newProject(), false)
- assert.equal(attempts, 1)
- settle.resolve(false)
- assert.equal(await first, false)
- const second = editor.newProject()
- settle.reject(new Error('fixture creation failed'))
- await assert.rejects(second, /fixture creation failed/)
- const third = editor.newProject()
- assert.equal(attempts, 3, 'cancellation and rejection must both permit a retry')
- settle.resolve(true)
- assert.equal(await third, true)
- bridge.roleSwitchCommitted()
- assert.equal(await editor.newProject(), false)
- assert.equal(attempts, 3, 'a committed role switch must prevent late creation')
- bridge.dispose()
- })
-
- const policy = await import(await compile('features/guide/publishDeliveriesPolicy.ts'))
- const publishSource = await readFile(new URL('features/guide/publishDeliveries.ts', web), 'utf8')
- const publishFunction = ts.transpileModule(publishSource.slice(publishSource.indexOf('export async function publishGuideWithDeliveries(')), {
- compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },
- }).outputText.replace(/^export /gm, '')
- const publishGuide = new Function('normalizeGuideContent', 'resolveGuideDeliveryAssets', 'commitGuideDeliveries', 'reusableGuideDelivery', 'assertCompleteGuideDeliveries', 'GUIDE_DELIVERY_ASSET_CODES', 'artifactFile', 'text', `${publishFunction};return publishGuideWithDeliveries`)(
- value => value, async () => ({}), policy.commitGuideDeliveries, policy.reusableGuideDelivery,
- policy.assertCompleteGuideDeliveries, policy.GUIDE_DELIVERY_ASSET_CODES,
- () => { throw new Error('publisher must not upload') }, value => String(value ?? '').trim(),
- )
- function guidePublisherFixture(savedFingerprint) {
- const calls = []
- const formats = ['OFD', 'OFFLINE_HTML']
- const assets = formats.map(format => ({ code: policy.GUIDE_DELIVERY_ASSET_CODES[format], type: 'DOCUMENT', status: 'READY', sha256: 'a'.repeat(64),
- storageUri: `content://${format}`, metadata: { deliveryFormat: format, sourceFingerprint: savedFingerprint } }))
- const dependencies = {
- loadProject: async () => ({ id: 'g', version: 17, status: 'DRAFT', content: {}, assets }),
- readAsset: async () => new Blob(), uploadAsset: async () => { calls.push('upload'); throw new Error('forbidden') },
- buildArtifacts: async () => ({ sourceFingerprint: 'current-source', artifacts: formats.map(format => ({ format, code: policy.GUIDE_DELIVERY_ASSET_CODES[format] })) }),
- publishProject: async (_id, _type, input) => { calls.push(input); return { id: 'g', version: 18 } },
- }
- return { calls, dependencies }
- }
- test('OFD publisher reuses the exact saved source artifacts and optimistic-lock version without uploading', async () => {
- const { calls, dependencies } = guidePublisherFixture('current-source')
- const result = await publishGuide('g', { allowUpload: false }, dependencies)
- assert.equal(result.project.version, 18)
- assert.deepEqual(result.uploadedFormats, [])
- assert.deepEqual(result.reusedFormats, ['OFD', 'OFFLINE_HTML'])
- assert.equal(calls.length, 1)
- assert.equal(calls[0].version, 17)
- assert.equal(calls[0].deliveries.length, 2)
- })
- test('OFD publisher cannot regenerate/upload stale artifacts or publish them against changed content', async () => {
- const { calls, dependencies } = guidePublisherFixture('stale-source')
- await assert.rejects(publishGuide('g', { allowUpload: false }, dependencies), /交付物/)
- assert.deepEqual(calls, [])
- })
|