Skip to content
Merged
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

Large diffs are not rendered by default.

34 changes: 23 additions & 11 deletions src/application/project/sdk/plugNextSdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {ApiKeyPermission} from '@/application/model/application';
import {PlugReactExampleGenerator} from '@/application/project/code/generation/slot/plugReactExampleGenerator';

type CodemodConfiguration = {
proxy: Codemod<string>,
middleware: Codemod<string>,
fallbackProvider: Codemod<string, AppComponentOptions>,
appRouterProvider: Codemod<string, LayoutComponentOptions>,
Expand All @@ -50,7 +51,8 @@ type NextProjectInfo = {
router: NextRouter,
sourceDirectory: string,
pageDirectory: string,
middleware: {
proxy: {
name: 'proxy' | 'middleware',
file: string,
},
provider: {
Expand Down Expand Up @@ -181,10 +183,11 @@ export class PlugNextSdk extends JavaScriptSdk {
}

private async getProjectInfo(): Promise<NextProjectInfo> {
const [isTypescript, directory, fallbackMode] = await Promise.all([
const [isTypescript, directory, fallbackMode, legacyMiddleware] = await Promise.all([
this.isTypeScriptProject(),
this.getPageDirectory(),
this.isFallbackMode(),
this.packageManager.hasDirectDependency('next', '<16'),
]);

const project: Pick<NextProjectInfo, 'typescript' | 'router' | 'sourceDirectory' | 'pageDirectory'> = {
Expand All @@ -194,9 +197,11 @@ export class PlugNextSdk extends JavaScriptSdk {
pageDirectory: directory,
};

const [middlewareFile, providerComponentFile] = await Promise.all([
const proxyName = legacyMiddleware ? 'middleware' : 'proxy';

const [proxyFile, providerComponentFile] = await Promise.all([
this.locateFile(
...['middleware.js', 'middleware.ts']
...[`${proxyName}.js`, `${proxyName}.ts`]
.map(file => this.fileSystem.joinPaths(project.sourceDirectory, file)),
),
this.locateFile(
Expand Down Expand Up @@ -233,8 +238,9 @@ export class PlugNextSdk extends JavaScriptSdk {
this.fileSystem.joinPaths(projectDirectory, '.env.production'),
),
},
middleware: {
file: middlewareFile ?? this.fileSystem.joinPaths(project.sourceDirectory, `middleware.${extension}`),
proxy: {
name: proxyName,
file: proxyFile ?? this.fileSystem.joinPaths(project.sourceDirectory, `${proxyName}.${extension}`),
},
provider: {
file: providerComponentFile
Expand All @@ -251,17 +257,19 @@ export class PlugNextSdk extends JavaScriptSdk {
const tasks: Task[] = [];

if (!installation.project.fallbackMode) {
const proxyName = installation.project.proxy.name;

tasks.push({
title: 'Configure middleware',
title: `Configure ${proxyName}`,
task: async notifier => {
notifier.update('Configuring middleware');
notifier.update(`Configuring ${proxyName}`);

try {
await this.updateCode(this.codemod.middleware, installation.project.middleware.file);
await this.updateCode(this.codemod[proxyName], installation.project.proxy.file);

notifier.confirm('Middleware configured');
notifier.confirm(`${PlugNextSdk.capitalize(proxyName)} configured`);
} catch (error) {
notifier.alert('Failed to install middleware', HelpfulError.formatMessage(error));
notifier.alert(`Failed to install ${proxyName}`, HelpfulError.formatMessage(error));
}
},
});
Expand Down Expand Up @@ -440,4 +448,8 @@ export class PlugNextSdk extends JavaScriptSdk {
private isFallbackMode(): Promise<boolean> {
return this.packageManager.hasDirectDependency('next', '<=13');
}

private static capitalize(name: string): string {
return name.charAt(0).toUpperCase() + name.slice(1);
}
}
44 changes: 24 additions & 20 deletions src/infrastructure/application/cli/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import {Command, CommandInput} from '@/application/cli/command/command';
import {AdminCommand, AdminInput} from '@/application/cli/command/admin';
import {JsxWrapperCodemod} from '@/application/project/code/transformation/javascript/jsxWrapperCodemod';
import {JavaScriptCodemod} from '@/application/project/code/transformation/javascript/javaScriptCodemod';
import {NextJsMiddlewareCodemod} from '@/application/project/code/transformation/javascript/nextJsMiddlewareCodemod';
import {NextJsProxyCodemod} from '@/application/project/code/transformation/javascript/nextJsProxyCodemod';
import {CodeFormatter} from '@/application/project/code/formatting/formatter';
import {FormatCodemod} from '@/application/project/code/transformation/formatCodemod';
import {FileCodemod} from '@/application/project/code/transformation/fileCodemod';
Expand Down Expand Up @@ -1796,31 +1796,35 @@ export class Cli {
},
};

const createProxyCodemod = (proxyName: string): Codemod<string> => new FormatCodemod(
formatter,
new FileCodemod({
fileSystem: this.getFileSystem(),
codemod: new JavaScriptCodemod({
languages: ['typescript', 'jsx'],
codemod: new NextJsProxyCodemod({
// eslint-disable-next-line max-len -- Ignore for readability
matcherPattern: '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
exportName: proxyName,
import: {
module: `@croct/plug-next/${proxyName}`,
proxyName: proxyName,
proxyFactoryName: 'withCroct',
},
}),
}),
}),
);

return new PlugNextSdk({
...config,
plugins: [this.createStoryblokPlugin(Platform.NEXTJS)],
userApi: this.getUserApi(),
applicationApi: this.getApplicationApi(),
importResolver: importResolver,
codemod: {
middleware: new FormatCodemod(
formatter,
new FileCodemod({
fileSystem: this.getFileSystem(),
codemod: new JavaScriptCodemod({
languages: ['typescript', 'jsx'],
codemod: new NextJsMiddlewareCodemod({
// eslint-disable-next-line max-len -- Ignore for readability
matcherPattern: '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
import: {
module: '@croct/plug-next/middleware',
middlewareName: 'middleware',
middlewareFactoryName: 'withCroct',
},
}),
}),
}),
),
proxy: createProxyCodemod('proxy'),
middleware: createProxyCodemod('middleware'),
appRouterProvider: new FormatCodemod(
formatter,
new FileCodemod({
Expand Down Expand Up @@ -2177,7 +2181,7 @@ export class Cli {
return this.share(
this.getJavaScriptFormatter,
() => new JavaScriptFormatter({
commandExecutor: this.getAsynchronousCommandExecutor(),
commandExecutor: this.getSynchronousCommandExecutor(),
workingDirectory: this.workingDirectory,
packageManager: this.getNodePackageManager(),
fileSystem: this.getFileSystem(),
Expand Down
12 changes: 7 additions & 5 deletions src/infrastructure/application/project/javaScriptFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {CodeFormatter, CodeFormatterError} from '@/application/project/code/form
import {FileSystem} from '@/application/fs/fileSystem';
import {Dependency, PackageManager} from '@/application/project/packageManager/packageManager';
import {WorkingDirectory} from '@/application/fs/workingDirectory/workingDirectory';
import {CommandExecutor} from '@/application/system/process/executor';
import {SynchronousCommandExecutor} from '@/application/system/process/executor';
import {Command} from '@/application/system/process/command';

type FormatterTool = {
Expand All @@ -15,7 +15,7 @@ export type Configuration = {
workingDirectory: WorkingDirectory,
fileSystem: FileSystem,
packageManager: PackageManager,
commandExecutor: CommandExecutor,
commandExecutor: SynchronousCommandExecutor,
timeout?: number,
tools: FormatterTool[],
};
Expand All @@ -41,17 +41,19 @@ export class JavaScriptFormatter implements CodeFormatter {
}
}

private async run(command: Command): Promise<void> {
private run(command: Command): Promise<void> {
const {commandExecutor, workingDirectory, timeout} = this.configuration;

const execution = await commandExecutor.run(command, {
const execution = commandExecutor.runSync(command, {
workingDirectory: workingDirectory.get(),
timeout: timeout,
});

if (await execution.wait() !== 0) {
if (execution.exitCode !== 0) {
throw new CodeFormatterError('Failed to format code.');
}

return Promise.resolve();
}

private async getCommand(files: string[]): Promise<Command|null> {
Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest): void {
export function proxy(request: NextRequest): void {
console.log(request.url);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { NextRequest } from 'next/server'

export default function middleware(request: NextRequest): void {
export default function proxy(request: NextRequest): void {
console.log(request.url);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { NextRequest } from 'next/server'

// middleware
export function middleware(request: NextRequest): void {
// proxy
export function proxy(request: NextRequest): void {
console.log(request.url);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { NextRequest } from 'next/server'

export default function middleware(request: NextRequest): void {
export default function proxy(request: NextRequest): void {
console.log(request.url);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
}

export function middleware(request: NextRequest): void {
export function proxy(request: NextRequest): void {
console.log(request.url);
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ const indirectReference = configValue;

export const config = indirectReference;

export function middleware(request) {
export function proxy(request) {
console.log(request.url);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ export const config = {
matcher: '/((?!api|_next/static|_next/image|favicon.ico).*)',
}

export function middleware(request) {
export function proxy(request) {
console.log(request.url);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ export const config = {
matcher: regex,
}

export function middleware(request) {
export function proxy(request) {
console.log(request.url);
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ const configValue = {

export const config = configValue;

export function middleware(request) {
export function proxy(request) {
console.log(request.url);
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export const config = {
}

export function middleware(request) {
export function proxy(request) {
console.log(request.url);
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export default function () {
console.log('middleware');
console.log('proxy');
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default () => {
console.log('proxy');
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default class Proxy {
// invalid
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { withCroct as croctProxy } from "@croct/plug-next/proxy";

export default croctProxy(function () {
console.log('proxy');
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { proxy } from "@croct/plug-next/proxy";

export default proxy(function () {
console.log('proxy');
});
Loading
Loading