Compare commits

..
Author SHA1 Message Date
ohif-bot b996070583 chore(version): Update package versions to 3.13.0-beta.115 [skip ci] 2026-07-08 18:15:05 +00:00
Bill Wallace 1b6fa2194e Revert "feat: Add extensibility for tmtv and segmentation modes"
This reverts commit 84c7d17b13.
2026-07-08 14:11:24 -04:00
Bill Wallace 84c7d17b13 feat: Add extensibility for tmtv and segmentation modes 2026-07-08 14:08:59 -04:00
ohif-bot 76687cf496 chore(version): Update package versions to 3.13.0-beta.114 [skip ci] 2026-07-07 19:33:37 +00:00
Bill WallaceandClaude Opus 4.8 3dd5c70cb2 feat: Add customization URL parameter (#5992)
* Add customization URL parameter

* fix: Preserve should be customizeable

* Update customizations docs

* fix: Overlay items on patient name

* Add customization test

* Fix resolve to absolute path

* fix: Warn on no data in load

* Remove unused customization stuff

* fix: PR comments

* Update stored parameters to only use an array for mulitples

* Remove requires ohif.* special call out

* Remove strict mode

* PR comments

* Document segmentation examples

* Add three examples as requested

* PR comments

* lock

* Remove old customizatoin export

* fix: Ordering issues on customization loads

* fix: Use correct default for dev builds app config

* Fixes for conflicts

* chore: restore pnpm-lock.yaml to match master

The lockfile diff was incidental peer-descriptor churn and carried no
functional dependency change. It tripped the CircleCI security-audit gate
(which only runs when pnpm-lock.yaml is in the PR diff), surfacing a
pre-existing critical `decompress` transitive vuln that also exists on
master. Restoring master's lockfile removes the audit trigger.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(ci): restore json5 lockfile entry; ignore unfixable decompress GHSA

The previous commit restored pnpm-lock.yaml from master, which dropped the
json5@2.2.3 entry that platform/core legitimately depends on (JSONC parsing
for the customization feature). That broke `--frozen-lockfile` install
(ERR_PNPM_OUTDATED_LOCKFILE). This restores the correct lockfile.

Because the lockfile must change (json5), the CircleCI security-audit gate
runs and previously failed on a critical `decompress` <=4.2.1 zip-slip
advisory. This is a pre-existing transitive vuln (present on master too) with
no published patch — decompress's latest release is 4.2.1, so no version
bump/override can resolve it. It reaches the tree only via @itk-wasm/dam, a
build/data-asset extraction tool under @cornerstonejs/labelmap-interpolation.

Add GHSA-mp2f-45pm-3cg9 to the existing pnpm-workspace.yaml auditConfig
ignoreGhsas accepted-risk list, matching how the repo already exempts other
build-tooling advisories. `pnpm audit --audit-level high` now passes locally
(1 critical ignored, 0 high).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(e2e): fix visitStudy URL encoding that broke mpr2 study load

The visitStudy rewrite (added for the ?customization= option) built the URL
with new URLSearchParams({ StudyInstanceUIDs: studyInstanceUID }), which
percent-encodes the value. mpr2.spec.ts embeds an extra param in the UID
string ('<uid>&hangingprotocolid=mpr'), so the & and = were encoded and the
whole thing collapsed into one invalid StudyInstanceUIDs value -> the study
could not be found ('studies are not available'), the viewer never rendered,
and the side-panel-header-right click timed out.

Restore master's raw concatenation for StudyInstanceUIDs (so embedded params
survive as separate query params) while still appending the customization
option separately. Only mpr2 embeds & in the UID, matching the single failure.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* PR comments

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 15:30:27 -04:00
ohif-bot 3d9a17bc0c chore(version): Update package versions to 3.13.0-beta.113 [skip ci] 2026-07-07 18:01:19 +00:00
Joe Boccanfuso 333d73e334 fix(security): ignore decompress security vulnerability (#6125) 2026-07-07 13:58:15 -04:00
ohif-bot e381d22200 chore(version): Update package versions to 3.13.0-beta.112 [skip ci] 2026-07-07 17:21:45 +00:00
Alireza f8546ce0e0 fix: recipe config cleanup, report-only CSP, logout redirect validation (#6124) 2026-07-07 13:18:46 -04:00
ohif-bot 973631b7e8 chore(version): Update package versions to 3.13.0-beta.111 [skip ci] 2026-07-06 13:38:47 +00:00
Alireza e0f42d4f1d fix(dicom-pdf): enhance PDF loading with authentication support
- move authenticated rendered media loading into the datasource\n- route DICOM video display sets through Cornerstone video viewports\n- add a 3.12 to 3.13 migration note for the removed DICOM-video viewport namespace
2026-07-06 09:35:26 -04:00
132 changed files with 4336 additions and 823 deletions

No files matched your search

+1
View File
@@ -23,6 +23,7 @@ concurrency:
jobs:
playwright-tests:
timeout-minutes: 120
environment: fork-pr-approval
runs-on: [self-hosted, nashua]
strategy:
fail-fast: false
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-cornerstone-dicom-pmap",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "DICOM Parametric Map read workflow",
"author": "OHIF",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-cornerstone-dicom-rt",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "DICOM RT read workflow",
"author": "OHIF",
"license": "MIT",
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-cornerstone-dicom-seg",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "DICOM SEG read workflow",
"author": "OHIF",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-cornerstone-dicom-sr",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "OHIF extension for an SR Cornerstone Viewport",
"author": "OHIF",
"license": "MIT",
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-cornerstone-dynamic-volume",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "OHIF extension for 4D volumes data",
"author": "OHIF",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-cornerstone",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "OHIF extension for Cornerstone",
"author": "OHIF",
"license": "MIT",
@@ -14,7 +14,7 @@ import './CustomizableViewportOverlay.css';
import { useViewportRendering } from '../../hooks';
const EPSILON = 1e-4;
const { formatPN } = utils;
const { formatPN, formatValue } = utils;
type ViewportData = StackViewportData | VolumeViewportData;
@@ -184,7 +184,12 @@ function CustomizableViewportOverlay({
} else {
const renderItem = customizationService.transform(item);
if (typeof renderItem.contentF === 'function') {
if (
renderItem &&
typeof renderItem === 'object' &&
'contentF' in renderItem &&
typeof renderItem.contentF === 'function'
) {
return renderItem.contentF(overlayItemProps);
}
}
@@ -357,7 +362,8 @@ function OverlayItem(props) {
const { instance, customization = {} } = props;
const { color, attribute, title, label, background } = customization;
const value = customization.contentF?.(props, customization) ?? instance?.[attribute];
if (value === undefined || value === null) {
const displayValue = formatValue(value);
if (displayValue === null || displayValue === '') {
return null;
}
return (
@@ -367,7 +373,7 @@ function OverlayItem(props) {
title={title}
>
{label ? <span className="mr-1 shrink-0">{label}</span> : null}
<span className="ml-0 shrink-0">{value}</span>
<span className="ml-0 shrink-0">{displayValue}</span>
</div>
);
}
@@ -1,9 +1,11 @@
import type { Button } from '@ohif/core/types';
import { EVENTS } from '@cornerstonejs/core';
import { ViewportGridService } from '@ohif/core';
import { ViewportGridService, ToolbarService } from '@ohif/core';
import i18n from 'i18next';
const { TOOLBAR_SECTIONS } = ToolbarService;
const callbacks = (toolName: string) => [
{
commandName: 'setViewportForToolConfiguration',
@@ -708,4 +710,91 @@ const toolbarButtons: Button[] = [
// },
];
export default toolbarButtons;
/**
* Default toolbar layout: which buttons appear in each toolbar section.
* Registered as a customization so modes (and `?customization=` modules) can
* append/replace entries without rebuilding.
*/
export const toolbarSections = {
[TOOLBAR_SECTIONS.primary]: [
'MeasurementTools',
'Zoom',
'Pan',
'TrackballRotate',
'WindowLevel',
'Capture',
'Layout',
'Crosshairs',
'MoreTools',
],
[TOOLBAR_SECTIONS.viewportActionMenu.topLeft]: ['orientationMenu', 'dataOverlayMenu'],
[TOOLBAR_SECTIONS.viewportActionMenu.bottomMiddle]: ['AdvancedRenderingControls'],
AdvancedRenderingControls: [
'windowLevelMenuEmbedded',
'voiManualControlMenu',
'Colorbar',
'opacityMenu',
'thresholdMenu',
],
[TOOLBAR_SECTIONS.viewportActionMenu.topRight]: [
'modalityLoadBadge',
'trackingStatus',
'navigationComponent',
],
[TOOLBAR_SECTIONS.viewportActionMenu.bottomLeft]: ['windowLevelMenu'],
MeasurementTools: [
'Length',
'Bidirectional',
'ArrowAnnotate',
'EllipticalROI',
'RectangleROI',
'CircleROI',
'PlanarFreehandROI',
'SplineROI',
'LivewireContour',
],
MoreTools: [
'Reset',
'rotate-right',
'flipHorizontal',
'ImageSliceSync',
'ReferenceLines',
'ImageOverlayViewer',
'StackScroll',
'invert',
'Probe',
'Cine',
'Angle',
'CobbAngle',
'Magnify',
'CalibrationLine',
'TagBrowser',
'AdvancedMagnify',
'UltrasoundDirectionalTool',
'WindowLevelRegion',
'SegmentLabelTool',
],
};
/**
* Customizations registered (at default scope) by the cornerstone extension:
* - `cornerstone.toolbarButtons` – the default toolbar button definitions
* - `cornerstone.toolbarSections` – the default toolbar layout (section -> button ids)
*
* Modes read these by name in `onModeEnter`; URL `?customization=` modules can
* extend them with immutability-helper commands (e.g. `$push` a new button).
*/
const toolbarButtonsCustomization = {
'cornerstone.toolbarButtons': toolbarButtons,
'cornerstone.toolbarSections': toolbarSections,
};
export { toolbarButtons };
export default toolbarButtonsCustomization;
@@ -8,6 +8,7 @@ import volumeRenderingCustomization from './customizations/volumeRenderingCustom
import colorbarCustomization from './customizations/colorbarCustomization';
import modalityColorMapCustomization from './customizations/modalityColorMapCustomization';
import windowLevelPresetsCustomization from './customizations/windowLevelPresetsCustomization';
import toolbarButtonsCustomization from './customizations/toolbarButtonsCustomization';
import miscCustomization from './customizations/miscCustomization';
import captureViewportModalCustomization from './customizations/captureViewportModalCustomization';
import viewportDownloadWarningCustomization from './customizations/viewportDownloadWarningCustomization';
@@ -32,6 +33,7 @@ function getCustomizationModule({ commandsManager, servicesManager, extensionMan
...colorbarCustomization,
...modalityColorMapCustomization,
...windowLevelPresetsCustomization,
...toolbarButtonsCustomization,
...miscCustomization,
...captureViewportModalCustomization,
...viewportDownloadWarningCustomization,
@@ -3,6 +3,7 @@ import {
WindowLevelTool,
SegmentBidirectionalTool,
StackScrollTool,
PlanarRotateTool,
VolumeRotateTool,
ZoomTool,
MIPJumpToClickTool,
@@ -74,6 +75,7 @@ export default function initCornerstoneTools(configuration = {}) {
addTool(SegmentBidirectionalTool);
addTool(WindowLevelTool);
addTool(StackScrollTool);
addTool(PlanarRotateTool);
addTool(VolumeRotateTool);
addTool(ZoomTool);
addTool(ProbeTool);
@@ -138,6 +140,7 @@ const toolNames = {
WindowLevel: WindowLevelTool.toolName,
StackScroll: StackScrollTool.toolName,
Zoom: ZoomTool.toolName,
PlanarRotate: PlanarRotateTool.toolName,
VolumeRotate: VolumeRotateTool.toolName,
MipJumpToClick: MIPJumpToClickTool.toolName,
Length: LengthTool.toolName,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-default",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "Common/default features and functionality for basic image viewing",
"author": "OHIF Core Team",
"license": "MIT",
@@ -18,6 +18,7 @@ import getDirectURL from '../utils/getDirectURL';
import { fixBulkDataURI } from './utils/fixBulkDataURI';
import { HeadersInterface } from '@ohif/core/src/types/RequestHeaders';
import { getGetThumbnailSrc, ThumbnailContext } from './retrieveThumbnail';
import { getRenderedURL } from './retrieveRendered';
const { DicomMetaDictionary, DicomDict } = dcmjs.data;
@@ -108,7 +109,6 @@ export type BulkDataURIConfig = {
relativeResolution?: 'studies' | 'series';
};
/**
* The header options are the options passed into the generateWadoHeader
* command. This takes an extensible set of attributes to allow future enhancements.
@@ -291,6 +291,14 @@ function createDicomWebApi(dicomWebConfig: DicomWebConfig, servicesManager) {
params
);
},
renderedURL: (params, options) => {
return getRenderedURL({
config: dicomWebConfig,
getAuthorizationHeader,
retrieve: implementation.retrieve,
userAuthenticationService,
})(params, options);
},
/**
* Provide direct access to the dicom web client for certain use cases
* where the dicom web client is used by an external library such as the
@@ -52,6 +52,7 @@ function processResults(qidoStudies) {
accession: getString(qidoStudy['00080050']) || '', // short string, probably a number?
mrn: getString(qidoStudy['00100020']) || '', // medicalRecordNumber
patientName: utils.formatPN(getName(qidoStudy['00100010'])) || '',
patientBirthDate: getString(qidoStudy['00100030']) || '', // YYYYMMDD
instances: Number(getString(qidoStudy['00201208'])) || 0, // number
description: getString(qidoStudy['00081030']) || '',
modalities: getString(getModalities(qidoStudy['00080060'], qidoStudy['00080061'])) || '',
@@ -153,6 +154,7 @@ function mapParams(params, options = {}) {
'00081030', // Study Description
'00080060', // Modality
'00080090', // Referring Physician's Name
'00100030', // Patient's Birth Date
// Add more fields here if you want them in the result
].join(',');
@@ -0,0 +1,147 @@
import { fetchRenderedURL, getRenderedURL, isTrustedWadoURL } from './retrieveRendered';
describe('retrieveRendered', () => {
const originalFetch = global.fetch;
const originalCreateObjectURL = URL.createObjectURL;
const originalRevokeObjectURL = URL.revokeObjectURL;
beforeEach(() => {
global.fetch = jest.fn();
URL.createObjectURL = jest.fn(() => 'blob:rendered') as jest.Mock;
URL.revokeObjectURL = jest.fn() as jest.Mock;
jest.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
jest.restoreAllMocks();
global.fetch = originalFetch;
URL.createObjectURL = originalCreateObjectURL;
URL.revokeObjectURL = originalRevokeObjectURL;
});
it('returns null when there is no resolved URL', async () => {
const result = await fetchRenderedURL({
url: undefined,
wadoRoot: 'https://example.com/dicomweb',
headers: { Authorization: 'Bearer token' },
});
expect(result).toEqual({ url: null });
expect(global.fetch).not.toHaveBeenCalled();
});
it('returns the direct URL without fetching when there is no authorization header', async () => {
const result = await fetchRenderedURL({
url: 'https://example.com/dicomweb/rendered',
wadoRoot: 'https://example.com/dicomweb',
headers: {},
});
expect(result).toEqual({ url: 'https://example.com/dicomweb/rendered' });
expect(global.fetch).not.toHaveBeenCalled();
});
it('does not attach auth headers to untrusted absolute URLs', async () => {
const result = await fetchRenderedURL({
url: 'https://untrusted.example.com/rendered',
wadoRoot: 'https://example.com/dicomweb',
headers: { Authorization: 'Bearer token' },
});
expect(result).toEqual({ url: 'https://untrusted.example.com/rendered' });
expect(global.fetch).not.toHaveBeenCalled();
});
it('fetches trusted URLs with auth and returns a revocable object URL', async () => {
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
blob: jest.fn().mockResolvedValueOnce(new Blob(['pdf'], { type: 'application/pdf' })),
});
const result = await fetchRenderedURL({
url: 'https://example.com/dicomweb/studies/1/rendered',
wadoRoot: 'https://example.com/dicomweb',
headers: { Authorization: 'Bearer token' },
});
expect(global.fetch).toHaveBeenCalledWith(
'https://example.com/dicomweb/studies/1/rendered',
expect.objectContaining({
method: 'GET',
headers: { Authorization: 'Bearer token' },
})
);
expect(result.url).toBe('blob:rendered');
result.revoke?.();
result.revoke?.();
expect(URL.revokeObjectURL).toHaveBeenCalledTimes(1);
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:rendered');
});
it('returns null and triggers unauthenticated handling on 401/403 responses', async () => {
const handleUnauthenticated = jest.fn();
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: false,
status: 401,
});
const result = await fetchRenderedURL({
url: 'https://example.com/dicomweb/studies/1/rendered',
wadoRoot: 'https://example.com/dicomweb',
headers: { Authorization: 'Bearer token' },
userAuthenticationService: { handleUnauthenticated },
});
expect(result).toEqual({ url: null });
expect(handleUnauthenticated).toHaveBeenCalledTimes(1);
});
it('revokes an object URL created after the request was aborted', async () => {
const abortController = new AbortController();
(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
blob: jest.fn().mockImplementationOnce(async () => {
abortController.abort();
return new Blob(['pdf'], { type: 'application/pdf' });
}),
});
const result = await fetchRenderedURL({
url: 'https://example.com/dicomweb/studies/1/rendered',
wadoRoot: 'https://example.com/dicomweb',
headers: { Authorization: 'Bearer token' },
signal: abortController.signal,
});
expect(result).toEqual({ url: null });
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:rendered');
});
it('resolves directURL through the datasource retrieve API', async () => {
const renderedURL = getRenderedURL({
config: { wadoRoot: 'https://example.com/dicomweb' },
getAuthorizationHeader: () => ({}),
retrieve: {
directURL: jest.fn().mockResolvedValueOnce('https://example.com/dicomweb/rendered'),
},
});
await expect(renderedURL({ instance: {} })).resolves.toEqual({
url: 'https://example.com/dicomweb/rendered',
});
});
it('trusts URLs that share the configured WADO origin', () => {
expect(
isTrustedWadoURL('/dicomweb/studies/1/rendered', `${window.location.origin}/dicomweb`)
).toBe(true);
expect(
isTrustedWadoURL(
'https://other.example.com/dicomweb/studies/1/rendered',
'https://example.com/dicomweb'
)
).toBe(false);
});
});
@@ -0,0 +1,141 @@
import { HeadersInterface } from '@ohif/core/src/types/RequestHeaders';
type RetrieveApi = {
directURL: (params: unknown) => unknown;
};
type RenderedURLConfig = {
wadoRoot?: string;
};
type UserAuthenticationService = {
handleUnauthenticated?: () => unknown;
};
type GetRenderedURLDeps = {
config: RenderedURLConfig;
getAuthorizationHeader: () => HeadersInterface;
retrieve: RetrieveApi;
userAuthenticationService?: UserAuthenticationService;
};
type RenderedURLOptions = {
signal?: AbortSignal;
};
type FetchRenderedURLOptions = RenderedURLOptions & {
url?: string | null;
wadoRoot?: string;
headers?: HeadersInterface;
userAuthenticationService?: UserAuthenticationService;
};
export type RenderedURLResult = {
url: string | null;
revoke?: () => void;
};
export function getRenderedURL({
config,
getAuthorizationHeader,
retrieve,
userAuthenticationService,
}: GetRenderedURLDeps) {
return async function renderedURL(
params: unknown,
options: RenderedURLOptions = {}
): Promise<RenderedURLResult> {
const resolvedUrl = (await retrieve.directURL(params)) as string | undefined | null;
return fetchRenderedURL({
url: resolvedUrl,
wadoRoot: config.wadoRoot,
headers: getAuthorizationHeader(),
signal: options.signal,
userAuthenticationService,
});
};
}
export async function fetchRenderedURL({
url,
wadoRoot,
headers,
signal,
userAuthenticationService,
}: FetchRenderedURLOptions): Promise<RenderedURLResult> {
if (!url || signal?.aborted) {
return { url: null };
}
if (!headers?.Authorization || !isTrustedWadoURL(url, wadoRoot)) {
return { url };
}
try {
const response = await fetch(url, {
method: 'GET',
headers: headers as Record<string, string>,
signal,
});
if (!response.ok) {
if (response.status === 401 || response.status === 403) {
userAuthenticationService?.handleUnauthenticated?.();
}
console.warn(`rendered media fetch failed with status ${response.status}`);
return { url: null };
}
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
if (signal?.aborted) {
URL.revokeObjectURL(objectUrl);
return { url: null };
}
return {
url: objectUrl,
revoke: createRevokeOnce(objectUrl),
};
} catch (error) {
if ((error as { name?: string })?.name === 'AbortError') {
return { url: null };
}
console.warn('rendered media fetch failed', error);
return { url: null };
}
}
export function isTrustedWadoURL(url: string, wadoRoot?: string): boolean {
if (!wadoRoot) {
return false;
}
try {
const parsedUrl = new URL(url, window.location.href);
const parsedWadoRoot = new URL(wadoRoot, window.location.href);
const isHttpUrl = parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:';
const isHttpWadoRoot =
parsedWadoRoot.protocol === 'http:' || parsedWadoRoot.protocol === 'https:';
return isHttpUrl && isHttpWadoRoot && parsedUrl.origin === parsedWadoRoot.origin;
} catch {
return false;
}
}
function createRevokeOnce(objectUrl: string) {
let revoked = false;
return () => {
if (revoked) {
return;
}
URL.revokeObjectURL(objectUrl);
revoked = true;
};
}
@@ -52,6 +52,7 @@ function createDicomWebProxyApi(dicomWebProxyConfig, servicesManager: AppTypes.S
retrieve: {
getGetThumbnailSrc: (...args) => dicomWebDelegate.retrieve.getGetThumbnailSrc(...args),
directURL: (...args) => dicomWebDelegate.retrieve.directURL(...args),
renderedURL: (...args) => dicomWebDelegate.retrieve.renderedURL(...args),
series: {
metadata: async (...args) => dicomWebDelegate.retrieve.series.metadata(...args),
},
@@ -62,7 +63,8 @@ function createDicomWebProxyApi(dicomWebProxyConfig, servicesManager: AppTypes.S
reject: {
series: (...args) => dicomWebDelegate?.reject?.series?.(...args),
},
deleteStudyMetadataPromise: (...args) => dicomWebDelegate?.deleteStudyMetadataPromise?.(...args),
deleteStudyMetadataPromise: (...args) =>
dicomWebDelegate?.deleteStudyMetadataPromise?.(...args),
getImageIdsForDisplaySet: (...args) => dicomWebDelegate?.getImageIdsForDisplaySet?.(...args),
getImageIdsForInstance: (...args) => dicomWebDelegate?.getImageIdsForInstance?.(...args),
getConfig: (...args) =>
@@ -242,6 +242,24 @@ function createMergeDataSourceApi(
defaultDataSourceName,
extensionManager,
}),
renderedURL: (...args: unknown[]) => {
const [dataSource] = extensionManager.getDataSources(defaultDataSourceName);
const renderedURL = get(dataSource, 'retrieve.renderedURL');
if (renderedURL) {
return renderedURL.apply(dataSource, args);
}
const directURL = get(dataSource, 'retrieve.directURL');
if (!directURL) {
return Promise.resolve({ url: null });
}
return Promise.resolve(directURL.apply(dataSource, [args[0]])).then(url => ({
url: (url as string | undefined | null) || null,
}));
},
series: {
metadata: (...args: unknown[]) =>
callForAllDataSourcesAsync({
@@ -28,7 +28,7 @@ function ViewerHeader({ appConfig }: withAppTypes<{ appConfig: AppTypes.Config }
if (dataSourceIdx !== -1 && existingDataSource) {
searchQuery.append('datasources', pathname.substring(dataSourceIdx + 1));
}
preserveQueryParameters(searchQuery);
preserveQueryParameters(searchQuery, customizationService);
navigate({
pathname: '/',
@@ -1,4 +1,5 @@
import React from 'react';
import { utils } from '@ohif/core';
export default {
'ohif.overlayItem': function (props) {
@@ -13,7 +14,8 @@ export default {
: this.contentF && typeof this.contentF === 'function'
? this.contentF(props)
: null;
if (!value) {
const displayValue = utils.formatValue(value);
if (!displayValue) {
return null;
}
@@ -24,7 +26,7 @@ export default {
title={this.title || ''}
>
{this.label && <span className="mr-1 shrink-0">{this.label}</span>}
<span className="font-light">{value}</span>
<span className="font-light">{displayValue}</span>
</span>
);
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-dicom-microscopy",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "OHIF extension for DICOM microscopy",
"author": "Bill Wallace, md-prog",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-dicom-pdf",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "OHIF extension for PDF display",
"author": "OHIF",
"license": "MIT",
@@ -14,12 +14,17 @@ const _getDisplaySetsFromSeries = (instances, servicesManager, extensionManager)
const { Modality, SOPInstanceUID } = instance;
const { SeriesDescription = 'PDF', MIMETypeOfEncapsulatedDocument } = instance;
const { SeriesNumber, SeriesDate, SeriesInstanceUID, StudyInstanceUID, SOPClassUID } = instance;
const renderedUrl = dataSource.retrieve.directURL({
const renderedUrlParams = {
instance,
tag: 'EncapsulatedDocument',
defaultType: MIMETypeOfEncapsulatedDocument || 'application/pdf',
singlepart: 'pdf',
});
};
const renderedUrl = dataSource.retrieve.directURL(renderedUrlParams);
const getRenderedUrl = dataSource.retrieve.renderedURL
? options =>
dataSource.retrieve.renderedURL({ ...renderedUrlParams, url: renderedUrl }, options)
: undefined;
const displaySet = {
//plugin: id,
@@ -36,6 +41,7 @@ const _getDisplaySetsFromSeries = (instances, servicesManager, extensionManager)
referencedImages: null,
measurements: null,
renderedUrl: renderedUrl,
getRenderedUrl,
instances: [instance],
thumbnailSrc: null,
isDerivedDisplaySet: true,
+2 -8
View File
@@ -28,15 +28,9 @@ const dicomPDFExtension = {
* @param {object} [configuration={}]
* @param {object|array} [configuration.csToolsConfig] - Passed directly to `initCornerstoneTools`
*/
getViewportModule({ servicesManager, extensionManager }) {
getViewportModule() {
const ExtendedOHIFCornerstonePdfViewport = props => {
return (
<OHIFCornerstonePdfViewport
servicesManager={servicesManager}
extensionManager={extensionManager}
{...props}
/>
);
return <OHIFCornerstonePdfViewport {...props} />;
};
return [{ name: 'dicom-pdf', component: ExtendedOHIFCornerstonePdfViewport }];
@@ -33,14 +33,43 @@ function OHIFCornerstonePdfViewport({ displaySets, viewportId = 'pdf-viewport' }
}
const { renderedUrl } = displaySets[0];
const { getRenderedUrl } = displaySets[0];
useEffect(() => {
let isCancelled = false;
let revokeUrl;
const abortController = new AbortController();
const load = async () => {
setUrl(await renderedUrl);
try {
const result = getRenderedUrl
? await getRenderedUrl({ signal: abortController.signal })
: { url: await renderedUrl };
if (isCancelled) {
result?.revoke?.();
return;
}
revokeUrl = result?.revoke;
setUrl(result?.url || null);
} catch (error) {
console.warn('Failed to load PDF', error);
if (!isCancelled) {
setUrl(null);
}
return;
}
};
load();
}, [renderedUrl]);
return () => {
isCancelled = true;
abortController.abort();
revokeUrl?.();
};
}, [renderedUrl, getRenderedUrl]);
return (
<div
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-dicom-video",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "OHIF extension for video display",
"author": "OHIF",
"license": "MIT",
@@ -57,12 +57,16 @@ const _getDisplaySetsFromSeries = (instances, servicesManager, extensionManager)
const { Modality, SOPInstanceUID, SeriesDescription = 'VIDEO', imageId } = instance;
const { SeriesNumber, SeriesDate, SeriesInstanceUID, StudyInstanceUID, NumberOfFrames, url } =
instance;
const videoUrl = dataSource.retrieve.directURL({
const videoUrlParams = {
instance,
singlepart: 'video',
tag: 'PixelData',
url,
});
};
const videoUrl = dataSource.retrieve.directURL(videoUrlParams);
const getVideoUrl = dataSource.retrieve.renderedURL
? options => dataSource.retrieve.renderedURL({ ...videoUrlParams, url: videoUrl }, options)
: undefined;
const displaySet = {
//plugin: id,
Modality,
@@ -76,6 +80,8 @@ const _getDisplaySetsFromSeries = (instances, servicesManager, extensionManager)
SOPClassHandlerId,
referencedImages: null,
measurements: null,
videoUrl,
getVideoUrl,
viewportType: csEnums.ViewportType.VIDEO,
instances: [instance],
getThumbnailSrc: dataSource.retrieve.getGetThumbnailSrc?.(instance),
-44
View File
@@ -1,19 +1,6 @@
import React from 'react';
import getSopClassHandlerModule from './getSopClassHandlerModule';
import { id } from './id';
const Component = React.lazy(() => {
return import(/* webpackPrefetch: true */ './viewports/OHIFCornerstoneVideoViewport');
});
const OHIFCornerstoneVideoViewport = props => {
return (
<React.Suspense fallback={<div>Loading...</div>}>
<Component {...props} />
</React.Suspense>
);
};
/**
*
*/
@@ -23,38 +10,7 @@ const dicomVideoExtension = {
*/
id,
/**
*
*
* @param {object} [configuration={}]
* @param {object|array} [configuration.csToolsConfig] - Passed directly to `initCornerstoneTools`
*/
getViewportModule({ servicesManager, extensionManager }) {
const ExtendedOHIFCornerstoneVideoViewport = props => {
return (
<OHIFCornerstoneVideoViewport
servicesManager={servicesManager}
extensionManager={extensionManager}
{...props}
/>
);
};
return [{ name: 'dicom-video', component: ExtendedOHIFCornerstoneVideoViewport }];
},
getSopClassHandlerModule,
};
function _getToolAlias(toolName) {
let toolAlias = toolName;
switch (toolName) {
case 'EllipticalRoi':
toolAlias = 'SREllipticalRoi';
break;
}
return toolAlias;
}
export default dicomVideoExtension;
@@ -1,55 +0,0 @@
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
function OHIFCornerstoneVideoViewport({ displaySets }) {
if (displaySets && displaySets.length > 1) {
throw new Error(
'OHIFCornerstoneVideoViewport: only one display set is supported for dicom video right now'
);
}
const { videoUrl } = displaySets[0];
const mimeType = 'video/mp4';
const [url, setUrl] = useState(null);
useEffect(() => {
const load = async () => {
setUrl(await videoUrl);
};
load();
}, [videoUrl]);
// Need to copies of the source to fix a firefox bug
return (
<div className="bg-primary-black h-full w-full">
<video
src={url}
controls
controlsList="nodownload"
preload="auto"
className="h-full w-full"
crossOrigin="anonymous"
>
<source
src={url}
type={mimeType}
/>
<source
src={url}
type={mimeType}
/>
Video src/type not supported:{' '}
<a href={url}>
{url} of type {mimeType}
</a>
</video>
</div>
);
}
OHIFCornerstoneVideoViewport.propTypes = {
displaySets: PropTypes.arrayOf(PropTypes.object).isRequired,
};
export default OHIFCornerstoneVideoViewport;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-measurement-tracking",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "Tracking features and functionality for basic image viewing",
"author": "OHIF Core Team",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-test",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "OHIF extension used inside e2e testing",
"author": "OHIF",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-tmtv",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "OHIF extension for Total Metabolic Tumor Volume",
"author": "OHIF",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/extension-ultrasound-pleura-bline",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "",
"author": "Rodrigo Basilio",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-basic-dev-mode",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "Basic OHIF Viewer Using Cornerstone",
"author": "OHIF",
"license": "MIT",
+1 -6
View File
@@ -26,7 +26,6 @@ const dicomsr = {
const dicomvideo = {
sopClassHandler: '@ohif/extension-dicom-video.sopClassHandlerModule.dicom-video',
viewport: '@ohif/extension-dicom-video.viewportModule.dicom-video',
};
const dicompdf = {
@@ -141,11 +140,7 @@ function modeFactory({ modeConfiguration }) {
viewports: [
{
namespace: cs3d.viewport,
displaySetsToDisplay: [ohif.sopClassHandler],
},
{
namespace: dicomvideo.viewport,
displaySetsToDisplay: [dicomvideo.sopClassHandler],
displaySetsToDisplay: [ohif.sopClassHandler, dicomvideo.sopClassHandler],
},
{
namespace: dicompdf.viewport,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-test",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "Basic mode for testing",
"author": "OHIF",
"license": "MIT",
-5
View File
@@ -33,7 +33,6 @@ const dicomsr = {
const dicomvideo = {
sopClassHandler: '@ohif/extension-dicom-video.sopClassHandlerModule.dicom-video',
viewport: '@ohif/extension-dicom-video.viewportModule.dicom-video',
};
const dicompdf = {
@@ -254,10 +253,6 @@ function modeFactory() {
namespace: dicomsr.viewport,
displaySetsToDisplay: [dicomsr.sopClassHandler, dicomsr.sopClassHandler3D],
},
{
namespace: dicomvideo.viewport,
displaySetsToDisplay: [dicomvideo.sopClassHandler],
},
{
namespace: dicompdf.viewport,
displaySetsToDisplay: [dicompdf.sopClassHandler],
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-basic",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "A basic mode used to build other modes on top of",
"author": "OHIF Contributors",
"license": "MIT",
+22 -77
View File
@@ -1,11 +1,9 @@
import update from 'immutability-helper';
import { ToolbarService, utils } from '@ohif/core';
import { utils } from '@ohif/core';
import initToolGroups from './initToolGroups';
import toolbarButtons from './toolbarButtons';
import { id } from './id';
const { TOOLBAR_SECTIONS } = ToolbarService;
const { structuredCloneWithFunctions } = utils;
/**
@@ -44,7 +42,6 @@ export const dicomsr = {
export const dicomvideo = {
sopClassHandler: '@ohif/extension-dicom-video.sopClassHandlerModule.dicom-video',
viewport: '@ohif/extension-dicom-video.viewportModule.dicom-video',
};
export const dicomecg = {
@@ -146,9 +143,22 @@ export function onModeEnter({
// Init Default and SR ToolGroups
initToolGroups(extensionManager, toolGroupService, commandsManager);
toolbarService.register(this.toolbarButtons);
// Toolbar buttons and layout may be supplied either as a customization name
// (a string, resolved through the customization service so `?customization=`
// modules can extend the cornerstone-registered defaults) or as a literal
// value (the button array / sections object) for modes that define them inline.
const resolveToolbarCustomization = (value: unknown) =>
typeof value === 'string' ? customizationService.getCustomization(value) : value;
for (const [key, section] of Object.entries(this.toolbarSections)) {
const toolbarButtons = resolveToolbarCustomization(this.toolbarButtons) as any;
const toolbarSections = (resolveToolbarCustomization(this.toolbarSections) ?? {}) as Record<
string,
string[]
>;
toolbarService.register(toolbarButtons);
for (const [key, section] of Object.entries(toolbarSections)) {
toolbarService.updateSection(key, section);
}
@@ -213,74 +223,6 @@ export function onModeExit({ servicesManager }: withAppTypes) {
cornerstoneViewportService.destroy();
}
export const toolbarSections = {
[TOOLBAR_SECTIONS.primary]: [
'MeasurementTools',
'Zoom',
'Pan',
'TrackballRotate',
'WindowLevel',
'Capture',
'Layout',
'Crosshairs',
'MoreTools',
],
[TOOLBAR_SECTIONS.viewportActionMenu.topLeft]: ['orientationMenu', 'dataOverlayMenu'],
[TOOLBAR_SECTIONS.viewportActionMenu.bottomMiddle]: ['AdvancedRenderingControls'],
AdvancedRenderingControls: [
'windowLevelMenuEmbedded',
'voiManualControlMenu',
'Colorbar',
'opacityMenu',
'thresholdMenu',
],
[TOOLBAR_SECTIONS.viewportActionMenu.topRight]: [
'modalityLoadBadge',
'trackingStatus',
'navigationComponent',
],
[TOOLBAR_SECTIONS.viewportActionMenu.bottomLeft]: ['windowLevelMenu'],
MeasurementTools: [
'Length',
'Bidirectional',
'ArrowAnnotate',
'EllipticalROI',
'RectangleROI',
'CircleROI',
'PlanarFreehandROI',
'SplineROI',
'LivewireContour',
],
MoreTools: [
'Reset',
'rotate-right',
'flipHorizontal',
'ImageSliceSync',
'ReferenceLines',
'ImageOverlayViewer',
'StackScroll',
'invert',
'Probe',
'Cine',
'Angle',
'CobbAngle',
'Magnify',
'CalibrationLine',
'TagBrowser',
'AdvancedMagnify',
'UltrasoundDirectionalTool',
'WindowLevelRegion',
'SegmentLabelTool',
],
};
export const basicLayout = {
id: ohif.layout,
props: {
@@ -343,7 +285,10 @@ export const modeInstance = {
hide: false,
displayName: 'Non-Longitudinal Basic',
_activatePanelTriggersSubscriptions: [],
toolbarSections,
// Toolbar buttons and layout are referenced by customization name; the
// cornerstone extension registers the defaults and `?customization=` modules
// can extend them. onModeEnter resolves these names via the customization service.
toolbarSections: 'cornerstone.toolbarSections',
/**
* Lifecycle hooks
@@ -365,7 +310,7 @@ export const modeInstance = {
// general handler needs to come last. For this case, the dicomvideo must
// come first to remove video transfer syntax before ohif uses images
sopClassHandlers,
toolbarButtons,
toolbarButtons: 'cornerstone.toolbarButtons',
enableSegmentationEdit: false,
nonModeModalities: NON_IMAGE_MODALITIES,
};
@@ -390,4 +335,4 @@ export const mode = {
};
export default mode;
export { initToolGroups, toolbarButtons };
export { initToolGroups };
+1
View File
@@ -69,6 +69,7 @@ function initDefaultToolGroup(extensionManager, toolGroupService, commandsManage
{ toolName: toolNames.Angle },
{ toolName: toolNames.CobbAngle },
{ toolName: toolNames.Magnify },
{ toolName: toolNames.PlanarRotate },
{ toolName: toolNames.CalibrationLine },
{
toolName: toolNames.PlanarFreehandContourSegmentation,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-longitudinal",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "Longitudinal Workflow",
"author": "OHIF",
"license": "MIT",
+2 -2
View File
@@ -1,6 +1,6 @@
import i18n from 'i18next';
import { id } from './id';
import { initToolGroups, toolbarButtons, cornerstone,
import { initToolGroups, cornerstone,
ohif,
dicomsr,
dicomvideo,
@@ -73,4 +73,4 @@ const mode = {
};
export default mode;
export { initToolGroups, toolbarButtons };
export { initToolGroups };
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-microscopy",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "OHIF mode for DICOM microscopy",
"author": "OHIF",
"license": "MIT",
+1 -2
View File
@@ -17,7 +17,6 @@ export const cornerstone = {
const dicomvideo = {
sopClassHandler: '@ohif/extension-dicom-video.sopClassHandlerModule.dicom-video',
viewport: '@ohif/extension-dicom-video.viewportModule.dicom-video',
};
const dicompdf = {
@@ -107,7 +106,7 @@ function modeFactory({ modeConfiguration }) {
],
},
{
namespace: dicomvideo.viewport,
namespace: cornerstone.viewport,
displaySetsToDisplay: [dicomvideo.sopClassHandler],
},
{
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-preclinical-4d",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "4D Workflow",
"author": "OHIF",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-segmentation",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "OHIF segmentation mode which enables labelmap segmentation read/edit/export",
"author": "@ohif",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-tmtv",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "Total Metabolic Tumor Volume Workflow",
"author": "OHIF",
"license": "MIT",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/mode-ultrasound-pleura-bline",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "Allows users to annotate ultrasound images with pleura B-line annotations.",
"author": "OHIF",
"license": "MIT",
-1
View File
@@ -32,7 +32,6 @@ const dicomsr = {
const dicomvideo = {
sopClassHandler: '@ohif/extension-dicom-video.sopClassHandlerModule.dicom-video',
viewport: '@ohif/extension-dicom-video.viewportModule.dicom-video',
};
const dicompdf = {
+8
View File
@@ -24,6 +24,14 @@
X-Frame-Options = "DENY"
X-XSS-Protection = "1; mode=block"
# Report-Only CSP: observational only, enforces nothing. Watch browser
# consoles for violation reports before ever promoting this to an
# enforcing Content-Security-Policy header. cdnjs.cloudflare.com is for
# the Rollbar snippet in html-templates/rollbar.html (demo builds);
# connect-src stays broad because deployments point the viewer at
# arbitrary DICOMweb origins.
Content-Security-Policy-Report-Only = "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' https: blob:; worker-src 'self' blob:; object-src 'self' blob:; frame-src 'self' blob:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"
cache-control = '''
max-age=0,
no-cache,
+1 -1
View File
@@ -124,5 +124,5 @@
"git add"
]
},
"version": "3.13.0-beta.110"
"version": "3.13.0-beta.115"
}
@@ -0,0 +1,7 @@
# Copy this file to .env next to docker-compose.yml and fill in strong
# values. docker compose refuses to start while either is unset.
KEYCLOAK_ADMIN_PASSWORD=
# POSTGRES_PASSWORD is the single PostgreSQL credential: it provisions the
# keycloak database role and Keycloak reuses it to connect (KC_DB_PASSWORD is
# derived from it in docker-compose.yml), so there is one value, not two.
POSTGRES_PASSWORD=
@@ -0,0 +1,42 @@
# Security notes for this recipe
## Secrets
This recipe no longer ships working credential values. Before `docker compose up`:
- Generate a fresh OAuth client secret for the `ohif_viewer` client and use it
to replace the `REPLACE_WITH_A_GENERATED_CLIENT_SECRET` placeholder in BOTH
`config/ohif-keycloak-realm.json` and `config/oauth2-proxy.cfg` (the two
values must match). To generate one after the realm is imported: Keycloak
admin console -> Clients -> ohif_viewer -> Credentials -> Regenerate.
- Copy `.env.example` to `.env` and set `POSTGRES_PASSWORD` and
`KEYCLOAK_ADMIN_PASSWORD` to strong values. `docker compose` refuses to
start while either is unset. `POSTGRES_PASSWORD` is the single PostgreSQL
credential - it both provisions the `keycloak` database role and is what
Keycloak uses to connect (the compose file derives `KC_DB_PASSWORD` from it),
so there is one database password to set, not two.
## Rotate if you deployed from an earlier checkout
Earlier versions of this recipe committed a fixed client secret and default
admin/database passwords to the public repository. A committed secret stays
burned even after this change, so any deployment created from an earlier
checkout must rotate:
- the `ohif_viewer` client secret (Keycloak admin console -> Clients ->
ohif_viewer -> Credentials -> Regenerate, then update
`config/oauth2-proxy.cfg` to match), and
- the Keycloak admin and PostgreSQL passwords. Note that changing
`POSTGRES_PASSWORD` in `.env` alone does not re-password an existing
database: Postgres only applies it when the `postgres_data` volume is first
initialized. To actually rotate it on an existing deployment, either
`ALTER ROLE keycloak WITH PASSWORD ...` inside the running database or
recreate the `postgres_data` volume.
## CORS
The wildcard `Access-Control-Allow-Origin: *` defaults were removed from
`config/nginx.conf`. The viewer is served by the same nginx as the dcm4chee
proxy, so same-origin deployments need no CORS headers. If you host the viewer
on a different origin, use the commented explicit-origin example in the nginx
config - never `*` on an authenticated endpoint that serves PHI.
@@ -54,6 +54,15 @@ http {
gzip_comp_level 9;
etag on;
# Content-Security-Policy: test in Report-Only mode first and watch
# the browser console for violations before switching the header name
# to the enforcing Content-Security-Policy. Note: nginx add_header does
# not merge into a location that sets its own add_header - if you
# promote this to an active header, re-declare it inside every location
# block that already uses add_header (several proxy locations here do)
# or it will silently not apply there.
# add_header Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' https: blob:; worker-src 'self' blob:; object-src 'self' blob:; frame-src 'self' blob:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" always;
location /sw.js {
add_header Cache-Control "no-cache";
proxy_cache_bypass $http_pragma;
@@ -101,19 +110,25 @@ http {
expires 0;
add_header Cache-Control private;
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Authorization, Origin, X-Requested-With, Content-Type, Accept' always;
if ($request_method = OPTIONS) {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Authorization, Origin, X-Requested-With, Content-Type, Accept';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
# CORS: this recipe serves the viewer from this same nginx, so
# browser requests to this endpoint are same-origin and need NO
# CORS headers at all. If you host the viewer on a different
# origin, allow that origin explicitly and only that origin -
# never use '*' on an authenticated endpoint that serves PHI.
# Cross-origin example (response headers plus OPTIONS preflight):
# add_header 'Access-Control-Allow-Origin' 'https://viewer.example.com' always;
# add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
# add_header 'Access-Control-Allow-Headers' 'Authorization, Origin, X-Requested-With, Content-Type, Accept' always;
#
# if ($request_method = OPTIONS) {
# add_header 'Access-Control-Allow-Origin' 'https://viewer.example.com';
# add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
# add_header 'Access-Control-Allow-Headers' 'Authorization, Origin, X-Requested-With, Content-Type, Accept';
# add_header 'Access-Control-Max-Age' 1728000;
# add_header 'Content-Type' 'text/plain; charset=utf-8';
# add_header 'Content-Length' 0;
# return 204;
# }
rewrite ^/pacs/(.*) /dcm4chee-arc/aets/DCM4CHEE/rs/$1 break;
proxy_pass http://arc:8080;
@@ -155,19 +170,8 @@ http {
expires 0;
add_header Cache-Control private;
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Authorization, Origin, X-Requested-With, Content-Type, Accept' always;
if ($request_method = OPTIONS) {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Authorization, Origin, X-Requested-With, Content-Type, Accept';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
# CORS: same-origin deployment - no CORS headers needed here; see
# the note on the /pacs/ location above before adding any.
proxy_pass http://arc:8080;
}
@@ -4,7 +4,7 @@ email_domains=["*"]
cookie_secure="false"
cookie_expire="9m30s"
cookie_refresh="5m"
client_secret="2Xtlde7aozdkzzYHdIxQNfPDr0wNPTgg"
client_secret="REPLACE_WITH_A_GENERATED_CLIENT_SECRET"
client_id="ohif_viewer"
redirect_url="http://YOUR_DOMAIN/oauth2/callback"
@@ -686,7 +686,7 @@
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"secret": "2Xtlde7aozdkzzYHdIxQNfPDr0wNPTgg",
"secret": "REPLACE_WITH_A_GENERATED_CLIENT_SECRET",
"redirectUris": [
"http://127.0.0.1/oauth2/callback"
],
@@ -94,14 +94,17 @@ services:
KC_DB_URL: 'jdbc:postgresql://postgres:5432/keycloak'
KC_DB_SCHEMA: public
KC_DB_USERNAME: keycloak
KC_DB_PASSWORD: password
# Keycloak authenticates to Postgres as the keycloak role provisioned
# below, so this must be the same value as POSTGRES_PASSWORD. Sourced
# from the single POSTGRES_PASSWORD variable to keep them in lockstep.
KC_DB_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in your .env}
KC_HOSTNAME_ADMIN_URL: http://YOUR_DOMAIN/keycloak/
KC_HOSTNAME_URL: http://YOUR_DOMAIN/keycloak/
KC_HOSTNAME_STRICT_BACKCHANNEL: true
KC_HOSTNAME_STRICT_HTTPS: false
KC_HTTP_ENABLED: true
KEYCLOAK_ADMIN: admin
KEYCLOAK_ADMIN_PASSWORD: admin
KEYCLOAK_ADMIN_PASSWORD: ${KEYCLOAK_ADMIN_PASSWORD:?set KEYCLOAK_ADMIN_PASSWORD in your .env}
KC_HEALTH_ENABLED: true
KC_METRICS_ENABLED: true
KC_PROXY: edge
@@ -139,7 +142,7 @@ services:
environment:
POSTGRES_DB: keycloak
POSTGRES_USER: keycloak
POSTGRES_PASSWORD: password
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in your .env}
restart: unless-stopped
networks:
- default
@@ -0,0 +1,7 @@
# Copy this file to .env next to docker-compose.yml and fill in strong
# values. docker compose refuses to start while either is unset.
KEYCLOAK_ADMIN_PASSWORD=
# POSTGRES_PASSWORD is the single PostgreSQL credential: it provisions the
# keycloak database role and Keycloak reuses it to connect (KC_DB_PASSWORD is
# derived from it in docker-compose.yml), so there is one value, not two.
POSTGRES_PASSWORD=
@@ -0,0 +1,42 @@
# Security notes for this recipe
## Secrets
This recipe no longer ships working credential values. Before `docker compose up`:
- Generate a fresh OAuth client secret for the `ohif_viewer` client and use it
to replace the `REPLACE_WITH_A_GENERATED_CLIENT_SECRET` placeholder in BOTH
`config/ohif-keycloak-realm.json` and `config/oauth2-proxy.cfg` (the two
values must match). To generate one after the realm is imported: Keycloak
admin console -> Clients -> ohif_viewer -> Credentials -> Regenerate.
- Copy `.env.example` to `.env` and set `POSTGRES_PASSWORD` and
`KEYCLOAK_ADMIN_PASSWORD` to strong values. `docker compose` refuses to
start while either is unset. `POSTGRES_PASSWORD` is the single PostgreSQL
credential - it both provisions the `keycloak` database role and is what
Keycloak uses to connect (the compose file derives `KC_DB_PASSWORD` from it),
so there is one database password to set, not two.
## Rotate if you deployed from an earlier checkout
Earlier versions of this recipe committed a fixed client secret and default
admin/database passwords to the public repository. A committed secret stays
burned even after this change, so any deployment created from an earlier
checkout must rotate:
- the `ohif_viewer` client secret (Keycloak admin console -> Clients ->
ohif_viewer -> Credentials -> Regenerate, then update
`config/oauth2-proxy.cfg` to match), and
- the Keycloak admin and PostgreSQL passwords. Note that changing
`POSTGRES_PASSWORD` in `.env` alone does not re-password an existing
database: Postgres only applies it when the `postgres_data` volume is first
initialized. To actually rotate it on an existing deployment, either
`ALTER ROLE keycloak WITH PASSWORD ...` inside the running database or
recreate the `postgres_data` volume.
## CORS
The wildcard `Access-Control-Allow-Origin: *` defaults were removed from
`config/nginx.conf`. The viewer is served by the same nginx as the DICOMweb
proxy, so same-origin deployments need no CORS headers. If you host the viewer
on a different origin, use the commented explicit-origin example in the nginx
config - never `*` on an authenticated endpoint that serves PHI.
@@ -50,6 +50,15 @@ http {
gzip_comp_level 9;
etag on;
# Content-Security-Policy: test in Report-Only mode first and watch
# the browser console for violations before switching the header name
# to the enforcing Content-Security-Policy. Note: nginx add_header does
# not merge into a location that sets its own add_header - if you
# promote this to an active header, re-declare it inside every location
# block that already uses add_header (several proxy locations here do)
# or it will silently not apply there.
# add_header Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' https: blob:; worker-src 'self' blob:; object-src 'self' blob:; frame-src 'self' blob:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" always;
location /sw.js {
add_header Cache-Control "no-cache";
proxy_cache_bypass $http_pragma;
@@ -105,19 +114,25 @@ http {
expires 0;
add_header Cache-Control private;
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Authorization, Origin, X-Requested-With, Content-Type, Accept' always;
if ($request_method = OPTIONS) {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Authorization, Origin, X-Requested-With, Content-Type, Accept';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
# CORS: this recipe serves the viewer from this same nginx, so
# browser requests to this endpoint are same-origin and need NO
# CORS headers at all. If you host the viewer on a different
# origin, allow that origin explicitly and only that origin -
# never use '*' on an authenticated endpoint that serves PHI.
# Cross-origin example (response headers plus OPTIONS preflight):
# add_header 'Access-Control-Allow-Origin' 'https://viewer.example.com' always;
# add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
# add_header 'Access-Control-Allow-Headers' 'Authorization, Origin, X-Requested-With, Content-Type, Accept' always;
#
# if ($request_method = OPTIONS) {
# add_header 'Access-Control-Allow-Origin' 'https://viewer.example.com';
# add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
# add_header 'Access-Control-Allow-Headers' 'Authorization, Origin, X-Requested-With, Content-Type, Accept';
# add_header 'Access-Control-Max-Age' 1728000;
# add_header 'Content-Type' 'text/plain; charset=utf-8';
# add_header 'Content-Length' 0;
# return 204;
# }
proxy_pass http://orthanc:8042/;
}
@@ -137,19 +152,25 @@ http {
expires 0;
add_header Cache-Control private;
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Authorization, Origin, X-Requested-With, Content-Type, Accept' always;
if ($request_method = OPTIONS) {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Authorization, Origin, X-Requested-With, Content-Type, Accept';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
# CORS: this recipe serves the viewer from this same nginx, so
# browser requests to this endpoint are same-origin and need NO
# CORS headers at all. If you host the viewer on a different
# origin, allow that origin explicitly and only that origin -
# never use '*' on an authenticated endpoint that serves PHI.
# Cross-origin example (response headers plus OPTIONS preflight):
# add_header 'Access-Control-Allow-Origin' 'https://viewer.example.com' always;
# add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
# add_header 'Access-Control-Allow-Headers' 'Authorization, Origin, X-Requested-With, Content-Type, Accept' always;
#
# if ($request_method = OPTIONS) {
# add_header 'Access-Control-Allow-Origin' 'https://viewer.example.com';
# add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
# add_header 'Access-Control-Allow-Headers' 'Authorization, Origin, X-Requested-With, Content-Type, Accept';
# add_header 'Access-Control-Max-Age' 1728000;
# add_header 'Content-Type' 'text/plain; charset=utf-8';
# add_header 'Content-Length' 0;
# return 204;
# }
proxy_pass http://orthanc:8042/dicom-web/;
}
@@ -4,7 +4,7 @@ email_domains=["*"]
cookie_secure="false"
cookie_expire="9m30s"
cookie_refresh="5m"
client_secret="2Xtlde7aozdkzzYHdIxQNfPDr0wNPTgg"
client_secret="REPLACE_WITH_A_GENERATED_CLIENT_SECRET"
client_id="ohif_viewer"
redirect_url="http://YOUR_DOMAIN/oauth2/callback"
@@ -686,7 +686,7 @@
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"secret": "2Xtlde7aozdkzzYHdIxQNfPDr0wNPTgg",
"secret": "REPLACE_WITH_A_GENERATED_CLIENT_SECRET",
"redirectUris": [
"http://127.0.0.1/oauth2/callback"
],
@@ -51,14 +51,17 @@ services:
KC_DB_URL: 'jdbc:postgresql://postgres:5432/keycloak'
KC_DB_SCHEMA: public
KC_DB_USERNAME: keycloak
KC_DB_PASSWORD: password
# Keycloak authenticates to Postgres as the keycloak role provisioned
# below, so this must be the same value as POSTGRES_PASSWORD. Sourced
# from the single POSTGRES_PASSWORD variable to keep them in lockstep.
KC_DB_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in your .env}
KC_HOSTNAME_ADMIN_URL: http://YOUR_DOMAIN/keycloak/
KC_HOSTNAME_URL: http://YOUR_DOMAIN/keycloak/
KC_HOSTNAME_STRICT_BACKCHANNEL: true
KC_HOSTNAME_STRICT_HTTPS: false
KC_HTTP_ENABLED: true
KEYCLOAK_ADMIN: admin
KEYCLOAK_ADMIN_PASSWORD: admin
KEYCLOAK_ADMIN_PASSWORD: ${KEYCLOAK_ADMIN_PASSWORD:?set KEYCLOAK_ADMIN_PASSWORD in your .env}
KC_HEALTH_ENABLED: true
KC_METRICS_ENABLED: true
KC_PROXY: edge
@@ -104,7 +107,7 @@ services:
environment:
POSTGRES_DB: keycloak
POSTGRES_USER: keycloak
POSTGRES_PASSWORD: password
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in your .env}
restart: unless-stopped
networks:
- default
@@ -24,3 +24,12 @@ localhost/pacs -> Orthanc
See [here](../../../docs/docs/deployment/nginx--image-archive.md) for more information about this recipe.
# Security notes
- CORS: earlier versions of this recipe set `Access-Control-Allow-Origin: *`
on the `/pacs/` proxy. That default has been removed. The viewer is served
by the same nginx as the proxy, so same-origin deployments need no CORS
headers. If you host the viewer on a different origin, set that origin
explicitly in `config/nginx.conf` - never `*` on an endpoint that serves
PHI.
@@ -32,6 +32,15 @@ http {
gzip_comp_level 9;
etag on;
# Content-Security-Policy: test in Report-Only mode first and watch the
# browser console for violations before switching the header name to the
# enforcing Content-Security-Policy. Note: nginx add_header does not merge
# into a location that sets its own add_header - if you promote this to an
# active header, re-declare it inside every location block that already
# uses add_header (the /pacs/ proxy here does) or it will silently not
# apply there.
# add_header Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' https: blob:; worker-src 'self' blob:; object-src 'self' blob:; frame-src 'self' blob:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" always;
# Reverse Proxy for `orthanc` APIs (including DICOMWeb)
#
@@ -47,17 +56,14 @@ http {
expires 0;
add_header Cache-Control private;
# Add CORS headers
# Note: uncomment the following line to allow all domains to access the Orthanc APIs
# You should actually only allow the domains you trust to access the APIs
# add_header 'Access-Control-Allow-Origin' '*' always;
# CORS: this recipe serves the viewer from this same nginx, so browser
# requests to /pacs/ are same-origin and need NO CORS header at all.
# If you host the viewer on a different origin, allow that origin
# explicitly and only that origin - never use '*' on an endpoint that
# serves PHI. Example:
# add_header 'Access-Control-Allow-Origin' 'https://viewer.example.com' always;
proxy_pass http://orthanc:8042/;
# By default, this endpoint is protected by CORS (cross-origin-resource-sharing)
# You can add headers to allow other domains to request this resource.
# See the "Updating CORS Settings" example below
add_header 'Access-Control-Allow-Origin' '*' always;
}
+6 -1
View File
@@ -15,7 +15,6 @@ const WATCH_IGNORED = /node_modules[\\/](?!@cornerstonejs(?:[\\/]|$))/;
// ~~ Env Vars
const HTML_TEMPLATE = process.env.HTML_TEMPLATE || 'index.html';
const PUBLIC_URL = process.env.PUBLIC_URL || '/';
const APP_CONFIG = process.env.APP_CONFIG || 'config/default.js';
// proxy settings
const PROXY_TARGET = process.env.PROXY_TARGET;
@@ -103,6 +102,12 @@ const setHeaders = (res, path) => {
module.exports = (env, argv) => {
const baseConfig = webpackBase(env, argv, { SRC_DIR, DIST_DIR });
const isProdBuild = process.env.NODE_ENV === 'production';
// Honor an explicit APP_CONFIG; otherwise the dev server gets the
// full-featured `config/dev.js` and a production build the locked-down
// `config/default.js`. This lets `APP_CONFIG=config/foo.js pnpm run dev`
// override the default instead of being clobbered by the script.
const APP_CONFIG =
process.env.APP_CONFIG || (isProdBuild ? 'config/default.js' : 'config/dev.js');
const hasProxy = PROXY_TARGET && PROXY_DOMAIN;
const mergedConfig = merge(baseConfig, {
+1
View File
@@ -0,0 +1 @@
2800f82e3cd02d991146af3f2887fca18c4ab161
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/app",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"productVersion": "3.4.0",
"description": "OHIF Viewer",
"author": "OHIF Contributors",
+38 -5
View File
@@ -11,11 +11,44 @@ window.config = {
strictZSpacingForVolumeViewport: true,
// filterQueryParam: false,
// Add some customizations to the default e2e datasource
customizationService: [
'@ohif/extension-default.customizationModule.datasources',
'@ohif/extension-default.customizationModule.helloPage',
],
// Allowlist for the `?customization=` URL parameter and for
// `customizationService.requires` below. The `default` prefix (no slashes)
// resolves a value to `<publicUrl>/customizations/<value>.jsonc`. Files are
// fetched as DATA (JSON with comments) and never executed.
customizationUrlPrefixes: {
default: './customizations/',
},
// Phase-tagged startup customizations. Each block is applied at a fixed point
// in the lifecycle so ordering is deterministic regardless of when extensions
// and modes load:
// - requires: URL customization data files to resolve up front.
// - bootstrap: applied (Global) BEFORE extensions register.
// - global: applied (Global) AFTER extensions register.
// - mode: applied (Mode) on each mode enter — `*` (general) first,
// then a block keyed by the mode id / routeName.
customizationService: {
// Pulls in platform/app/public/customizations/patientBirthDate.jsonc, which
// adds a "Birth Date" column to the WorkList study list (global phase).
requires: ['patientBirthDate'],
// The previous (legacy-array) customizations, now in the explicit `global`
// phase. A `global` block accepts the same input as setCustomizations: an
// array mixing string references and inline object maps.
global: [
'@ohif/extension-default.customizationModule.datasources',
'@ohif/extension-default.customizationModule.helloPage',
],
// Example of mode-scoped customizations (cleared/reapplied per mode):
// the `*` block applies to every mode first; a mode-named block (matched
// against the mode id or routeName, e.g. 'viewer') applies after it.
//
// mode: {
// '*': { 'someCustomizationId': { $set: 'applies to all modes' } },
// viewer: { 'someCustomizationId': { $set: 'overrides for the viewer mode' } },
// },
},
defaultDataSourceName: 'e2e',
investigationalUseDialog: {
+42 -251
View File
@@ -1,5 +1,21 @@
/** @type {AppTypes.Config} */
// Secure, minimal default configuration.
//
// This is what a plain production build with no APP_CONFIG produces, so it is
// deliberately locked down:
// - The local file data source (`dicomlocal`) and the runtime `?url=` sources
// (`dicomjson`, `dicomwebproxy`) are NOT enabled — they widen the attack
// surface of a default deployment.
// - `?customization=` URL loading is OFF: no `customizationUrlPrefixes` are
// configured, so any `?customization=` value is rejected (and aborts boot
// rather than silently loading).
// - `dangerouslyUseDynamicConfig` (the `configUrl` query parameter) is off.
//
// It does not need to "just work" untouched — point the data source below at
// your own DICOMweb server. For a fully-featured setup with every data source
// and customization loading enabled, see config/dev.js (local development) and
// config/netlify.js (the public demo deploy).
window.config = {
name: 'config/default.js',
routerBasename: null,
@@ -7,6 +23,21 @@ window.config = {
extensions: [],
modes: [],
customizationService: {},
// --- URL-driven customizations (?customization=) ----------------------------
// OFF by default. To allow loading customization data files from the URL, set
// `customizationUrlPrefixes` to a map of allowed prefixes. The `default` prefix
// (no slashes) is used for values with no leading slash; every other prefix
// must start AND end with a slash and is matched against the leading
// `/segment/` of the value. Files are fetched and parsed as JSONC data — they
// are never executed. Example (left disabled here on purpose):
//
// customizationUrlPrefixes: {
// default: './customizations/', // ?customization=ctPresets
// '/remote/': 'https://cdn.example.com/ohif-custom/', // ?customization=/remote/siteA
// },
// ----------------------------------------------------------------------------
showStudyList: true,
// some windows systems have issues with more than 3 web workers
maxNumberOfWebWorkers: 3,
@@ -26,81 +57,13 @@ window.config = {
prefetch: 25,
},
showErrorDetails: 'always', // 'always', 'dev', 'production'
// filterQueryParam: false,
// Defines multi-monitor layouts
multimonitor: [
{
id: 'split',
test: ({ multimonitor }) => multimonitor === 'split',
screens: [
{
id: 'ohif0',
screen: null,
location: {
screen: 0,
width: 0.5,
height: 1,
left: 0,
top: 0,
},
options: 'location=no,menubar=no,scrollbars=no,status=no,titlebar=no',
},
{
id: 'ohif1',
screen: null,
location: {
width: 0.5,
height: 1,
left: 0.5,
top: 0,
},
options: 'location=no,menubar=no,scrollbars=no,status=no,titlebar=no',
},
],
},
{
id: '2',
test: ({ multimonitor }) => multimonitor === '2',
screens: [
{
id: 'ohif0',
screen: 0,
location: {
width: 1,
height: 1,
left: 0,
top: 0,
},
options: 'fullscreen=yes,location=no,menubar=no,scrollbars=no,status=no,titlebar=no',
},
{
id: 'ohif1',
screen: 1,
location: {
width: 1,
height: 1,
left: 0,
top: 0,
},
options: 'fullscreen=yes,location=no,menubar=no,scrollbars=no,status=no,titlebar=no',
},
],
},
],
// `dangerouslyUseDynamicConfig` (load configuration from a `configUrl` query
// parameter) is intentionally left OFF in the secure default build. See
// config/dev.js for the documented shape.
defaultDataSourceName: 'ohif',
/* Dynamic config allows user to pass "configUrl" query string this allows to load config without recompiling application. The regex will ensure valid configuration source */
// dangerouslyUseDynamicConfig: {
// enabled: true,
// // regex will ensure valid configuration source and default is /.*/ which matches any character. To use this, setup your own regex to choose a specific source of configuration only.
// // Example 1, to allow numbers and letters in an absolute or sub-path only.
// // regex: /(0-9A-Za-z.]+)(\/[0-9A-Za-z.]+)*/
// // Example 2, to restricts to either hosptial.com or othersite.com.
// // regex: /(https:\/\/hospital.com(\/[0-9A-Za-z.]+)*)|(https:\/\/othersite.com(\/[0-9A-Za-z.]+)*)/
// regex: /.*/,
// },
dataSources: [
{
// Read-only public demo server. Replace with your own DICOMweb server.
namespace: '@ohif/extension-default.dataSourcesModule.dicomweb',
sourceName: 'ohif',
configuration: {
@@ -118,9 +81,6 @@ window.config = {
supportsWildcard: true,
staticWado: true,
singlepart: 'bulkdata,video',
// whether the data source should use retrieveBulkData to grab metadata,
// and in case of relative path, what would it be relative to, options
// are in the series level or study level (some servers like series some study)
bulkDataURI: {
enabled: true,
relativeResolution: 'studies',
@@ -130,157 +90,13 @@ window.config = {
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomweb',
sourceName: 'ohif2',
configuration: {
friendlyName: 'AWS S3 Static wado secondary server',
name: 'aws',
wadoUriRoot: 'https://dd14fa38qiwhyfd.cloudfront.net/dicomweb',
qidoRoot: 'https://dd14fa38qiwhyfd.cloudfront.net/dicomweb',
wadoRoot: 'https://dd14fa38qiwhyfd.cloudfront.net/dicomweb',
qidoSupportsIncludeField: false,
supportsReject: false,
imageRendering: 'wadors',
thumbnailRendering: 'wadors',
enableStudyLazyLoad: true,
supportsFuzzyMatching: false,
supportsWildcard: true,
staticWado: true,
singlepart: 'bulkdata,video',
// whether the data source should use retrieveBulkData to grab metadata,
// and in case of relative path, what would it be relative to, options
// are in the series level or study level (some servers like series some study)
bulkDataURI: {
enabled: true,
relativeResolution: 'studies',
},
omitQuotationForMultipartRequest: true,
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomweb',
sourceName: 'ohif3',
configuration: {
friendlyName: 'AWS S3 Static wado secondary server',
name: 'aws',
wadoUriRoot: 'https://d3t6nz73ql33tx.cloudfront.net/dicomweb',
qidoRoot: 'https://d3t6nz73ql33tx.cloudfront.net/dicomweb',
wadoRoot: 'https://d3t6nz73ql33tx.cloudfront.net/dicomweb',
qidoSupportsIncludeField: false,
supportsReject: false,
imageRendering: 'wadors',
thumbnailRendering: 'wadors',
enableStudyLazyLoad: true,
supportsFuzzyMatching: false,
supportsWildcard: true,
staticWado: true,
singlepart: 'bulkdata,video',
// whether the data source should use retrieveBulkData to grab metadata,
// and in case of relative path, what would it be relative to, options
// are in the series level or study level (some servers like series some study)
bulkDataURI: {
enabled: true,
relativeResolution: 'studies',
},
omitQuotationForMultipartRequest: true,
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomweb',
sourceName: 'local5000',
configuration: {
friendlyName: 'Static WADO Local Data',
name: 'DCM4CHEE',
qidoRoot: 'http://localhost:5000/dicomweb',
wadoRoot: 'http://localhost:5000/dicomweb',
qidoSupportsIncludeField: false,
supportsReject: true,
supportsStow: true,
imageRendering: 'wadors',
thumbnailRendering: 'wadors',
enableStudyLazyLoad: true,
supportsFuzzyMatching: false,
supportsWildcard: true,
staticWado: true,
singlepart: 'video',
bulkDataURI: {
enabled: true,
relativeResolution: 'studies',
},
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomweb',
sourceName: 'orthanc',
configuration: {
friendlyName: 'local Orthanc DICOMWeb Server',
name: 'DCM4CHEE',
wadoUriRoot: 'http://localhost/pacs/dicom-web',
qidoRoot: 'http://localhost/pacs/dicom-web',
wadoRoot: 'http://localhost/pacs/dicom-web',
qidoSupportsIncludeField: true,
supportsReject: true,
dicomUploadEnabled: true,
imageRendering: 'wadors',
thumbnailRendering: 'wadors',
enableStudyLazyLoad: true,
supportsFuzzyMatching: true,
supportsWildcard: true,
omitQuotationForMultipartRequest: true,
bulkDataURI: {
enabled: true,
// This is an example config that can be used to fix the retrieve URL
// where it has the wrong prefix (eg a canned prefix). It is better to
// just use the correct prefix out of the box, but that is sometimes hard
// when URLs go through several systems.
// Example URLS are:
// "BulkDataURI" : "http://localhost/dicom-web/studies/1.2.276.0.7230010.3.1.2.2344313775.14992.1458058363.6979/series/1.2.276.0.7230010.3.1.3.1901948703.36080.1484835349.617/instances/1.2.276.0.7230010.3.1.4.1901948703.36080.1484835349.618/bulk/00420011",
// when running on http://localhost:3003 with no server running on localhost. This can be corrected to:
// /orthanc/dicom-web/studies/1.2.276.0.7230010.3.1.2.2344313775.14992.1458058363.6979/series/1.2.276.0.7230010.3.1.3.1901948703.36080.1484835349.617/instances/1.2.276.0.7230010.3.1.4.1901948703.36080.1484835349.618/bulk/00420011
// which is a valid relative URL, and will result in using the http://localhost:3003/orthanc/.... path
// startsWith: 'http://localhost/',
// prefixWith: '/orthanc/',
},
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomwebproxy',
sourceName: 'dicomwebproxy',
configuration: {
friendlyName: 'dicomweb delegating proxy',
name: 'dicomwebproxy',
// Security controls for runtime ?url=... datasource loading:
// In authenticated environments, runtime ?url origins must be allowlisted:
// dangerouslyAllowedOriginsForAuthenticatedEnvironments: [
// 'https://config.example.com',
// 'http://localhost:5000',
// ],
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomjson',
sourceName: 'dicomjson',
configuration: {
friendlyName: 'dicom json',
name: 'json',
// Security controls for runtime ?url=... datasource loading:
// In authenticated environments, runtime ?url origins must be allowlisted:
// dangerouslyAllowedOriginsForAuthenticatedEnvironments: [
// 'https://config.example.com',
// 'http://localhost:5000',
// ],
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomlocal',
sourceName: 'dicomlocal',
configuration: {
friendlyName: 'dicom local',
},
},
// The following data sources are intentionally NOT enabled in the secure
// default because they broaden the attack surface of a default deployment.
// Enable them only in a deployment you control (see config/dev.js):
// - dicomlocal: loads DICOM files from the user's machine.
// - dicomjson: loads metadata from an arbitrary `?url=` (gate with
// `dangerouslyAllowedOriginsForAuthenticatedEnvironments`).
// - dicomwebproxy: delegating proxy driven by `?url=`.
],
httpErrorHandler: error => {
// This is 429 when rejected from the public idc sandbox too often.
@@ -289,29 +105,4 @@ window.config = {
// Could use services manager here to bring up a dialog/modal if needed.
console.warn('test, navigate to https://ohif.org/');
},
// segmentation: {
// segmentLabel: {
// enabledByDefault: true,
// labelColor: [255, 255, 0, 1], // must be an array
// hoverTimeout: 1,
// background: 'rgba(100, 100, 100, 0.5)', // can be any valid css color
// },
// },
// whiteLabeling: {
// createLogoComponentFn: function (React) {
// return React.createElement(
// 'a',
// {
// target: '_self',
// rel: 'noopener noreferrer',
// className: 'text-purple-600 line-through',
// href: '_X___IDC__LOGO__LINK___Y_',
// },
// React.createElement('img', {
// src: './Logo.svg',
// className: 'w-14 h-14',
// })
// );
// },
// },
};
+272
View File
@@ -0,0 +1,272 @@
/** @type {AppTypes.Config} */
// Local development configuration.
//
// This is the default config for the dev server (`pnpm run dev`, `dev:fast`,
// `start`). Like config/netlify.js it is full-featured — every data source is
// enabled and the `?customization=` URL feature is ON via
// `customizationUrlPrefixes` — so the whole app can be exercised locally. The
// locked-down config/default.js is what a plain production build emits instead.
window.config = {
name: 'config/dev.js',
routerBasename: null,
// whiteLabeling: {},
extensions: [],
modes: [],
customizationService: {},
// URL-driven customizations (?customization=). The `default` prefix (no
// slashes) is used for values without a leading slash; every other prefix
// must start AND end with a slash and matches the leading `/segment/` of the
// value. Files are fetched and parsed as JSONC data — never executed.
// e.g. ?customization=ctPresets -> ./customizations/ctPresets.jsonc
customizationUrlPrefixes: {
default: './customizations/',
},
showStudyList: true,
// some windows systems have issues with more than 3 web workers
maxNumberOfWebWorkers: 3,
// below flag is for performance reasons, but it might not work for all servers
showWarningMessageForCrossOrigin: true,
showCPUFallbackMessage: true,
showLoadingIndicator: true,
experimentalStudyBrowserSort: false,
strictZSpacingForVolumeViewport: true,
groupEnabledModesFirst: true,
allowMultiSelectExport: false,
maxNumRequests: {
interaction: 100,
thumbnail: 5,
// Prefetch number is dependent on the http protocol. For http 2 or
// above, the number of requests can be go a lot higher.
prefetch: 25,
},
showErrorDetails: 'always', // 'always', 'dev', 'production'
// filterQueryParam: false,
// Defines multi-monitor layouts
multimonitor: [
{
id: 'split',
test: ({ multimonitor }) => multimonitor === 'split',
screens: [
{
id: 'ohif0',
screen: null,
location: {
screen: 0,
width: 0.5,
height: 1,
left: 0,
top: 0,
},
options: 'location=no,menubar=no,scrollbars=no,status=no,titlebar=no',
},
{
id: 'ohif1',
screen: null,
location: {
width: 0.5,
height: 1,
left: 0.5,
top: 0,
},
options: 'location=no,menubar=no,scrollbars=no,status=no,titlebar=no',
},
],
},
{
id: '2',
test: ({ multimonitor }) => multimonitor === '2',
screens: [
{
id: 'ohif0',
screen: 0,
location: {
width: 1,
height: 1,
left: 0,
top: 0,
},
options: 'fullscreen=yes,location=no,menubar=no,scrollbars=no,status=no,titlebar=no',
},
{
id: 'ohif1',
screen: 1,
location: {
width: 1,
height: 1,
left: 0,
top: 0,
},
options: 'fullscreen=yes,location=no,menubar=no,scrollbars=no,status=no,titlebar=no',
},
],
},
],
defaultDataSourceName: 'ohif',
/* Dynamic config allows user to pass "configUrl" query string this allows to load config without recompiling application. The regex will ensure valid configuration source */
// dangerouslyUseDynamicConfig: {
// enabled: true,
// regex: /.*/,
// },
dataSources: [
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomweb',
sourceName: 'ohif',
configuration: {
friendlyName: 'AWS S3 Static wado server',
name: 'aws',
wadoUriRoot: 'https://d14fa38qiwhyfd.cloudfront.net/dicomweb',
qidoRoot: 'https://d14fa38qiwhyfd.cloudfront.net/dicomweb',
wadoRoot: 'https://d14fa38qiwhyfd.cloudfront.net/dicomweb',
qidoSupportsIncludeField: false,
imageRendering: 'wadors',
thumbnailRendering: 'thumbnail',
thumbnailRequestStrategy: 'fetch',
enableStudyLazyLoad: true,
supportsFuzzyMatching: true,
supportsWildcard: true,
staticWado: true,
singlepart: 'bulkdata,video',
bulkDataURI: {
enabled: true,
relativeResolution: 'studies',
transform: url => url.replace('/pixeldata.mp4', '/rendered'),
},
omitQuotationForMultipartRequest: true,
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomweb',
sourceName: 'ohif2',
configuration: {
friendlyName: 'AWS S3 Static wado secondary server',
name: 'aws',
wadoUriRoot: 'https://dd14fa38qiwhyfd.cloudfront.net/dicomweb',
qidoRoot: 'https://dd14fa38qiwhyfd.cloudfront.net/dicomweb',
wadoRoot: 'https://dd14fa38qiwhyfd.cloudfront.net/dicomweb',
qidoSupportsIncludeField: false,
supportsReject: false,
imageRendering: 'wadors',
thumbnailRendering: 'wadors',
enableStudyLazyLoad: true,
supportsFuzzyMatching: false,
supportsWildcard: true,
staticWado: true,
singlepart: 'bulkdata,video',
bulkDataURI: {
enabled: true,
relativeResolution: 'studies',
},
omitQuotationForMultipartRequest: true,
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomweb',
sourceName: 'ohif3',
configuration: {
friendlyName: 'AWS S3 Static wado secondary server',
name: 'aws',
wadoUriRoot: 'https://d3t6nz73ql33tx.cloudfront.net/dicomweb',
qidoRoot: 'https://d3t6nz73ql33tx.cloudfront.net/dicomweb',
wadoRoot: 'https://d3t6nz73ql33tx.cloudfront.net/dicomweb',
qidoSupportsIncludeField: false,
supportsReject: false,
imageRendering: 'wadors',
thumbnailRendering: 'wadors',
enableStudyLazyLoad: true,
supportsFuzzyMatching: false,
supportsWildcard: true,
staticWado: true,
singlepart: 'bulkdata,video',
bulkDataURI: {
enabled: true,
relativeResolution: 'studies',
},
omitQuotationForMultipartRequest: true,
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomweb',
sourceName: 'local5000',
configuration: {
friendlyName: 'Static WADO Local Data',
name: 'DCM4CHEE',
qidoRoot: 'http://localhost:5000/dicomweb',
wadoRoot: 'http://localhost:5000/dicomweb',
qidoSupportsIncludeField: false,
supportsReject: true,
supportsStow: true,
imageRendering: 'wadors',
thumbnailRendering: 'wadors',
enableStudyLazyLoad: true,
supportsFuzzyMatching: false,
supportsWildcard: true,
staticWado: true,
singlepart: 'video',
bulkDataURI: {
enabled: true,
relativeResolution: 'studies',
},
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomweb',
sourceName: 'orthanc',
configuration: {
friendlyName: 'local Orthanc DICOMWeb Server',
name: 'DCM4CHEE',
wadoUriRoot: 'http://localhost/pacs/dicom-web',
qidoRoot: 'http://localhost/pacs/dicom-web',
wadoRoot: 'http://localhost/pacs/dicom-web',
qidoSupportsIncludeField: true,
supportsReject: true,
dicomUploadEnabled: true,
imageRendering: 'wadors',
thumbnailRendering: 'wadors',
enableStudyLazyLoad: true,
supportsFuzzyMatching: true,
supportsWildcard: true,
omitQuotationForMultipartRequest: true,
bulkDataURI: {
enabled: true,
},
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomwebproxy',
sourceName: 'dicomwebproxy',
configuration: {
friendlyName: 'dicomweb delegating proxy',
name: 'dicomwebproxy',
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomjson',
sourceName: 'dicomjson',
configuration: {
friendlyName: 'dicom json',
name: 'json',
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomlocal',
sourceName: 'dicomlocal',
configuration: {
friendlyName: 'dicom local',
},
},
],
httpErrorHandler: error => {
// This is 429 when rejected from the public idc sandbox too often.
console.warn(error.status);
// Could use services manager here to bring up a dialog/modal if needed.
console.warn('test, navigate to https://ohif.org/');
},
};
+5
View File
@@ -20,6 +20,11 @@ window.config = {
routerBasename: null,
extensions: [],
modes: ['@ohif/mode-test'],
// Allow the `default` prefix so e2e specs can exercise `?customization=` (e.g.
// Customization.spec.ts loads `?customization=veterinaryOverlay`).
customizationUrlPrefixes: {
default: './customizations/',
},
showStudyList: true,
// below flag is for performance reasons, but it might not work for all servers
maxNumberOfWebWorkers: 3,
+119 -31
View File
@@ -1,13 +1,30 @@
/** @type {AppTypes.Config} */
// Public demo / Netlify deploy configuration.
//
// This is the full-featured config used for the Netlify deploy (build:viewer:ci).
// Unlike the locked-down config/default.js, it enables every data source and
// turns the `?customization=` URL feature ON via `customizationUrlPrefixes`.
window.config = {
name: 'config/netlify.js',
routerBasename: null,
customizationService: [
'@ohif/extension-default.customizationModule.theme',
],
// whiteLabeling: {},
extensions: [],
modes: [],
customizationService: ['@ohif/extension-default.customizationModule.theme'],
// URL-driven customizations (?customization=). The `default` prefix (no
// slashes) is used for values without a leading slash; every other prefix
// must start AND end with a slash and matches the leading `/segment/` of the
// value. Files are fetched and parsed as JSONC data — never executed.
// e.g. ?customization=ctPresets -> ./customizations/ctPresets.jsonc
customizationUrlPrefixes: {
default: './customizations/',
},
showStudyList: true,
// some windows systems have issues with more than 3 web workers
maxNumberOfWebWorkers: 3,
// below flag is for performance reasons, but it might not work for all servers
showWarningMessageForCrossOrigin: true,
showCPUFallbackMessage: true,
@@ -15,8 +32,83 @@ window.config = {
experimentalStudyBrowserSort: false,
strictZSpacingForVolumeViewport: true,
groupEnabledModesFirst: true,
allowMultiSelectExport: false,
maxNumRequests: {
interaction: 100,
thumbnail: 5,
// Prefetch number is dependent on the http protocol. For http 2 or
// above, the number of requests can be go a lot higher.
prefetch: 25,
},
showErrorDetails: 'always', // 'always', 'dev', 'production'
// filterQueryParam: false,
// Defines multi-monitor layouts
multimonitor: [
{
id: 'split',
test: ({ multimonitor }) => multimonitor === 'split',
screens: [
{
id: 'ohif0',
screen: null,
location: {
screen: 0,
width: 0.5,
height: 1,
left: 0,
top: 0,
},
options: 'location=no,menubar=no,scrollbars=no,status=no,titlebar=no',
},
{
id: 'ohif1',
screen: null,
location: {
width: 0.5,
height: 1,
left: 0.5,
top: 0,
},
options: 'location=no,menubar=no,scrollbars=no,status=no,titlebar=no',
},
],
},
{
id: '2',
test: ({ multimonitor }) => multimonitor === '2',
screens: [
{
id: 'ohif0',
screen: 0,
location: {
width: 1,
height: 1,
left: 0,
top: 0,
},
options: 'fullscreen=yes,location=no,menubar=no,scrollbars=no,status=no,titlebar=no',
},
{
id: 'ohif1',
screen: 1,
location: {
width: 1,
height: 1,
left: 0,
top: 0,
},
options: 'fullscreen=yes,location=no,menubar=no,scrollbars=no,status=no,titlebar=no',
},
],
},
],
defaultDataSourceName: 'ohif',
/* Dynamic config allows user to pass "configUrl" query string this allows to load config without recompiling application. The regex will ensure valid configuration source */
// dangerouslyUseDynamicConfig: {
// enabled: true,
// regex: /.*/,
// },
dataSources: [
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomweb',
@@ -32,13 +124,10 @@ window.config = {
thumbnailRendering: 'thumbnail',
thumbnailRequestStrategy: 'fetch',
enableStudyLazyLoad: true,
supportsFuzzyMatching: false,
supportsFuzzyMatching: true,
supportsWildcard: true,
staticWado: true,
singlepart: 'bulkdata,video',
// whether the data source should use retrieveBulkData to grab metadata,
// and in case of relative path, what would it be relative to, options
// are in the series level or study level (some servers like series some study)
bulkDataURI: {
enabled: true,
relativeResolution: 'studies',
@@ -66,9 +155,6 @@ window.config = {
supportsWildcard: true,
staticWado: true,
singlepart: 'bulkdata,video',
// whether the data source should use retrieveBulkData to grab metadata,
// and in case of relative path, what would it be relative to, options
// are in the series level or study level (some servers like series some study)
bulkDataURI: {
enabled: true,
relativeResolution: 'studies',
@@ -76,7 +162,6 @@ window.config = {
omitQuotationForMultipartRequest: true,
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomweb',
sourceName: 'ohif3',
@@ -95,9 +180,6 @@ window.config = {
supportsWildcard: true,
staticWado: true,
singlepart: 'bulkdata,video',
// whether the data source should use retrieveBulkData to grab metadata,
// and in case of relative path, what would it be relative to, options
// are in the series level or study level (some servers like series some study)
bulkDataURI: {
enabled: true,
relativeResolution: 'studies',
@@ -130,6 +212,29 @@ window.config = {
},
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomweb',
sourceName: 'orthanc',
configuration: {
friendlyName: 'local Orthanc DICOMWeb Server',
name: 'DCM4CHEE',
wadoUriRoot: 'http://localhost/pacs/dicom-web',
qidoRoot: 'http://localhost/pacs/dicom-web',
wadoRoot: 'http://localhost/pacs/dicom-web',
qidoSupportsIncludeField: true,
supportsReject: true,
dicomUploadEnabled: true,
imageRendering: 'wadors',
thumbnailRendering: 'wadors',
enableStudyLazyLoad: true,
supportsFuzzyMatching: true,
supportsWildcard: true,
omitQuotationForMultipartRequest: true,
bulkDataURI: {
enabled: true,
},
},
},
{
namespace: '@ohif/extension-default.dataSourcesModule.dicomwebproxy',
@@ -163,20 +268,3 @@ window.config = {
console.warn('test, navigate to https://ohif.org/');
},
};
function waitForElement(selector, maxAttempts = 20, interval = 25) {
return new Promise(resolve => {
let attempts = 0;
const checkForElement = setInterval(() => {
const element = document.querySelector(selector);
if (element || attempts >= maxAttempts) {
clearInterval(checkForElement);
resolve();
}
attempts++;
}, interval);
});
}
@@ -0,0 +1,21 @@
// Example URL-loaded customization: ctPresets
//
// Replaces the CT window/level presets offered in the window-level menu with a
// site-specific set (key: `cornerstone.windowLevelPresets`). Other modalities
// keep their defaults because only the `CT` entry is overridden.
//
// Load it with `?customization=ctPresets`.
{
"global": {
"cornerstone.windowLevelPresets": {
"$merge": {
"CT": [
{ "id": "ct-soft-tissue", "description": "Soft tissue", "window": "400", "level": "40" },
{ "id": "ct-lung", "description": "Lung", "window": "1500", "level": "-600" },
{ "id": "ct-angio", "description": "Angio", "window": "600", "level": "300" },
{ "id": "ct-bone", "description": "Bone", "window": "2500", "level": "480" }
]
}
}
}
}
@@ -0,0 +1,23 @@
// Example URL-loaded customization: measurementLabels
//
// Makes the viewer prompt for a label from a fixed list whenever a measurement
// is created (key: `measurementLabels`). `labelOnMeasure` triggers the prompt on
// creation and `exclusive` restricts entries to the provided items.
//
// Load it with `?customization=measurementLabels`.
{
"global": {
"measurementLabels": {
"$set": {
"labelOnMeasure": true,
"exclusive": true,
"items": [
{ "value": "Head", "label": "Head" },
{ "value": "Shoulder", "label": "Shoulder" },
{ "value": "Knee", "label": "Knee" },
{ "value": "Toe", "label": "Toe" }
]
}
}
}
}
@@ -0,0 +1,34 @@
// Example URL-loaded customization: patientBirthDate
//
// Adds a "Birth Date" column to the WorkList study list, right after the
// Patient column. Because a URL customization file is DATA (never executed), it
// cannot carry a render function — it inserts a plain, serializable column spec
// (`id` + `meta`) and WorkList expands it into a display-only text column that
// reads `row.patientBirthDate` (surfaced by the DICOMweb data source from DICOM
// tag 00100030).
//
// This applies in the `global` phase, so it is in place before the WorkList
// renders. Load it with `?customization=patientBirthDate`, or pull it in from
// `appConfig.customizationService.requires`.
{
"global": {
"workList.columns": {
// Insert at index 1 (immediately after the Patient column). Using a
// fixed index keeps the trailing `actions` column last.
"$splice": [
[
1,
0,
{
"id": "patientBirthDate",
"meta": {
"label": "Birth Date",
"minWidth": 130,
"priority": 40
}
}
]
]
}
}
}
@@ -0,0 +1,42 @@
// Example URL-loaded customization: smoothRotate
//
// Adds a "Smooth Rotate" tool button to the More Tools menu of the basic and
// longitudinal viewers. It activates the cornerstone `PlanarRotate` tool, which
// rotates the image freely as you drag (unlike the fixed 90° "Rotate Right").
//
// It extends the default toolbar customizations registered by the cornerstone
// extension (`cornerstone.toolbarButtons` / `cornerstone.toolbarSections`) using
// immutability-helper `$push` commands, so the built-in buttons are preserved.
//
// Load it with `?customization=smoothRotate`.
{
"global": {
"cornerstone.toolbarButtons": {
"$push": [
{
"id": "SmoothRotate",
"uiType": "ohif.toolButton",
"props": {
"type": "tool",
// Re-use the existing rotate icon.
"icon": "tool-rotate-right",
"label": "Smooth Rotate",
"tooltip": "Smooth Rotate (drag to rotate the image freely)",
"commands": {
"commandName": "setToolActiveToolbar",
"commandOptions": {
"toolName": "PlanarRotate"
}
},
"evaluate": "evaluate.cornerstoneTool"
}
}
]
},
"cornerstone.toolbarSections": {
"MoreTools": {
"$push": ["SmoothRotate"]
}
}
}
}
@@ -0,0 +1,5 @@
// Example chaining module: ensures `veterinaryOverlay` is loaded and applied
// first when using `?customization=veterinary` alone.
{
"requires": ["veterinaryOverlay"]
}
@@ -0,0 +1,56 @@
// Example URL-loaded customization: veterinaryOverlay
//
// Demonstrates a runtime-loaded customization that overrides the default
// viewport overlay with a veterinary-style demographics layout. Loaded via
// `?customization=veterinaryOverlay` (see CustomizationService URL handling).
//
// Uses the same `global`-at-top-level shape as the cornerstone overlay samples
// and `inheritsFrom: 'ohif.overlayItem'` on each row, matching
// extensions/cornerstone/.../viewportOverlayCustomization.tsx.
{
"global": {
"viewportOverlay.topLeft": {
"$set": [
{
"id": "PatientName",
"inheritsFrom": "ohif.overlayItem",
"attribute": "PatientName",
"label": "Patient",
"title": "Patient name"
},
{
"id": "PatientID",
"inheritsFrom": "ohif.overlayItem",
"attribute": "PatientID",
"label": "ID",
"title": "Patient ID"
},
{
"id": "StudyDate",
"inheritsFrom": "ohif.overlayItem",
"attribute": "StudyDate",
"label": "Date",
"title": "Study date"
}
]
},
"viewportOverlay.topRight": {
"$set": [
{
"id": "PatientSpecies",
"inheritsFrom": "ohif.overlayItem",
"attribute": "PatientSpecies",
"label": "Species",
"title": "Patient species"
},
{
"id": "PatientBreed",
"inheritsFrom": "ohif.overlayItem",
"attribute": "PatientBreed",
"label": "Breed",
"title": "Patient breed"
}
]
}
}
}
@@ -1,6 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<!--
Content-Security-Policy is delivered via hosting headers (netlify.toml
for Netlify deploys; commented add_header examples in the nginx
recipes under platform/app/.recipes), not as a meta tag: a meta tag
cannot express Report-Only mode. See the deployment docs
(docs/deployment) for the policy and the criteria for promoting it
from Report-Only to enforcing.
-->
<meta charset="UTF-8" />
<meta
name="viewport"
+2 -3
View File
@@ -110,7 +110,6 @@ function App({
cineService,
userAuthenticationService,
uiNotificationService,
customizationService,
} = servicesManager.services;
const providers = [
@@ -142,8 +141,8 @@ function App({
let authRoutes = null;
// Should there be a generic call to init on the extension manager?
customizationService.init(extensionManager);
// customizationService.init(extensionManager) runs in appInit after extensions register;
// do not call init again here — repeated init would duplicate-merge unless guarded (see CustomizationService.init).
// Use config to create routes
const appRoutes = createRoutes({
+18 -1
View File
@@ -28,7 +28,7 @@ import loadModules, { loadModule as peerImport } from './pluginImports';
import { publicUrl } from './utils/publicUrl';
/**
* @param {object|func} appConfigOrFunc - application configuration, or a function that returns application configuration
* @param {object|function} appConfigOrFunc - application configuration, or a function that returns application configuration
* @param {object[]} defaultExtensions - array of extension objects
*/
async function appInit(appConfigOrFunc, defaultExtensions, defaultModes) {
@@ -91,8 +91,25 @@ async function appInit(appConfigOrFunc, defaultExtensions, defaultModes) {
* Example2: [[ext1, config], ext2, [ext3, config]]
*/
const loadedExtensions = await loadModules([...defaultExtensions, ...appConfig.extensions]);
const { customizationService } = servicesManager.services;
// Resolve every customization module up front — from
// `appConfig.customizationService.requires` and the `?customization=` URL
// parameter — long before any mode loads, then apply the `bootstrap` phase
// BEFORE extensions register so it is in place while they initialize. Modules
// are only loaded when `appConfig.customizationUrlPrefixes` allows their
// prefix; the feature is off by default, and a value with an unconfigured
// prefix throws here (aborting startup) rather than being silently ignored.
await customizationService.loadAndApplyBootstrapCustomizations(extensionManager);
await extensionManager.registerExtensions(loadedExtensions, appConfig.dataSources);
// Merge extension default/global modules, then layer on the `global` phase of
// the structured config + the URL modules resolved above (so `$apply`-style
// overrides see the extension-provided defaults they build on).
customizationService.init(extensionManager);
customizationService.applyGlobalCustomizations();
// TODO: We no longer use `utils.addServer`
// TODO: We no longer init webWorkers at app level
// TODO: We no longer init the user Manager
@@ -175,7 +175,9 @@ function parseFiltersFromURL(params: URLSearchParams): ColumnFiltersState {
* Build URL query string from study list state preserving key query parameters.
*/
function buildQueryFromState(state: StudyListState): string {
const query: Record<string, string> = {};
// preserveQueryStrings may write repeated values as arrays, so the value type
// must allow string[] in addition to string.
const query: Record<string, string | string[]> = {};
// Sorting
if (state.sorting.length > 0) {
+6
View File
@@ -221,6 +221,12 @@ export default function ModeRoute({
appConfig,
});
// `extensionManager.onModeEnter` resets the customization mode scope via
// `customizationService.onModeEnter`; now layer on the `mode` phase blocks
// for this mode — the general (`*`) block first, then any block keyed by
// this mode's id / routeName so a single mode can override the general one.
customizationService.applyModeCustomizations([mode.id, mode.routeName]);
// use the URL hangingProtocolId if it exists, otherwise use the one
// defined in the mode configuration
const hangingProtocolIdToUse = hangingProtocolService.getProtocolById(
+10 -1
View File
@@ -51,7 +51,16 @@ export default function WorkList({
// `workList.columns` is registered as a value (StudyList.defaultColumns) and
// merged via customization commands, so we read the result directly.
const customized = customizationService.getCustomization('workList.columns');
return Array.isArray(customized) ? customized : StudyList.defaultColumns;
const resolved = Array.isArray(customized) ? customized : StudyList.defaultColumns;
// Expand data-only column specs. A `?customization=` JSONC file (or any
// serializable source) cannot carry render functions, so an entry that has
// an `id` but no `accessorFn`/`cell` is turned into a display-only text
// column that reads `row[id]` — matching `StudyList.textColumn`.
return resolved.map((col: any) =>
col && typeof col === 'object' && col.id && !col.accessorFn && !col.cell
? StudyList.textColumn(col.id, col.meta?.label ?? col.id, col.meta)
: col
);
}, [customizationService]);
const logoComponent = appConfig?.whiteLabeling?.createLogoComponentFn?.(React) ?? (
+1 -1
View File
@@ -14,7 +14,7 @@ workbox.core.clientsClaim();
// Cache static assets that aren't precached
workbox.routing.registerRoute(
/\.(?:js|css|json5)$/,
/\.(?:js|css|json5|jsonc)$/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: 'static-resources',
})
@@ -5,6 +5,7 @@ import CallbackPage from '../routes/CallbackPage';
import SignoutCallbackComponent from '../routes/SignoutCallbackComponent';
import LegacyClient from './legacyOIDCClient';
import NextClient from './nextOIDCClient';
import { sanitizeSameOriginRedirect } from './sanitizeRedirect';
function _isAbsoluteUrl(url) {
return url.includes('http://') || url.includes('https://');
@@ -55,7 +56,10 @@ function LogoutComponent(props) {
const location = useLocation();
const query = new URLSearchParams(location.search);
userManager.signoutRedirect({
post_logout_redirect_uri: query.get('redirect_uri'),
post_logout_redirect_uri: sanitizeSameOriginRedirect(
query.get('redirect_uri'),
window.location.origin
),
});
return null;
}
@@ -0,0 +1,102 @@
// query-string is the stringifier used by the worklist navigation callers
// (useStudyListStateSync, LegacyWorkList); test against it, not the `qs` library.
import qs from 'query-string';
import { preserveQueryParameters, preserveQueryStrings } from './preserveQueryParameters';
describe('preserveQueryParameters', () => {
it('preserves base keys as query arrays', () => {
const current = new URLSearchParams();
current.append('configUrl', 'foo.js');
const out = new URLSearchParams();
preserveQueryParameters(out, undefined, current);
expect(out.getAll('configUrl')).toEqual(['foo.js']);
});
it('preserves all repeated values for the customization key', () => {
const current = new URLSearchParams();
current.append('customization', 'a');
current.append('customization', 'b');
const out = new URLSearchParams();
preserveQueryParameters(out, undefined, current);
expect(out.getAll('customization')).toEqual(['a', 'b']);
});
it('does not preserve unrelated keys', () => {
const current = new URLSearchParams();
current.append('foo', 'bar');
const out = new URLSearchParams();
preserveQueryParameters(out, undefined, current);
expect(out.get('foo')).toBeNull();
});
it('uses customization service values for multi-key preservation', () => {
const customizationService = {
getValue: jest.fn().mockReturnValue(['customization', 'customizationAlt']),
};
const current = new URLSearchParams();
current.append('customizationAlt', 'c');
const out = new URLSearchParams();
preserveQueryParameters(out, customizationService, current);
expect(out.getAll('customizationAlt')).toEqual(['c']);
expect(customizationService.getValue).toHaveBeenCalled();
});
});
describe('preserveQueryStrings', () => {
it('keeps single values as strings and repeated values as arrays', () => {
const current = new URLSearchParams();
current.append('configUrl', 'foo.js');
current.append('customization', 'a');
current.append('customization', 'b');
const out: Record<string, string | string[]> = {};
preserveQueryStrings(out, undefined, current);
expect(out.configUrl).toBe('foo.js');
expect(out.customization).toEqual(['a', 'b']);
});
it('keeps a single customization value as a string', () => {
const current = new URLSearchParams();
current.append('customization', 'only');
const out: Record<string, string | string[]> = {};
preserveQueryStrings(out, undefined, current);
expect(out.customization).toBe('only');
});
it('uses customization service values for query string preservation', () => {
const customizationService = {
getValue: jest.fn().mockReturnValue(['customization', 'customizationAlt']),
};
const current = new URLSearchParams();
current.append('customizationAlt', 'c');
const out: Record<string, string | string[]> = {};
preserveQueryStrings(out, customizationService, current);
expect(out.customizationAlt).toBe('c');
expect(customizationService.getValue).toHaveBeenCalled();
});
it('serializes single preserved values as plain query keys with default options', () => {
const current = new URLSearchParams();
current.append('configUrl', 'foo.js');
const out: Record<string, string | string[]> = {};
preserveQueryStrings(out, undefined, current);
// Default options only — no arrayFormat. Single values are plain strings, so
// they round-trip unchanged regardless of arrayFormat.
const search = qs.stringify(out, { skipNull: true, skipEmptyString: true });
expect(search).toBe('configUrl=foo.js');
expect(search).not.toMatch(/configUrl\[/);
});
it('serializes repeated preserved values as duplicated keys with default options', () => {
const current = new URLSearchParams();
current.append('customization', 'a');
current.append('customization', 'b');
const out: Record<string, string | string[]> = {};
preserveQueryStrings(out, undefined, current);
// query-string's default arrayFormat already produces duplicated keys, so callers
// need no arrayFormat option for repeated preserved keys to round-trip.
const search = qs.stringify(out, { skipNull: true, skipEmptyString: true });
expect(search).toBe('customization=a&customization=b');
});
});
@@ -1,26 +1,63 @@
function preserve(query, current, key) {
const value = current.get(key);
if (value) {
query.append(key, value);
}
}
import type CustomizationService from '@ohif/core/src/services/CustomizationService';
export const preserveKeys = ['configUrl', 'multimonitor', 'screenNumber', 'hangingProtocolId'];
/**
* Keys preserved when navigating between worklist and viewer modes.
* Each key may repeat in the URL; a single occurrence is preserved as a string and
* multiple occurrences as an array (see preserveQueryStrings).
*/
export const PRESERVE_CUSTOMIZATION_KEYS_KEY = 'ohif.preserveCustomizationKeys';
export const preserveKeys = [
'configUrl',
'multimonitor',
'screenNumber',
'hangingProtocolId',
'customization',
];
export function preserveQueryParameters(
query,
current = new URLSearchParams(window.location.search)
) {
for (const key of preserveKeys) {
preserve(query, current, key);
}
}
export function preserveQueryStrings(query, current = new URLSearchParams(window.location.search)) {
for (const key of preserveKeys) {
const value = current.get(key);
function preserveKey(query: URLSearchParams, current: URLSearchParams, key: string) {
const values = current.getAll(key);
for (const value of values) {
if (value) {
query[key] = value;
query.append(key, value);
}
}
}
function getPreserveKeys(customizationService?: CustomizationService): string[] {
const customKeys = customizationService?.getValue?.(PRESERVE_CUSTOMIZATION_KEYS_KEY, []) || [];
if (!customKeys?.length) {
return preserveKeys;
}
return [...preserveKeys, ...customKeys];
}
export function preserveQueryParameters(
query: URLSearchParams,
customizationService?: CustomizationService,
current: URLSearchParams = new URLSearchParams(window.location.search)
): void {
for (const key of getPreserveKeys(customizationService)) {
preserveKey(query, current, key);
}
}
export function preserveQueryStrings(
query: Record<string, string | string[]>,
customizationService?: CustomizationService,
current: URLSearchParams = new URLSearchParams(window.location.search)
): void {
for (const key of getPreserveKeys(customizationService)) {
const values = current.getAll(key).filter(Boolean);
if (!values.length) {
continue;
}
// A single value is stored as a plain string and repeated values as an array.
// The worklist stringifier (query-string) serializes both correctly with its
// default arrayFormat: a string becomes `key=value` and an array becomes
// duplicated `key=a&key=b` keys — no arrayFormat option required by callers.
// Keeping single values as strings also keeps them safe under stricter
// serializers (e.g. the `qs` library, whose default would index arrays).
query[key] = values.length === 1 ? values[0] : values;
}
}
@@ -0,0 +1,40 @@
import { sanitizeSameOriginRedirect } from './sanitizeRedirect';
describe('sanitizeSameOriginRedirect', () => {
const origin = 'https://viewer.example.com';
it('returns the same href back for an absolute same-origin URL', () => {
expect(sanitizeSameOriginRedirect('https://viewer.example.com/worklist?a=1', origin)).toBe(
'https://viewer.example.com/worklist?a=1'
);
});
it('resolves relative paths against the app origin', () => {
expect(sanitizeSameOriginRedirect('/worklist', origin)).toBe(
'https://viewer.example.com/worklist'
);
});
it('rejects an absolute cross-origin URL', () => {
expect(sanitizeSameOriginRedirect('https://evil.example.com/', origin)).toBeUndefined();
});
it('rejects a protocol-relative cross-origin URL', () => {
expect(sanitizeSameOriginRedirect('//evil.example.com/x', origin)).toBeUndefined();
});
it('rejects javascript: scheme values', () => {
expect(sanitizeSameOriginRedirect('javascript:alert(1)', origin)).toBeUndefined();
});
it('rejects null and empty values', () => {
expect(sanitizeSameOriginRedirect(null, origin)).toBeUndefined();
expect(sanitizeSameOriginRedirect('', origin)).toBeUndefined();
});
it('rejects lookalike hosts that merely start with the app host', () => {
expect(
sanitizeSameOriginRedirect('https://viewer.example.com.evil.com/', origin)
).toBeUndefined();
});
});
@@ -0,0 +1,22 @@
/**
* Returns the given redirect target only when it resolves to the provided
* origin; otherwise returns undefined so callers fall back to the configured
* post-logout destination.
*/
export function sanitizeSameOriginRedirect(
value: string | null,
origin: string
): string | undefined {
if (!value) {
return undefined;
}
try {
const url = new URL(value, origin);
if (url.origin !== origin) {
return undefined;
}
return url.href;
} catch {
return undefined;
}
}
+1
View File
@@ -0,0 +1 @@
3.13.0-beta.110-new-one-click
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/cli",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "A CLI to bootstrap new OHIF extension or mode",
"type": "module",
"main": "src/index.js",
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@ohif/core",
"version": "3.13.0-beta.110",
"version": "3.13.0-beta.115",
"description": "Generic business logic for web-based medical imaging applications",
"author": "OHIF Core Team",
"license": "MIT",
@@ -49,6 +49,7 @@
"gl-matrix": "3.4.3",
"immutability-helper": "3.1.1",
"isomorphic-base64": "1.0.2",
"json5": "2.2.3",
"lodash.clonedeep": "4.5.0",
"lodash.isequal": "4.5.0",
"moment": "2.30.1",
@@ -0,0 +1,50 @@
import CustomizationService from './CustomizationService';
const commandsManager = {};
describe('CustomizationService.init (extension default/global deduplication)', () => {
it('does not re-merge the same extension customization modules on repeated init', () => {
const getModuleEntry = jest.fn((id: string) => {
if (id === 'ext1.customizationModule.default') {
return { value: { fromDefault: { $set: 1 } } };
}
if (id === 'ext1.customizationModule.global') {
return { value: { fromGlobal: { $set: 'g' } } };
}
return undefined;
});
const extensionManager = {
registeredExtensionIds: ['ext1'],
getRegisteredExtensionIds: () => ['ext1'],
getModuleEntry,
};
const service = new CustomizationService({ commandsManager, configuration: {} });
service.init(extensionManager as any);
service.init(extensionManager as any);
expect(getModuleEntry).toHaveBeenCalledTimes(2);
expect(service.getCustomization('fromDefault')).toBe(1);
expect(service.getCustomization('fromGlobal')).toBe('g');
});
it('merges a module the first time it appears on a later init', () => {
const moduleEntries: Record<string, { value: Record<string, unknown> }> = {};
const extensionManager = {
registeredExtensionIds: ['ext2'],
getRegisteredExtensionIds: () => ['ext2'],
getModuleEntry: (id: string) => moduleEntries[id],
};
const service = new CustomizationService({ commandsManager, configuration: {} });
service.init(extensionManager as any);
expect(service.getCustomization('late')).toBeUndefined();
moduleEntries['ext2.customizationModule.default'] = { value: { late: { $set: true } } };
service.init(extensionManager as any);
expect(service.getCustomization('late')).toBe(true);
});
});
@@ -0,0 +1,130 @@
import CustomizationService, { GENERAL_MODE_KEY } from './CustomizationService';
const commandsManager = {};
const policy = {
prefixes: { default: './customizations/' },
};
/** Minimal ExtensionManager stub exposing the appConfig the URL policy reads. */
function makeExtensionManager(appConfig: Record<string, unknown> = {}) {
return {
appConfig: { customizationUrlPrefixes: policy.prefixes, ...appConfig },
registeredExtensionIds: [],
getRegisteredExtensionIds: () => [],
getModuleEntry: () => undefined,
} as any;
}
describe('CustomizationService phase-tagged loading', () => {
it('applies bootstrap before extensions and global after, both Global scope', async () => {
const service = new CustomizationService({
commandsManager,
configuration: {
bootstrap: { early: { $set: 'pre' } },
global: { late: { $set: 'post' } },
},
});
const extensionManager = makeExtensionManager();
await service.loadAndApplyBootstrapCustomizations(extensionManager);
// bootstrap is applied immediately; global is not yet.
expect(service.getCustomization('early')).toBe('pre');
expect(service.getCustomization('late')).toBeUndefined();
service.init(extensionManager);
service.applyGlobalCustomizations();
expect(service.getCustomization('late')).toBe('post');
expect(service.getCustomizations(service.Scope.Global).get('early')).toBeDefined();
});
it('does not treat a phase-tagged config as legacy Global references', () => {
const service = new CustomizationService({
commandsManager,
configuration: { global: { a: { $set: 1 } } },
});
service.init(makeExtensionManager());
// `global` must NOT be added as a customization id during init; it is a phase.
expect(service.getCustomization('global')).toBeUndefined();
expect(service.getCustomization('a')).toBeUndefined();
});
it('applies the general mode block first, then the mode-specific block', () => {
const service = new CustomizationService({
commandsManager,
configuration: {
mode: {
[GENERAL_MODE_KEY]: { greeting: { $set: 'general' }, shared: { $set: 'general' } },
viewer: { greeting: { $set: 'viewer' } },
},
},
});
service.init(makeExtensionManager());
service.onModeEnter();
service.applyModeCustomizations(['viewer']);
// mode-specific overrides general; non-overridden general value remains.
expect(service.getCustomization('greeting')).toBe('viewer');
expect(service.getCustomization('shared')).toBe('general');
});
it('matches a mode block by id OR routeName', () => {
const service = new CustomizationService({
commandsManager,
configuration: {
mode: { viewer: { fromRouteName: { $set: true } } },
},
});
service.init(makeExtensionManager());
service.onModeEnter();
service.applyModeCustomizations(['@ohif/mode-longitudinal', 'viewer']);
expect(service.getCustomization('fromRouteName')).toBe(true);
});
it('clears mode-scope customizations on re-enter so a different mode does not leak', () => {
const service = new CustomizationService({
commandsManager,
configuration: {
mode: {
viewer: { onlyViewer: { $set: true } },
segmentation: { onlySeg: { $set: true } },
},
},
});
service.init(makeExtensionManager());
service.onModeEnter();
service.applyModeCustomizations(['viewer']);
expect(service.getCustomization('onlyViewer')).toBe(true);
service.onModeEnter();
service.applyModeCustomizations(['segmentation']);
expect(service.getCustomization('onlyViewer')).toBeUndefined();
expect(service.getCustomization('onlySeg')).toBe(true);
});
it('applies phase blocks from URL-loaded modules and merges $apply over extension defaults', async () => {
const service = new CustomizationService({ commandsManager, configuration: {} });
const extensionManager = makeExtensionManager();
// Seed an extension-style default so $apply has something to build on.
service.init(extensionManager);
service.setCustomizations({ 'list.columns': ['a', 'b'] }, service.Scope.Default);
const importFn = jest.fn(async () => ({
global: { 'list.columns': { $push: ['c'] } },
mode: { '*': { banner: { $set: 'all' } }, viewer: { banner: { $set: 'viewer' } } },
}));
await service.loadCustomizationModules(['A'], { policy, importFn });
service.applyGlobalCustomizations();
expect(service.getCustomization('list.columns')).toEqual(['a', 'b', 'c']);
service.applyModeCustomizations(['viewer']);
expect(service.getCustomization('banner')).toBe('viewer');
});
});
@@ -0,0 +1,148 @@
import CustomizationService from './CustomizationService';
const commandsManager = {};
const policy = {
prefixes: { default: './customizations/' },
};
describe('CustomizationService.requires (URL customization modules)', () => {
let service: CustomizationService;
beforeEach(() => {
service = new CustomizationService({ commandsManager, configuration: {} });
});
it('loads a single module', async () => {
const importFn = jest.fn(async (url: string) => ({
global: { entry: { value: url } },
}));
const loaded = await service.requires(['A'], { policy, importFn });
expect(loaded).toHaveLength(1);
expect(loaded[0].request.name).toBe('A');
expect(loaded[0].module.global).toBeDefined();
expect(importFn).toHaveBeenCalledTimes(1);
});
it('returns immediately when the same module is already loaded', async () => {
const importFn = jest.fn(async (url: string) => ({
global: { entry: { value: url } },
}));
await service.requires(['A'], { policy, importFn });
expect(importFn).toHaveBeenCalledTimes(1);
const loadedAgain = await service.requires(['A'], { policy, importFn });
expect(loadedAgain).toHaveLength(0);
expect(importFn).toHaveBeenCalledTimes(1);
});
it('loads dependencies first via module requires', async () => {
const importFn = jest.fn(async (url: string) => {
if (url.endsWith('/A.jsonc')) {
return {
global: { 'pkg.A': { value: 'A' } },
requires: ['B'],
};
}
if (url.endsWith('/B.jsonc')) {
return {
global: { 'pkg.B': { value: 'B' } },
};
}
return {};
});
const loaded = await service.requires(['A'], { policy, importFn });
expect(loaded.map(l => l.request.name)).toEqual(['B', 'A']);
});
it('handles cycles per the spec: A requires B, B requires A => B then A', async () => {
const importFn = jest.fn(async (url: string) => {
if (url.endsWith('/A.jsonc')) {
return {
global: { 'pkg.A': { value: 'A' } },
requires: ['B'],
};
}
if (url.endsWith('/B.jsonc')) {
return {
global: { 'pkg.B': { value: 'B' } },
requires: ['A'],
};
}
return {};
});
const loaded = await service.requires(['A'], { policy, importFn });
expect(loaded.map(l => l.request.name)).toEqual(['B', 'A']);
expect(importFn).toHaveBeenCalledTimes(2);
});
it('does not treat customization field refs as URL dependencies', async () => {
const importFn = jest.fn(async () => ({
global: {
'viewportOverlay.topLeft.X': { customization: 'ohif.overlayItem' },
},
}));
const loaded = await service.requires(['A'], { policy, importFn });
expect(loaded).toHaveLength(1);
expect(importFn).toHaveBeenCalledTimes(1);
});
it('parses comma-separated names like the URL query integration', async () => {
const importFn = jest.fn(async () => ({
global: { 'pkg.X': {} },
}));
const loaded = await service.requires(['A', 'B', 'C'], { policy, importFn });
expect(loaded.map(l => l.request.name)).toEqual(['A', 'B', 'C']);
expect(importFn).toHaveBeenCalledTimes(3);
});
it('throws and loads nothing when any entry is rejected', async () => {
const importFn = jest.fn(async () => ({
global: {},
}));
await expect(
service.requires(['A', '/missing/foo', '../escape'], { policy, importFn })
).rejects.toThrow(/refusing to load customization/);
expect(importFn).not.toHaveBeenCalled();
});
it('warns and skips when import fails', async () => {
const importFn = jest.fn(async () => {
throw new Error('404');
});
const warn = jest.fn();
const loaded = await service.requires(['A'], {
policy,
importFn,
logger: { warn, error: jest.fn() },
});
expect(loaded).toHaveLength(0);
expect(warn).toHaveBeenCalled();
});
it('warns and skips when the module has no customization payload', async () => {
const importFn = jest.fn(async () => ({}));
const warn = jest.fn();
const loaded = await service.requires(['A'], {
policy,
importFn,
logger: { warn, error: jest.fn() },
});
expect(loaded).toHaveLength(0);
expect(warn).toHaveBeenCalled();
});
it('applyCustomizationUrlSearchParams delegates to requires', async () => {
const importFn = jest.fn(async () => ({
global: { 'pkg.X': {} },
}));
const params = new URLSearchParams();
params.append('customization', 'A,B');
params.append('customization', 'C');
await service.applyCustomizationUrlSearchParams(params, { policy, importFn });
expect(importFn).toHaveBeenCalledTimes(3);
});
});
@@ -1,8 +1,33 @@
import update, { extend } from 'immutability-helper';
import JSON5 from 'json5';
import { PubSubService } from '../_shared/pubSubServiceInterface';
import type { Customization } from './types';
import type { CommandsManager } from '../../classes';
import type { ExtensionManager } from '../../extensions';
import type ExtensionManager from '../../extensions/ExtensionManager';
import { getCustomizationUrlPolicy } from './customizationUrl';
import { getUrlCustomizationModulePayload } from './getUrlCustomizationModulePayload';
import { resolveCustomizationUrl } from './resolve';
import {
parseCustomizationParams,
validateCustomizationRequests,
} from './validate';
import type { ValidatedCustomization } from './validate';
import type { CustomizationUrlPolicy } from './customizationUrlDefaults';
import type {
CustomizationModule,
CustomizationPhaseInput,
LoadedCustomization,
LoadOptions,
PhasedCustomizationConfig,
} from './customizationUrlTypes';
/**
* Reserved key in a `mode` phase block for the "general" customizations that
* apply to every mode. The general block is applied FIRST on each mode enter;
* a block keyed by the entered mode's id / routeName is applied after it so a
* single mode can override the general values.
*/
export const GENERAL_MODE_KEY = '*';
const EVENTS = {
MODE_CUSTOMIZATION_MODIFIED: 'event::CustomizationService:modeModified',
@@ -28,7 +53,8 @@ export enum CustomizationScope {
/**
* Default customizations that serve as fallbacks when no global or mode-specific
* customizations are defined. These can only be defined once.
* customizations are defined. These are not cleared when the service re-inits
* for a mode change; only Mode scope is reset.
*/
Default = 'default',
}
@@ -89,10 +115,9 @@ export default class CustomizationService extends PubSubService {
private modeCustomizations = new Map<string, Customization>();
/**
* A collection of default customizations used as fallbacks. These serve as
* the base configuration and are registered at setup. Default customizations
* provide baseline values that can be overridden by mode or global customizations.
* Use these for cases where default values are necessary for predictable behavior.
* A collection of default customizations used as fallbacks. Entries are merged
* over time (including from `init()` re-reading extension default modules) and
* are not cleared on mode change. Mode and Global scopes override these values.
*/
private defaultCustomizations = new Map<string, Customization>();
@@ -103,41 +128,334 @@ export default class CustomizationService extends PubSubService {
private transformedCustomizations = new Map<string, Customization>();
private configuration: AppTypes.Config;
/**
* URL customization modules already imported and applied (key = normalized `/prefix/name`).
* Entries are kept for the lifetime of the page: repeated loads skip imports, and the app
* normally applies `?customization=` only at bootstrap (see {@link applyWindowUrlCustomizations}).
*/
private _urlCustomizationLoaded = new Map<string, LoadedCustomization>();
private _urlCustomizationPending = new Map<string, Promise<LoadedCustomization | null>>();
/**
* Every URL customization module resolved this page session, in load order
* (dependencies before dependents). The lifecycle phase appliers
* ({@link applyBootstrapCustomizations}, {@link applyGlobalCustomizations},
* {@link applyModeCustomizations}) iterate this list so a module's phase
* blocks are applied at the right time regardless of when it was fetched.
*/
private _resolvedUrlModules: LoadedCustomization[] = [];
/**
* Normalized form of `appConfig.customizationService`. Either a phase-tagged
* config ({@link PhasedCustomizationConfig}) or, for the legacy array/object
* form, the references to add (Global) during {@link init}.
*/
private _customizationConfig: {
phased?: PhasedCustomizationConfig;
legacyReferences?: unknown;
} | null = null;
/** Id/aliases of the mode currently entered, used to re-apply mode phase blocks. */
private _currentModeIds: string[] = [];
/**
* Extension module entry ids (e.g. `${extensionId}.customizationModule.default`) whose
* default/global payloads have already been merged via {@link init}. Matches the URL
* loader pattern: repeated {@link init} skips work for the same slot so immutability-style
* merges are not applied twice. A slot is recorded only after a module was present and applied;
* if a module appears only on a later {@link init} (e.g. a newly registered extension), it is merged then.
*/
private _extensionCustomizationModuleApplied = new Set<string>();
constructor({ configuration, commandsManager }) {
super(EVENTS);
this.configuration = configuration;
this.commandsManager = commandsManager;
}
// ===========================================================================
// Public API
// ===========================================================================
/**
* Clears mode customizations and merges each extension's `customizationModule.default` /
* `customizationModule.global` into the service. Safe to call multiple times (e.g. from
* {@link onModeEnter}): each extension module slot is merged at most once per page session,
* matching the deduplication pattern used for URL-loaded modules in {@link requires}.
* Slots with no module yet are left unmarked so a later call can merge when the module appears.
*/
public init(extensionManager: ExtensionManager): void {
this.extensionManager = extensionManager;
// Clear defaults as those are defined by the customization modules
this.defaultCustomizations.clear();
// Clear modes because those are defined in onModeEnter functions.
// Mode customizations are defined per mode in onModeEnter; reset them here.
// Default customizations are not cleared — they are merged again from
// extension modules below so definitions stay available across mode changes.
this.modeCustomizations.clear();
this.extensionManager.getRegisteredExtensionIds().forEach(extensionId => {
const keyDefault = `${extensionId}.customizationModule.default`;
const defaultCustomizations = this._findExtensionValue(keyDefault);
if (defaultCustomizations) {
const { value } = defaultCustomizations;
this._addReference(value, CustomizationScope.Default);
if (!this._extensionCustomizationModuleApplied.has(keyDefault)) {
const defaultCustomizations = this._findExtensionValue(keyDefault);
if (defaultCustomizations) {
const { value } = defaultCustomizations;
this._addReference(value, CustomizationScope.Default);
this._extensionCustomizationModuleApplied.add(keyDefault);
}
}
const keyGlobal = `${extensionId}.customizationModule.global`;
const globalCustomizations = this._findExtensionValue(keyGlobal);
if (globalCustomizations) {
const { value } = globalCustomizations;
this._addReference(value, CustomizationScope.Global);
if (!this._extensionCustomizationModuleApplied.has(keyGlobal)) {
const globalCustomizations = this._findExtensionValue(keyGlobal);
if (globalCustomizations) {
const { value } = globalCustomizations;
this._addReference(value, CustomizationScope.Global);
this._extensionCustomizationModuleApplied.add(keyGlobal);
}
}
});
// Only add references for the configuration once.
if (!this.configuration?._hasBeenAdded) {
this.addReferences(this.configuration);
// Only add references for the configuration once. The phase-tagged config
// form (bootstrap/global/mode) is applied by the lifecycle appliers
// instead, so only the legacy array/object form is added here as Global.
const config = this._getCustomizationConfig();
if (config.legacyReferences !== undefined && !this.configuration?._hasBeenAdded) {
this.addReferences(config.legacyReferences);
Object.defineProperty(this.configuration, '_hasBeenAdded', { value: true, writable: false });
}
}
/**
* Memoized, normalized view of `appConfig.customizationService`. Detects the
* phase-tagged form (any of `requires` / `bootstrap` / `global` / `mode`)
* and otherwise treats the value as legacy Global references.
*/
private _getCustomizationConfig(): { phased?: PhasedCustomizationConfig; legacyReferences?: unknown } {
if (!this._customizationConfig) {
this._customizationConfig = normalizeCustomizationConfig(this.configuration);
}
return this._customizationConfig;
}
/**
* Loads and applies `?customization=` modules from `window.location.search`.
*
* **Throws on disallowed values.** A `?customization=` value whose prefix is
* not in `appConfig.customizationUrlPrefixes` (the default — the feature is off
* until prefixes are configured) rejects this promise, which by design aborts
* app bootstrap rather than silently ignoring the request.
*
* **Intended SPA behavior:** The shell typically calls this once during startup. It does not
* run again on client-side route changes. The query key `customization` may still appear in
* URLs (for example preserved by worklist navigation) without implying that modules are
* re-evaluated on every navigation. Modules resolved here are also deduplicated by normalized
* URL for the lifetime of the page in {@link requires}. To pick up a different `?customization=`
* set, use a full page load or call {@link applyCustomizationUrlSearchParams} /
* {@link requires} from your own integration code when appropriate.
*
* **What is loaded:** Each `?customization=` entry resolves to a JSONC file (JSON with
* comments / trailing commas) under a configured prefix directory. The file is fetched and
* parsed as **data** — it is never executed. Executable code (plugins, modes, extensions)
* loads only through `pluginConfig.json`, never from the customization URL path. A module's
* `global` payload is applied as global customizations and its `requires` are loaded first.
*/
public async applyWindowUrlCustomizations(overrides?: Partial<LoadOptions>): Promise<void> {
if (typeof window === 'undefined') {
return;
}
await this.applyCustomizationUrlSearchParams(
new URLSearchParams(window.location.search),
overrides
);
}
/**
* Parses `?customization=` values from the search string and delegates to
* {@link requires}.
*/
public async applyCustomizationUrlSearchParams(
params: URLSearchParams,
overrides?: Partial<LoadOptions>
): Promise<void> {
const raws = parseCustomizationParams(params);
if (!raws.length) {
return;
}
await this.requires(raws, overrides);
}
/**
* Depth-first dynamic import of URL customization modules
* `requires` edges and `customization` field
* references are loaded before dependents. Already-loaded modules (same normalized key) are
* skipped for the rest of the page session; they are not unloaded when the address bar changes.
*
* Invalid query entries, resolve failures, failed imports, and modules without a
* customization payload are warned and skipped.
*/
public requires(
names: string | string[],
overrides?: Partial<LoadOptions>
): Promise<LoadedCustomization[]> {
return this.loadCustomizationModules(names, overrides).then(newlyLoaded => {
// Back-compat: a direct `requires()` / `applyWindowUrlCustomizations()`
// call applies the `global` slice immediately. The `bootstrap` and
// `mode` phases are driven by the boot orchestration
// ({@link loadAndApplyBootstrapCustomizations}) and {@link onModeEnter}.
this._applyLoadedUrlCustomizationModules(newlyLoaded);
return newlyLoaded;
});
}
/**
* Resolves (fetches + parses) the given URL customization modules and their
* `requires` dependencies depth-first, WITHOUT applying any phase block.
* Newly resolved modules are appended to {@link _resolvedUrlModules} in load
* order so the lifecycle appliers can apply each phase at the right time.
*
* Rejects (aborting the load) when any entry is disallowed by the policy.
*/
public loadCustomizationModules(
names: string | string[],
overrides?: Partial<LoadOptions>
): Promise<LoadedCustomization[]> {
const policy = overrides?.policy ?? getCustomizationUrlPolicy(this);
const list = (Array.isArray(names) ? names : [names])
.map(s => String(s).trim())
.filter(Boolean);
if (!list.length) {
return Promise.resolve([]);
}
const { valid, rejected } = validateCustomizationRequests(list, policy);
const logger = overrides?.logger || console;
// A `?customization=` value that is not allowed by the configured prefixes is
// a hard error: stop the load and let it propagate. The feature is off until
// `appConfig.customizationUrlPrefixes` allows a prefix, so on a default build
// any `?customization=` value throws here rather than being silently ignored.
if (rejected.length) {
const details = rejected.map(r => `"${r.raw}" (${r.reason})`).join('; ');
return Promise.reject(
new Error(
`[customizationUrl] refusing to load customization(s): ${details}. ` +
`Allowed prefixes are configured in appConfig.customizationUrlPrefixes.`
)
);
}
if (!valid.length) {
return Promise.resolve([]);
}
const importFn = overrides?.importFn ?? this._urlDefaultImport.bind(this);
const requestedSet = new Set<string>();
const newlyLoaded: LoadedCustomization[] = [];
return valid
.reduce(
(prev, request) =>
prev.then(() =>
this._urlCustomizationLoadOne(
request,
policy,
importFn,
logger,
requestedSet,
newlyLoaded
)
),
Promise.resolve() as Promise<void>
)
.then(() => {
this._resolvedUrlModules.push(...newlyLoaded);
return newlyLoaded;
});
}
/**
* Boot-time entry point that runs BEFORE extensions are registered. It:
* 1. records the ExtensionManager (so the URL policy / appConfig is readable),
* 2. resolves every customization module requested via the
* `appConfig.customizationService.requires` list and the `?customization=`
* URL parameter (their data is fetched once, up front — long before any
* mode loads), and
* 3. applies the `bootstrap` phase blocks.
*
* Rejects (aborting bootstrap) if a `?customization=` value is disallowed.
*/
public async loadAndApplyBootstrapCustomizations(
extensionManager: ExtensionManager,
overrides?: Partial<LoadOptions>
): Promise<void> {
this.extensionManager = extensionManager;
const config = this._getCustomizationConfig();
const names: string[] = [];
const requires = config.phased?.requires;
if (typeof requires === 'string' && requires) {
names.push(requires);
} else if (Array.isArray(requires)) {
names.push(...requires.filter(name => typeof name === 'string' && name));
}
if (typeof window !== 'undefined') {
names.push(...parseCustomizationParams(new URLSearchParams(window.location.search)));
}
if (names.length) {
await this.loadCustomizationModules(names, overrides);
}
this.applyBootstrapCustomizations();
}
/**
* Applies the `bootstrap` phase (Global scope) of the structured app config
* and every resolved URL module. App-config blocks apply first so URL modules
* layer on top.
*/
public applyBootstrapCustomizations(): void {
this._applyPhase('bootstrap');
}
/**
* Applies the `global` phase (Global scope) of the structured app config and
* every resolved URL module. Call after {@link init} so extension default /
* global customizations are already in place for `$apply`-style merges.
*/
public applyGlobalCustomizations(): void {
this._applyPhase('global');
}
/**
* Applies the `mode` phase (Mode scope) for the entered mode. The general
* block (`*`) is applied FIRST, then any block keyed by one of `modeIds`
* (the mode's id / routeName), so a single mode can override the general
* values. Call this AFTER `customizationService.onModeEnter()` has reset the
* mode scope (i.e. after `extensionManager.onModeEnter()`).
*/
public applyModeCustomizations(modeIds: string | string[]): void {
const ids = (Array.isArray(modeIds) ? modeIds : [modeIds]).filter(Boolean) as string[];
this._currentModeIds = ids;
const blocks = this._collectPhaseBlocks('mode') as Array<{
mode?: Record<string, CustomizationPhaseInput>;
}>;
// General first, for every source.
for (const block of blocks) {
const general = block.mode?.[GENERAL_MODE_KEY];
if (general) {
this.setCustomizations(general, CustomizationScope.Mode);
}
}
// Then mode-specific, for every source.
for (const block of blocks) {
for (const id of ids) {
const specific = block.mode?.[id];
if (specific) {
this.setCustomizations(specific, CustomizationScope.Mode);
}
}
}
}
public onModeEnter(): void {
this.clearTransformedCustomizations();
@@ -148,17 +466,6 @@ export default class CustomizationService extends PubSubService {
this.clearTransformedCustomizations();
}
private clearTransformedCustomizations(): void {
super.reset();
const modeCustomizationKeys = Array.from(this.modeCustomizations.keys());
for (const key of modeCustomizationKeys) {
this.transformedCustomizations.delete(key);
}
this.modeCustomizations.clear();
}
/**
* Unified getter for customizations.
*
@@ -184,6 +491,14 @@ export default class CustomizationService extends PubSubService {
return newTransformed;
}
/**
* Returns a customization value, or the provided fallback when unset.
*/
public getValue<T = Customization>(customizationId: string, fallbackValue?: T): T | undefined {
const value = this.getCustomization(customizationId);
return (value === undefined ? fallbackValue : (value as T)) as T | undefined;
}
/**
* Takes an object with multiple properties, each property containing
* immutability-helper commands, and applies them one by one.
@@ -229,34 +544,6 @@ export default class CustomizationService extends PubSubService {
this._setCustomization(customizationId, customization, scope);
}
/**
* Internal method to set a single customization
*/
private _setCustomization(
customizationId: string,
customization: Customization,
scope: CustomizationScope = CustomizationScope.Mode
): void {
// if (typeof customization === 'string') {
// const extensionValue = this._findExtensionValue(customization);
// customization = extensionValue.value;
// }
switch (scope) {
case CustomizationScope.Global:
this.setGlobalCustomization(customizationId, customization);
break;
case CustomizationScope.Mode:
this.setModeCustomization(customizationId, customization);
break;
case CustomizationScope.Default:
this.setDefaultCustomization(customizationId, customization);
break;
default:
throw new Error(`Invalid customization scope: ${scope}`);
}
}
/**
* Gets all customizations for a given scope.
*
@@ -303,68 +590,6 @@ export default class CustomizationService extends PubSubService {
return result.$transform?.(this) || result;
}
/**
*
* Sets a mode-specific customization.
*
* This method allows you to define or update a customization that applies only to the current mode.
* Mode customizations are temporary and isolated, reset whenever a mode changes.
*
* @param customizationId - The unique identifier for the customization.
* @param customization - The customization object containing the desired settings.
*/
private setModeCustomization(customizationId: string, customization: Customization): void {
const defaultCustomization = this.defaultCustomizations.get(customizationId);
const modeCustomization = this.modeCustomizations.get(customizationId);
const globCustomization = this.globalCustomizations.get(customizationId);
const sourceCustomization =
modeCustomization || this._cloneIfNeeded(globCustomization) || defaultCustomization;
const result = this._update(sourceCustomization, customization);
this.modeCustomizations.set(customizationId, result);
this.transformedCustomizations.clear();
this._broadcastEvent(this.EVENTS.MODE_CUSTOMIZATION_MODIFIED, {
buttons: this.modeCustomizations,
button: this.modeCustomizations.get(customizationId),
});
}
private setGlobalCustomization(id: string, value: Customization): void {
const defaultCustomization = this.defaultCustomizations.get(id);
const globCustomization = this.globalCustomizations.get(id);
const sourceCustomization = this._cloneIfNeeded(globCustomization) || defaultCustomization;
this.globalCustomizations.set(id, this._update(sourceCustomization, value));
this.transformedCustomizations.clear();
this._broadcastEvent(this.EVENTS.GLOBAL_CUSTOMIZATION_MODIFIED, {
buttons: this.defaultCustomizations,
button: this.defaultCustomizations.get(id),
});
}
private setDefaultCustomization(id: string, value: Customization): void {
if (this.defaultCustomizations.has(id)) {
console.warn(`Trying to update existing default for customization ${id}`);
}
this.transformedCustomizations.clear();
const sourceCustomization = this.defaultCustomizations.get(id);
this.defaultCustomizations.set(id, this._update(sourceCustomization, value));
this._broadcastEvent(this.EVENTS.DEFAULT_CUSTOMIZATION_MODIFIED, {
buttons: this.defaultCustomizations,
button: this.defaultCustomizations.get(id),
});
}
private _findExtensionValue(value: string) {
const entry = this.extensionManager.getModuleEntry(value);
return entry as { value: Customization };
}
/**
* Registers a custom command to be used in customization updates.
* @param commandName - The name of the command (without the $ prefix)
@@ -381,40 +606,6 @@ export default class CustomizationService extends PubSubService {
extend(commandName, handler);
}
/**
* Uses immutability-helper to apply the user's commands (e.g. $set, $push, $apply, etc.)
* Takes into account the 'mergeType' if it's explicitly 'Replace'; otherwise does a normal update.
*/
private _update(oldValue: Customization | undefined, newValue: Customization): Customization {
if (!oldValue) {
oldValue = undefined;
}
// Use immutability-helper to apply the commands
// if $ is not part of the value in the json string, then we just return the newValue
if (!hasDollarKey(newValue)) {
return newValue;
}
const result = update(oldValue, newValue);
return result;
}
private _cloneIfNeeded(value: any) {
// If it's null/undefined or not an object, return as is
if (!value || typeof value !== 'object') {
return value;
}
// If it's an array, create a shallow copy
if (Array.isArray(value)) {
return [...value];
}
// Otherwise create a shallow copy of the object
return { ...value };
}
_addReference(value?: any, type = CustomizationScope.Global): void {
if (!value) {
return;
@@ -451,6 +642,362 @@ export default class CustomizationService extends PubSubService {
this._addReference(references, type);
}
}
// ===========================================================================
// Private methods
// ===========================================================================
private clearTransformedCustomizations(): void {
super.reset();
const modeCustomizationKeys = Array.from(this.modeCustomizations.keys());
for (const key of modeCustomizationKeys) {
this.transformedCustomizations.delete(key);
}
this.modeCustomizations.clear();
}
/**
* Default loader for a `?customization=` module. Customization files are
* **data**, not code: the file is fetched and parsed as JSONC (JSON with
* comments / trailing commas, via JSON5 which is a superset). It is never
* executed. Executable modules — plugins, modes and extensions — load only
* through `pluginConfig.json`, never from the customization URL path.
*/
private async _urlDefaultImport(url: string): Promise<any> {
if (typeof fetch !== 'function') {
throw new Error(`No fetch implementation available to load customization ${url}`);
}
const response = await fetch(url);
if (!response.ok) {
throw new Error(
`Failed to fetch customization ${url}: ${response.status} ${response.statusText}`
);
}
const text = await response.text();
return JSON5.parse(text);
}
private _normalizeImportedCustomizationModule(imported: any): CustomizationModule {
return imported && typeof imported === 'object' && 'customizations' in imported
? imported
: imported && typeof imported.default === 'object'
? imported.default
: imported;
}
private _collectUrlDependencyRefs(module: CustomizationModule): string[] {
const refs = new Set<string>();
const payload = getUrlCustomizationModulePayload(module);
if (!payload || typeof payload !== 'object') {
return Array.from(refs);
}
const moduleRequires = (payload as any).requires;
if (typeof moduleRequires === 'string' && moduleRequires) {
refs.add(moduleRequires);
} else if (Array.isArray(moduleRequires)) {
for (const id of moduleRequires) {
if (typeof id === 'string' && id) {
refs.add(id);
}
}
}
return Array.from(refs);
}
private _urlDependencyToRequest(
name: string,
policy: CustomizationUrlPolicy
): ValidatedCustomization | null {
// `requires` entries are module names to load; each is validated/resolved like any
// other URL customization request. Entries that don't resolve to a valid module
// (e.g. a bare customization-key reference) are rejected by validation and
// skipped — there is no namespace carve-out.
const result = validateCustomizationRequests([name], policy);
if (result.valid.length) {
return result.valid[0];
}
return null;
}
private _urlCustomizationLoadOne(
request: ValidatedCustomization,
policy: CustomizationUrlPolicy,
importFn: (url: string) => Promise<any>,
logger: { warn: (...args: any[]) => void; error: (...args: any[]) => void },
requestedSet: Set<string>,
newlyLoaded: LoadedCustomization[]
): Promise<LoadedCustomization | null> {
const key = request.normalized;
if (this._urlCustomizationLoaded.has(key)) {
return Promise.resolve(this._urlCustomizationLoaded.get(key) || null);
}
if (this._urlCustomizationPending.has(key)) {
return this._urlCustomizationPending.get(key)!;
}
requestedSet.add(key);
const promise = this._urlCustomizationLoadOneBody(
request,
policy,
importFn,
logger,
requestedSet,
newlyLoaded
);
this._urlCustomizationPending.set(key, promise);
// Use then(success, failure) for cleanup — `finally` left rejections unhandled
// with the current Promise polyfill in the Jest/Node test stack.
promise.then(
() => this._urlCustomizationPending.delete(key),
() => this._urlCustomizationPending.delete(key)
);
return promise;
}
private _urlCustomizationLoadOneBody(
request: ValidatedCustomization,
policy: CustomizationUrlPolicy,
importFn: (url: string) => Promise<any>,
logger: { warn: (...args: any[]) => void; error: (...args: any[]) => void },
requestedSet: Set<string>,
newlyLoaded: LoadedCustomization[]
): Promise<LoadedCustomization | null> {
const key = request.normalized;
const importFailedSentinel = Symbol('importFailed');
let url: string;
try {
url = resolveCustomizationUrl(request, policy);
} catch (err) {
const msg = `[customizationUrl] failed to resolve "${request.raw}": ${(err as Error).message}`;
logger.warn(msg);
return Promise.resolve(null);
}
return importFn(url)
.catch(err => {
logger.warn(
`[customizationUrl] failed to import customization "${request.raw}" (${url})`,
err
);
return importFailedSentinel;
})
.then(importedOrSentinel => {
if (importedOrSentinel === importFailedSentinel) {
return null;
}
const imported = importedOrSentinel;
const module = this._normalizeImportedCustomizationModule(imported);
if (!module || typeof module !== 'object') {
const msg = `[customizationUrl] missing customization module "${request.raw}" (${url}): module is not an object`;
logger.warn(msg);
return null;
}
if (!getUrlCustomizationModulePayload(module)) {
const msg = `[customizationUrl] missing customization module "${request.raw}" (${url}): no customizations payload`;
logger.warn(msg);
return null;
}
const depRefs = this._collectUrlDependencyRefs(module);
let depsChain: Promise<unknown> = Promise.resolve();
for (const depRef of depRefs) {
depsChain = depsChain.then(() => {
const depRequest = this._urlDependencyToRequest(depRef, policy);
if (!depRequest || requestedSet.has(depRequest.normalized)) {
return undefined;
}
return this._urlCustomizationLoadOne(
depRequest,
policy,
importFn,
logger,
requestedSet,
newlyLoaded
);
});
}
return depsChain.then(() => {
const loaded: LoadedCustomization = { request, module, url };
this._urlCustomizationLoaded.set(key, loaded);
newlyLoaded.push(loaded);
return loaded;
});
});
}
private _applyLoadedUrlCustomizationModules(loaded: LoadedCustomization[]): void {
if (!loaded?.length) {
return;
}
for (const entry of loaded) {
const payload = getUrlCustomizationModulePayload(entry.module);
if (payload?.global) {
this.setCustomizations(payload.global, CustomizationScope.Global);
}
}
}
/**
* Collects the phase blocks for `phase` from every source, in apply order:
* the structured app config first, then each resolved URL module in load
* order. Used by {@link applyModeCustomizations}; the simpler `bootstrap` /
* `global` phases go through {@link _applyPhase}.
*/
private _collectPhaseBlocks(phase: keyof PhasedCustomizationConfig): PhasedCustomizationConfig[] {
const blocks: PhasedCustomizationConfig[] = [];
const phased = this._getCustomizationConfig().phased;
if (phased && phased[phase] !== undefined) {
blocks.push(phased);
}
for (const entry of this._resolvedUrlModules) {
const payload = getUrlCustomizationModulePayload(entry.module);
if (payload && payload[phase] !== undefined) {
blocks.push(payload);
}
}
return blocks;
}
/** Applies a Global-scoped phase (`bootstrap` / `global`) from all sources. */
private _applyPhase(phase: 'bootstrap' | 'global'): void {
for (const block of this._collectPhaseBlocks(phase)) {
const value = block[phase] as CustomizationPhaseInput | undefined;
if (value) {
this.setCustomizations(value, CustomizationScope.Global);
}
}
}
/**
* Internal method to set a single customization
*/
private _setCustomization(
customizationId: string,
customization: Customization,
scope: CustomizationScope = CustomizationScope.Mode
): void {
// if (typeof customization === 'string') {
// const extensionValue = this._findExtensionValue(customization);
// customization = extensionValue.value;
// }
switch (scope) {
case CustomizationScope.Global:
this.setGlobalCustomization(customizationId, customization);
break;
case CustomizationScope.Mode:
this.setModeCustomization(customizationId, customization);
break;
case CustomizationScope.Default:
this.setDefaultCustomization(customizationId, customization);
break;
default:
throw new Error(`Invalid customization scope: ${scope}`);
}
}
/**
*
* Sets a mode-specific customization.
*
* This method allows you to define or update a customization that applies only to the current mode.
* Mode customizations are temporary and isolated, reset whenever a mode changes.
*
* @param customizationId - The unique identifier for the customization.
* @param customization - The customization object containing the desired settings.
*/
private setModeCustomization(customizationId: string, customization: Customization): void {
const defaultCustomization = this.defaultCustomizations.get(customizationId);
const modeCustomization = this.modeCustomizations.get(customizationId);
const globCustomization = this.globalCustomizations.get(customizationId);
const sourceCustomization =
modeCustomization || this._cloneIfNeeded(globCustomization) || defaultCustomization;
const result = this._update(sourceCustomization, customization);
this.modeCustomizations.set(customizationId, result);
this.transformedCustomizations.clear();
this._broadcastEvent(this.EVENTS.MODE_CUSTOMIZATION_MODIFIED, {
buttons: this.modeCustomizations,
button: this.modeCustomizations.get(customizationId),
});
}
private setGlobalCustomization(id: string, value: Customization): void {
const defaultCustomization = this.defaultCustomizations.get(id);
const globCustomization = this.globalCustomizations.get(id);
const sourceCustomization = this._cloneIfNeeded(globCustomization) || defaultCustomization;
this.globalCustomizations.set(id, this._update(sourceCustomization, value));
this.transformedCustomizations.clear();
this._broadcastEvent(this.EVENTS.GLOBAL_CUSTOMIZATION_MODIFIED, {
buttons: this.globalCustomizations,
button: this.globalCustomizations.get(id),
});
}
private setDefaultCustomization(id: string, value: Customization): void {
// There are two inits now, without a clear between them, so we can't warn about existing defaults
// if (this.defaultCustomizations.has(id)) {
// console.warn(`Trying to update existing default for customization ${id}`);
// }
this.transformedCustomizations.clear();
const sourceCustomization = this.defaultCustomizations.get(id);
this.defaultCustomizations.set(id, this._update(sourceCustomization, value));
this._broadcastEvent(this.EVENTS.DEFAULT_CUSTOMIZATION_MODIFIED, {
buttons: this.defaultCustomizations,
button: this.defaultCustomizations.get(id),
});
}
private _findExtensionValue(value: string) {
const entry = this.extensionManager.getModuleEntry(value);
return entry as { value: Customization };
}
/**
* Uses immutability-helper to apply the user's commands (e.g. $set, $push, $apply, etc.)
* Takes into account the 'mergeType' if it's explicitly 'Replace'; otherwise does a normal update.
*/
private _update(oldValue: Customization | undefined, newValue: Customization): Customization {
if (!oldValue) {
oldValue = undefined;
}
// Use immutability-helper to apply the commands
// if $ is not part of the value in the json string, then we just return the newValue
if (!hasDollarKey(newValue)) {
return newValue;
}
const result = update(oldValue, newValue);
return result;
}
private _cloneIfNeeded(value: any) {
// If it's null/undefined or not an object, return as is
if (!value || typeof value !== 'object') {
return value;
}
// If it's an array, create a shallow copy
if (Array.isArray(value)) {
return [...value];
}
// Otherwise create a shallow copy of the object
return { ...value };
}
}
/** Add custom $filter command */
@@ -523,6 +1070,48 @@ extend('$filter', (query, original) => {
return deepFilter(original, query);
});
const PHASE_CONFIG_KEYS: Array<keyof PhasedCustomizationConfig> = [
'requires',
'bootstrap',
'global',
'mode',
];
/**
* Normalizes `appConfig.customizationService` into either:
* - `{ phased }` — the structured, phase-tagged config, detected by
* the presence of any of `requires` / `bootstrap`
* / `global` / `mode`; or
* - `{ legacyReferences }` — the legacy array / object-map form, which is
* added (Global scope) during `init()` exactly as
* before.
*/
export function normalizeCustomizationConfig(configuration: unknown): {
phased?: PhasedCustomizationConfig;
legacyReferences?: unknown;
} {
if (!configuration) {
return {};
}
if (Array.isArray(configuration)) {
return { legacyReferences: configuration };
}
if (typeof configuration === 'object') {
const isPhased = PHASE_CONFIG_KEYS.some(key => key in (configuration as object));
if (isPhased) {
const phased: PhasedCustomizationConfig = {};
for (const key of PHASE_CONFIG_KEYS) {
if (key in (configuration as object)) {
(phased as Record<string, unknown>)[key] = (configuration as Record<string, unknown>)[key];
}
}
return { phased };
}
return { legacyReferences: configuration };
}
return {};
}
function hasDollarKey(value) {
if (Array.isArray(value)) {
for (const item of value) {
@@ -0,0 +1,49 @@
import {
CUSTOMIZATION_URL_PREFIXES_KEY,
customizationUrlDefaults,
DEFAULT_PREFIX,
} from './customizationUrlDefaults';
import type { CustomizationUrlPolicy } from './customizationUrlDefaults';
import { getUrlCustomizationModulePayload } from './getUrlCustomizationModulePayload';
import {
parseCustomizationParams,
validateCustomizationRequests,
normalizeCustomizationValue,
} from './validate';
import type { ValidatedCustomization, ValidationResult } from './validate';
import { resolveCustomizationUrl } from './resolve';
/**
* Builds the `?customization=` policy from the **app config** property
* `customizationUrlPrefixes` (read off `extensionManager.appConfig`). This is
* intentionally not a customization: customizations can be loaded from the URL,
* so letting one define prefixes would let it widen its own allowlist. When the
* property is absent the policy has no prefixes and the feature is off.
*/
export function getCustomizationUrlPolicy(customizationService: any): CustomizationUrlPolicy {
const prefixes =
customizationService?.extensionManager?.appConfig?.[CUSTOMIZATION_URL_PREFIXES_KEY];
if (prefixes && typeof prefixes === 'object') {
return { prefixes };
}
return customizationUrlDefaults;
}
export {
CUSTOMIZATION_URL_PREFIXES_KEY,
customizationUrlDefaults,
DEFAULT_PREFIX,
getUrlCustomizationModulePayload,
parseCustomizationParams,
validateCustomizationRequests,
normalizeCustomizationValue,
resolveCustomizationUrl,
};
export type {
CustomizationUrlPolicy,
ValidatedCustomization,
ValidationResult,
};
export type { CustomizationModule, LoadedCustomization, LoadOptions } from './customizationUrlTypes';
@@ -0,0 +1,42 @@
/**
* Policy for the `?customization=` URL query parameter.
*
* The effective policy comes from the **app config** property
* `customizationUrlPrefixes` (NOT a customization — a customization must never
* be able to widen its own allowlist). When that property is absent the policy
* has no prefixes, so the feature is **off by default**: any `?customization=`
* value is rejected because its prefix is not configured.
*
* Shape:
* - prefixes: map of prefix -> base URL used to resolve a customization value
* to a fetched `.jsonc` data file. The `default` prefix (no slashes) is used
* for values with no leading slash; every other prefix must start and end
* with a slash (e.g. `/remote/`) and is matched against the leading
* `/segment/` of the value.
*
* Example app config:
* window.config = {
* customizationUrlPrefixes: {
* default: './customizations/',
* '/remote/': 'https://cdn.example.com/ohif-customizations/',
* },
* };
*/
export interface CustomizationUrlPolicy {
prefixes: Record<string, string>;
}
/**
* App config property name holding the prefix allowlist. Read directly off
* `appConfig` — deliberately not a customization key.
*/
export const CUSTOMIZATION_URL_PREFIXES_KEY = 'customizationUrlPrefixes';
export const DEFAULT_PREFIX = 'default';
/** Off by default: no prefixes are allowed until the app config configures them. */
export const customizationUrlDefaults: CustomizationUrlPolicy = {
prefixes: {},
};
export default customizationUrlDefaults;
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more