diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index 2b8fee12b..fadafebd3 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -153,7 +153,13 @@ back to Cesium. Both lists only ever shrink. - `src/render/cesiumAllowList.json` lists the files outside the Cesium adapter (`src/render/cesium/`) that may still import or be handed Cesium (`src/render/noCesiumOutsideRender.test.mjs`). A file leaves the list - when it no longer drives Cesium at all; nothing is added. + when it no longer drives Cesium at all; nothing is added. Two files name + the adapter by design and are not on it: the application scene + (`src/app/scene.js`), the composition root that picks the Cesium renderer, + may import `src/render/cesium/application.js` and nothing else of the + adapter; the conformance page (`dev/conformance/main.js`) may import the + adapter's harness and scene renderer. The test names both + (`ADAPTER_ENTRIES`), and that list is never grown. - `src/render/viewerAccessAllowList.json` counts, per file off that list, the Cesium-shaped accesses through the viewer it still makes (`src/render/viewerAccess.test.mjs`): the viewer's `entities`, diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 91e2ef225..936deec39 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -1131,6 +1131,7 @@ "src/tools/views.test.mjs", "src/app/embed.test.mjs", "src/render/cesium/panelRendering.js", + "src/render/cesium/application.js", "src/render/cesium/panelRendering.test.mjs", "src/tools/globePanel.test.mjs", "src/costEndpointThrottle.test.mjs", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index b44a0c021..6e7b87af7 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -4296,7 +4296,8 @@ "src/maps/attribution.js", "src/render/cesium/mapEngine.js", "src/sky/icrf.js", - "src/render/cesium/panelRendering.js" + "src/render/cesium/panelRendering.js", + "src/render/cesium/application.js" ], "external": [ "hls.js", diff --git a/src/app/scene.js b/src/app/scene.js index e4f018a94..d6dfa4495 100644 --- a/src/app/scene.js +++ b/src/app/scene.js @@ -1,15 +1,17 @@ import { createApplicationOperations } from './operations.js'; -import * as Cesium from 'cesium'; +// The application's composition root: it picks the Cesium renderer, and +// this is the only part of the adapter it imports. import { + applicationViewerHooks, cesiumRenderer, cesiumViewerOf, -} from '../render/cesium/appRenderer.js'; -import { trimStaleSceneCommands } from '../render/cesium/sceneCommandRelease.js'; -import { keepPanelRendering } from '../render/cesium/panelRendering.js'; + loadApplicationPhotoreal, + releaseApplicationPhotoreal, + showApplicationPhotoreal, +} from '../render/cesium/application.js'; import { registerDataCredits } from '../data/dataCredits.js'; import { configureCreditKeyboardAccess } from '../creditKeyboard.js'; import { MapStackController } from '../mapStackController.js'; -import { loadPhotorealisticTileset } from '../render/cesium/google3d.js'; import { initLogoGaze } from '../logoGaze.js'; import { inputFor } from '../input/dispatcher.js'; import { @@ -97,21 +99,17 @@ export async function createApplicationScene({ googleApiKey || googleTokens || cesiumToken ? t('Loading Google 3D Tiles...') : t('Loading the keyless globe...'); - const photoreal = await loadPhotorealisticTileset(Cesium, { + const photoreal = await loadApplicationPhotoreal({ googleApiKey, googleTokens, cesiumToken, }); const tileset = photoreal.tileset; // A provider can finish after cancellation; retain ownership of its result. - defer(() => { - if (tileset && !tileset.isDestroyed()) { - if (!viewer.scene.primitives.remove(tileset)) tileset.destroy(); - } - }); + defer(() => releaseApplicationPhotoreal(viewer, tileset)); signal.throwIfAborted(); if (tileset) { - viewer.scene.primitives.add(tileset); + showApplicationPhotoreal(viewer, tileset); // NOTE: Cesium World Terrain intentionally disabled — conflicts with Google 3D Tiles at high zoom. // Google Photorealistic 3D Tiles provide their own terrain/elevation. renderer.globe.setGlobeVisible(false); @@ -167,14 +165,8 @@ export async function createApplicationScene({ mapStackController, operations, input, - // Drops the draw commands the scene keeps after it stops drawing them; - // run after a drawn frame (see src/sceneCommandRelease.js). - trimStaleCommands: () => trimStaleSceneCommands(viewer.scene), - // Keeps the globe drawing in an inline panel whose host stops animation - // frames (embed mode, src/app/embed.js). - keepPanelRendering: (options) => keepPanelRendering(viewer, options), - // Whether an entity is one of the viewer's own (Cockpit asks whether - // the aircraft it flies still draws). - viewerDrawsEntity: (entity) => viewer.entities.contains(entity), + // Trims stale draw commands, keeps an inline panel drawing, and says + // whether an entity is the viewer's own (render/cesium/application.js). + ...applicationViewerHooks(viewer), }; } diff --git a/src/render/cesium/application.js b/src/render/cesium/application.js new file mode 100644 index 000000000..c423fb095 --- /dev/null +++ b/src/render/cesium/application.js @@ -0,0 +1,59 @@ +/** + * @module render/cesium/application + * @description The Cesium adapter's side of the application scene + * (`src/app/scene.js`), its composition root: the default renderer plugin, + * the viewer behind a renderer it made, the photoreal base tileset the scene + * loads into that viewer, and the viewer hooks the scene hands the + * application (stale command trimming, inline panel rendering, whether an + * entity is the viewer's own). The scene imports this module and no other + * part of the adapter (`src/render/noCesiumOutsideRender.test.mjs`). + */ +import * as Cesium from 'cesium'; +import { cesiumRenderer, cesiumViewerOf } from './appRenderer.js'; +import { loadPhotorealisticTileset } from './google3d.js'; +import { keepPanelRendering } from './panelRendering.js'; +import { trimStaleSceneCommands } from './sceneCommandRelease.js'; + +export { cesiumRenderer, cesiumViewerOf }; + +/** + * Load Google Photorealistic 3D Tiles for the application, by the best route + * the credentials allow (`google3d.js`). + * @param {{googleApiKey?: string, googleTokens?: object|null, cesiumToken?: string}} credentials + * @returns {Promise<{tileset: object|null, route: string, errors: Error[]}>} + */ +export const loadApplicationPhotoreal = (credentials) => + loadPhotorealisticTileset(Cesium, credentials); + +/** Draw the loaded photoreal tileset in `viewer`. */ +export function showApplicationPhotoreal(viewer, tileset) { + viewer.scene.primitives.add(tileset); +} + +/** + * Release the photoreal tileset: out of `viewer`, which destroys it, or + * destroyed by itself when the viewer never held it. + */ +export function releaseApplicationPhotoreal(viewer, tileset) { + if (tileset && !tileset.isDestroyed()) { + if (!viewer.scene.primitives.remove(tileset)) tileset.destroy(); + } +} + +/** + * What the application scene hands the application about its viewer. + * @param {object} viewer + */ +export function applicationViewerHooks(viewer) { + return { + // Drops the draw commands the scene keeps after it stops drawing them; + // run after a drawn frame (see sceneCommandRelease.js). + trimStaleCommands: () => trimStaleSceneCommands(viewer.scene), + // Keeps the globe drawing in an inline panel whose host stops animation + // frames (embed mode, src/app/embed.js). + keepPanelRendering: (options) => keepPanelRendering(viewer, options), + // Whether an entity is one of the viewer's own (Cockpit asks whether + // the aircraft it flies still draws). + viewerDrawsEntity: (entity) => viewer.entities.contains(entity), + }; +} diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 13b681f44..723a28c2f 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -1 +1 @@ -["dev/conformance/main.js", "src/app/scene.js", "src/data/geoImportPins.js"] +["src/data/geoImportPins.js"] diff --git a/src/render/noCesiumOutsideRender.test.mjs b/src/render/noCesiumOutsideRender.test.mjs index c0670a85b..cbb312e8b 100644 --- a/src/render/noCesiumOutsideRender.test.mjs +++ b/src/render/noCesiumOutsideRender.test.mjs @@ -19,6 +19,9 @@ * file. Any name `cesium` counts, so a config field of that name would * over-report rather than slip through. * + * Two files name the adapter by design and are not on the list: + * `ADAPTER_ENTRIES` below allows each exactly the adapter modules it needs. + * * Runtime code is every `.js`, `.mjs`, `.cjs` and `.vue` file under `src/`, * `server/` and `dev/`, except tests and test support. */ import assert from 'node:assert/strict'; @@ -52,6 +55,25 @@ const isTestSupport = (file) => TEST_ONLY.has(file); const isAdapter = (file) => file.startsWith('src/render/cesium/'); +/** + * The two places outside the adapter that name it by design, each limited + * to the adapter modules listed here; any other way they reach Cesium + * counts as above. Neither is a file still to port, so neither is on the + * allow-list; this list is never grown. + * - The application scene is the composition root: it picks the Cesium + * renderer as the default and takes the viewer hooks it hands the + * application from the adapter's application module. + * - The conformance page runs the suite on the Cesium adapter's harness + * and draws the reference scenes on its scene renderer. + */ +const ADAPTER_ENTRIES = { + 'src/app/scene.js': ['src/render/cesium/application.js'], + 'dev/conformance/main.js': [ + 'src/render/cesium/harness.js', + 'src/render/cesium/sceneRenderer.js', + ], +}; + const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8' }); const tracked = git( @@ -70,19 +92,27 @@ const runtimeFiles = tracked.filter( /\.(?:[cm]?js|vue)$/.test(file) && !isTestSupport(file) && !isAdapter(file), ); -/** Whether an import specifier from `file` reaches Cesium. */ -function reachesCesium(file, specifier) { +/** + * The repository path a relative or root-relative specifier names. Vite + * reads `/x` from the project root, not the filesystem's. + */ +function targetOf(file, specifier) { const bare = specifier.replace(/[?#].*$/, ''); - if (/^(?:cesium|@cesium\/[^/]+)(?:\/|$)/.test(bare)) return true; - if (!bare.startsWith('.') && !bare.startsWith('/')) return false; - // Vite reads `/x` from the project root, not the filesystem's. + if (!bare.startsWith('.') && !bare.startsWith('/')) return null; const from = bare.startsWith('/') ? root : path.join(root, path.dirname(file)); - const target = path - .relative(root, path.join(from, bare)) - .split(path.sep) - .join('/'); + return path.relative(root, path.join(from, bare)).split(path.sep).join('/'); +} + +/** Whether an import specifier from `file` reaches Cesium. */ +function reachesCesium(file, specifier) { + const allowed = ADAPTER_ENTRIES[file]; + if (allowed?.includes(targetOf(file, specifier))) return false; + const bare = specifier.replace(/[?#].*$/, ''); + if (/^(?:cesium|@cesium\/[^/]+)(?:\/|$)/.test(bare)) return true; + const target = targetOf(file, specifier); + if (target === null) return false; return ( isAdapter(target) || /^node_modules\/(?:cesium|@cesium\/[^/]+)(?:\/|$)/.test(target) @@ -233,6 +263,106 @@ test('every allow-listed file still reaches Cesium', () => { assert.deepEqual(stale, [], `Remove these from ${LIST}.`); }); +test('the files that name the adapter by design import exactly what they are allowed', () => { + const present = new Set(runtimeFiles); + for (const [file, modules] of Object.entries(ADAPTER_ENTRIES)) { + assert.ok(present.has(file), `${file} is gone: drop it from the list`); + assert.ok(!allowList.includes(file), `${file} is on ${LIST} too`); + const { imports } = scan(readFileSync(path.join(root, file), 'utf8')); + const named = new Set(imports.map((s) => targetOf(file, s))); + for (const module of modules) + assert.ok(named.has(module), `${file} no longer imports ${module}`); + } +}); + +/** Every node under `node`, with its parent. */ +function* nodesOf(node, parent = null) { + if (!node || typeof node !== 'object') return; + if (Array.isArray(node)) { + for (const child of node) yield* nodesOf(child, parent); + return; + } + if (typeof node.type === 'string') yield [node, parent]; + for (const [key, value] of Object.entries(node)) + if (!['loc', 'comments', 'tokens', 'extra'].includes(key)) + yield* nodesOf(value, typeof node.type === 'string' ? node : parent); +} + +test('the files that name the adapter by design take named exports, never Cesium itself', () => { + for (const [file, modules] of Object.entries(ADAPTER_ENTRIES)) { + const parsed = parsers.babel.parse( + readFileSync(path.join(root, file), 'utf8'), + ); + // A static import by name only: no namespace or default binding, no + // dynamic import, and no forwarding of the module. + for (const [node] of nodesOf(parsed.program)) { + const source = node.source?.value; + if (typeof source !== 'string') continue; + if (!modules.includes(targetOf(file, source))) continue; + assert.equal( + node.type, + 'ImportDeclaration', + `${file} must import ${source} statically and not forward it`, + ); + assert.deepEqual( + node.specifiers + .filter((s) => s.type !== 'ImportSpecifier') + .map((s) => s.local.name), + [], + `${file} must import ${source} by name`, + ); + } + // The allowed modules hand out no Cesium namespace: no export from the + // package, and no exported value that is the namespace itself (members + // of it, such as `Cesium.Math`, are the adapter's own business). + for (const module of modules) { + const program = parsers.babel.parse( + readFileSync(path.join(root, module), 'utf8'), + ).program; + const fromCesium = ({ source }) => { + if (typeof source?.value !== 'string') return false; + const bare = source.value.replace(/[?#].*$/, ''); + const target = targetOf(module, bare) ?? ''; + return /^(?:(?:node_modules\/)?(?:cesium|@cesium\/[^/]+))(?:\/|$)/.test( + target || bare, + ); + }; + const namespaces = new Set( + program.body + .filter((n) => n.type === 'ImportDeclaration' && fromCesium(n)) + .flatMap((n) => n.specifiers.map((s) => s.local.name)), + ); + for (const node of program.body) { + if (!node.type.startsWith('Export')) continue; + assert.ok(!fromCesium(node), `${module} must not re-export Cesium`); + for (const [inner, parent] of nodesOf(node)) { + if (inner.type !== 'Identifier' || !namespaces.has(inner.name)) + continue; + // Handing the namespace to the adapter's own functions is fine; + // giving it out as a value is not. + const handedOut = + [ + 'ExportSpecifier', + 'ExportDefaultDeclaration', + 'ReturnStatement', + 'SpreadElement', + 'ArrayExpression', + ].includes(parent?.type) || + (parent?.type === 'VariableDeclarator' && parent.init === inner) || + (parent?.type === 'ObjectProperty' && parent.value === inner) || + (parent?.type === 'ArrowFunctionExpression' && + parent.body === inner) || + (parent?.type === 'AssignmentExpression' && parent.right === inner); + assert.ok( + !handedOut, + `${module} must not export ${inner.name} itself`, + ); + } + } + } + } +}); + test('the allow-list only shrinks', (t) => { // Any git failure fails the check: only the list's confirmed absence on // origin/main (before it lands) skips it.