Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions packages/plugins/apps/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,14 @@
"hideFromRootReadme": true
},
"toBuild": {
"apps-runtime": {
"entry": "./src/built/apps-runtime.ts",
"apps-runtime-dev": {
"entry": "./src/built/apps-runtime-dev.ts",
"format": [
"esm"
]
},
"apps-runtime-prod": {
"entry": "./src/built/apps-runtime-prod.ts",
"format": [
"esm"
]
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@
// lives with the original tests in web-ui's @datadog/apps-function-query
// until a DOM-enabled harness is introduced.

import { executeBackendFunction } from './execute-backend-function';
import { BackendFunctionError } from './types';
import { BackendFunctionError } from '../types';

describe('executeBackendFunction', () => {
import { devServerTransport } from './dev-server-transport';

describe('devServerTransport', () => {
let originalFetch: typeof fetch;

beforeEach(() => {
Expand All @@ -30,7 +31,7 @@ describe('executeBackendFunction', () => {
json: async () => mockResponse,
});

const result = await executeBackendFunction<{ sum: number }>('testWithImport', [5, 7]);
const result = await devServerTransport<{ sum: number }>('testWithImport', [5, 7]);

expect(result).toEqual({ sum: 12 });
expect(global.fetch).toHaveBeenCalledWith('/__dd/executeAction', {
Expand All @@ -48,11 +49,9 @@ describe('executeBackendFunction', () => {
it('should throw BackendFunctionError on network error', async () => {
global.fetch = jest.fn().mockRejectedValue(new Error('Network failed'));

await expect(executeBackendFunction('testFunction', [])).rejects.toThrow(
BackendFunctionError,
);
await expect(devServerTransport('testFunction', [])).rejects.toThrow(BackendFunctionError);

await expect(executeBackendFunction('testFunction', [])).rejects.toThrow(
await expect(devServerTransport('testFunction', [])).rejects.toThrow(
'Network error while executing backend function "testFunction"',
);
});
Expand All @@ -64,11 +63,9 @@ describe('executeBackendFunction', () => {
text: async () => 'Internal Server Error',
});

await expect(executeBackendFunction('testFunction', [])).rejects.toThrow(
BackendFunctionError,
);
await expect(devServerTransport('testFunction', [])).rejects.toThrow(BackendFunctionError);

await expect(executeBackendFunction('testFunction', [])).rejects.toThrow(
await expect(devServerTransport('testFunction', [])).rejects.toThrow(
'Backend function "testFunction" failed with status 500',
);
});
Expand All @@ -83,11 +80,9 @@ describe('executeBackendFunction', () => {
json: async () => mockResponse,
});

await expect(executeBackendFunction('testFunction', [])).rejects.toThrow(
BackendFunctionError,
);
await expect(devServerTransport('testFunction', [])).rejects.toThrow(BackendFunctionError);

await expect(executeBackendFunction('testFunction', [])).rejects.toThrow(
await expect(devServerTransport('testFunction', [])).rejects.toThrow(
'Backend function "testFunction" returned an error',
);
});
Expand All @@ -101,11 +96,9 @@ describe('executeBackendFunction', () => {
},
});

await expect(executeBackendFunction('testFunction', [])).rejects.toThrow(
BackendFunctionError,
);
await expect(devServerTransport('testFunction', [])).rejects.toThrow(BackendFunctionError);

await expect(executeBackendFunction('testFunction', [])).rejects.toThrow(
await expect(devServerTransport('testFunction', [])).rejects.toThrow(
'Failed to parse response from backend function',
);
});
Expand All @@ -117,7 +110,7 @@ describe('executeBackendFunction', () => {
text: async () => 'Not Found',
});

await expect(executeBackendFunction('testFunction', [])).rejects.toMatchObject({
await expect(devServerTransport('testFunction', [])).rejects.toMatchObject({
name: 'BackendFunctionError',
functionName: 'testFunction',
statusCode: 404,
Expand Down
10 changes: 10 additions & 0 deletions packages/plugins/apps/src/built/apps-runtime-dev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.

/* eslint-env browser */
/* global globalThis */
import { devServerTransport } from '../backend/client/transports/dev-server-transport';

const globalAny: any = globalThis;
globalAny.DD_APPS_RUNTIME = { executeBackendFunction: devServerTransport };
10 changes: 10 additions & 0 deletions packages/plugins/apps/src/built/apps-runtime-prod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.

/* eslint-env browser */
/* global globalThis */
import { postMessageTransport } from '../backend/client/transports/post-message-transport/post-message-transport';

const globalAny: any = globalThis;
globalAny.DD_APPS_RUNTIME = { executeBackendFunction: postMessageTransport };
14 changes: 0 additions & 14 deletions packages/plugins/apps/src/built/apps-runtime.ts

This file was deleted.

46 changes: 31 additions & 15 deletions packages/plugins/apps/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,21 +59,37 @@ describe('Apps Plugin - getPlugins', () => {
expect(getPlugins(getArgs())).toHaveLength(1);
});

test('Should inject the apps runtime at the top of the user bundle when enabled', () => {
const injectMock = jest.fn();
getPlugins(
getGetPluginsArg(
{ apps: {} },
{ bundler: { ...getMockBundler({ name: 'vite' }), outDir }, inject: injectMock },
),
);

expect(injectMock).toHaveBeenCalledWith({
type: 'file',
position: InjectPosition.MIDDLE,
value: expect.stringContaining('apps-runtime.mjs'),
});
});
const runtimeInjectionCases = [
{ command: 'serve' as const, runtime: 'apps-runtime-dev.mjs' },
{ command: 'build' as const, runtime: 'apps-runtime-prod.mjs' },
];

test.each(runtimeInjectionCases)(
'Should inject the $runtime runtime when vite command is "$command"',
({ command, runtime }) => {
const injectMock = jest.fn();
const plugins = getPlugins(
getGetPluginsArg(
{ apps: {} },
{
bundler: { ...getMockBundler({ name: 'vite' }), outDir },
inject: injectMock,
},
),
);
const configHook = plugins[0].vite!.config as (
userConfig: object,
env: { command: 'serve' | 'build' },
) => void;
configHook({}, { command });

expect(injectMock).toHaveBeenCalledWith({
type: 'file',
position: InjectPosition.MIDDLE,
value: expect.stringContaining(runtime),
});
},
);

test('Should not inject the runtime when disabled', () => {
const injectMock = jest.fn();
Expand Down
18 changes: 2 additions & 16 deletions packages/plugins/apps/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import { rm } from '@dd/core/helpers/fs';
import type { GetPlugins } from '@dd/core/types';
import { InjectPosition } from '@dd/core/types';
import chalk from 'chalk';
import path from 'path';

Expand Down Expand Up @@ -89,21 +88,6 @@ export const getPlugins: GetPlugins = ({ options, context, bundler }) => {
return [];
}

// Inject the runtime that `globalThis.DD_APPS_RUNTIME.executeBackendFunction`
// is read from. The generated proxy modules (emitted by the transform hook
// below) reference that global. NOTE: This file is built alongside the
// bundler plugin via the `toBuild` entry in @dd/apps-plugin's package.json.
//
// Position MIDDLE is used instead of BEFORE so Vite's dev server injects
// the runtime as a <script type="module"> via `transformIndexHtml` — BEFORE
// is served via Rollup's `banner()` output hook which only fires at build
// time, leaving the runtime undefined during `vite` (dev).
context.inject({
type: 'file',
position: InjectPosition.MIDDLE,
value: path.join(__dirname, './apps-runtime.mjs'),
});

const { setBackendFunctions, getBackendFunctions } = createBackendFunctionRegistry();

const handleUpload = async (backendOutputs: Map<string, string>) => {
Expand Down Expand Up @@ -257,6 +241,8 @@ Either:
handleUpload,
log,
auth: context.auth,
inject: context.inject,
pluginDir: __dirname,
}),
},
];
Expand Down
2 changes: 2 additions & 0 deletions packages/plugins/apps/src/vite/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ const defaultOptions = {
handleUpload: mockHandleUpload,
log,
auth: { site: 'datadoghq.com' },
inject: jest.fn(),
pluginDir: '/plugin',
};

describe('Backend Functions - getVitePlugin', () => {
Expand Down
23 changes: 22 additions & 1 deletion packages/plugins/apps/src/vite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
// Copyright 2019-Present Datadog, Inc.

import { rm } from '@dd/core/helpers/fs';
import type { AuthOptionsWithDefaults, Logger, PluginOptions } from '@dd/core/types';
import type { AuthOptionsWithDefaults, GlobalContext, Logger, PluginOptions } from '@dd/core/types';
import { InjectPosition } from '@dd/core/types';
import path from 'path';
import type { build } from 'vite';

import type { BackendFunction } from '../backend/discovery';
Expand All @@ -18,11 +20,17 @@ export interface VitePluginOptions {
handleUpload: (backendOutputs: Map<string, string>) => Promise<void>;
log: Logger;
auth: AuthOptionsWithDefaults;
inject: GlobalContext['inject'];
pluginDir: string;
}

/**
* Returns the Vite-specific plugin hooks for the apps plugin.
*
* Config: injects either the dev-server or postMessage runtime depending on
* whether Vite is running in `serve` (dev) or `build` (production) mode, so
* each bundle ships only the transport it needs.
*
* Production (closeBundle): builds backend functions (if any) then uploads
* all assets sequentially.
*
Expand All @@ -36,7 +44,20 @@ export const getVitePlugin = ({
handleUpload,
log,
auth,
inject,
pluginDir,
}: VitePluginOptions): PluginOptions['vite'] => ({
config(_userConfig, { command }) {
// Position MIDDLE so the runtime is injected via Vite's
// `transformIndexHtml` in dev — BEFORE goes through Rollup's
// `banner()` which only fires at build time.
const runtime = command === 'serve' ? 'apps-runtime-dev.mjs' : 'apps-runtime-prod.mjs';
inject({
type: 'file',
position: InjectPosition.MIDDLE,
value: path.join(pluginDir, runtime),
});
},
async closeBundle() {
let backendOutDir: string | undefined;
let backendOutputs = new Map<string, string>();
Expand Down
Loading