Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

error when starting nextjs after installing @codesandbox/sdk #4

Open
nalaso opened this issue Dec 13, 2024 · 15 comments
Open

error when starting nextjs after installing @codesandbox/sdk #4

nalaso opened this issue Dec 13, 2024 · 15 comments

Comments

@nalaso
Copy link

nalaso commented Dec 13, 2024

Build Error
Next.js (15.0.1) out of date (learn more)
Failed to compile

./node_modules/glob-stream/node_modules/through2/through2.js:1:1
Module not found: Can't resolve 'readable-stream/transform'

1 | var Transform = require('readable-stream/transform')
| ^
2 | , inherits = require('util').inherits
3 | , xtend = require('xtend')
4 |

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./node_modules/glob-stream/index.js
./node_modules/vinyl-fs/lib/src/index.js
./node_modules/vinyl-fs/index.js
./node_modules/module/dist/index.js
./node_modules/@codesandbox/sdk/dist/esm/index.edge.js
./src/store/codeSandboxStore.ts
./src/components/app/console.tsx
This error occurred during the build process and can only be dismissed by fixing the error.

@nalaso
Copy link
Author

nalaso commented Dec 13, 2024

First, it showed "module" not found so I installed "module" manually.

@nalaso
Copy link
Author

nalaso commented Dec 13, 2024

Module not found: Can't resolve 'module'

1 | import {createRequire} from 'module'
| ^
2 | const require = createRequire(import.meta.url)
3 | var __create = Object.create;
4 | var __defProp = Object.defineProperty;

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./src/store/codeSandboxStore.ts
./src/components/app/console.tsx

@nalaso
Copy link
Author

nalaso commented Dec 13, 2024

my code

import { create } from "zustand";
import { CodeSandbox, VMTier } from "@codesandbox/sdk";

interface CodeSandboxStore {
  sandbox: any | null;
  sandboxInitialized: boolean;
  setSandbox: (sandbox: any) => void;
  boot: (templateId: string) => Promise<void>;
}

export const useCodeSandboxStore = create<CodeSandboxStore>((set, get) => ({
  sandbox: null,
  sandboxInitialized: false,
  setSandbox: (sandbox: any) => set({ sandbox }),
  boot: async (templateId: string) => {
    if (get().sandbox) {
      return;
    }

    try {
      const sdk = new CodeSandbox(process.env.CSB_API_KEY!); //error occurs here
      const sandbox = await sdk.sandbox.create({
        vmTier: VMTier.Pico ,
        template: templateId,
      });
      
      set({ 
        sandbox,
        sandboxInitialized: true
      });
    } catch (error) {
      console.error("Failed to boot CodeSandbox:", error);
      throw error;
    }
  },
}));

@nalaso
Copy link
Author

nalaso commented Dec 13, 2024

its also showing this

⚠ ./node_modules/@codesandbox/sdk/dist/esm/index.js
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

Import trace for requested module:
./node_modules/@codesandbox/sdk/dist/esm/index.js

tried with node v18.20.5, v22.12.0, v23.4.0, v20.18.0

@nalaso
Copy link
Author

nalaso commented Dec 13, 2024

i also tried it in api

import { CodeSandbox } from '@codesandbox/sdk'
import { NextResponse } from 'next/server';

const sdk = new CodeSandbox(process.env.CSB_API_KEY!);

export async function POST(request: Request) {
	try {
		const { id } = await request.json();

		if (!id) {
			return NextResponse.json(
				{ error: 'Template ID is required' },
				{ status: 400 }
			);
		}

		const startData = await sdk.sandbox.start(id);

		console.log("startData", startData);
	
		return NextResponse.json(startData);
	} catch (error) {
		console.error('Failed to start sandbox:', error);
		return NextResponse.json(
			{ error: 'Failed to start sandbox' },
			{ status: 500 }
		);
	}
}

Import trace for requested module:
./node_modules/@codesandbox/sdk/dist/esm/index.js
./src/app/api/sandbox/start/route.ts
⚠ ./node_modules/@codesandbox/sdk/dist/esm/index.js
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

@CompuIves
Copy link
Member

Interesting. I believe we've seen this issue before. Could you try running Next.js with Turbo enabled and see if you can reproduce this? I'm talking with the Next.js team to see how we can resolve this.

@nalaso
Copy link
Author

nalaso commented Dec 14, 2024

I also tried it with a remix + vite project. its still the same

@nalaso
Copy link
Author

nalaso commented Dec 14, 2024

i tried it using express server
https://codesandbox.io/docs/sdk/sandboxes#opening-a-sandbox-from-the-browser

when using module type

import express from 'express';
import {CodeSandbox} from '@codesandbox/sdk';
import dotenv from 'dotenv';
dotenv.config();

const app = express();
const sdk = new CodeSandbox(process.env.CODESANDBOX_API_KEY);

app.get('/api/start-sandbox/:id', async (req, res) => {
  const startData = await sdk.sandbox.start(req.params.id);

  res.json(startData);
});

const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

error

import {CodeSandbox} from '@codesandbox/sdk';
        ^^^^^^^^^^^
SyntaxError: Named export 'CodeSandbox' not found. The requested module '@codesandbox/sdk' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from '@codesandbox/sdk';
const {CodeSandbox} = pkg;

    at ModuleJob._instantiate (node:internal/modules/esm/module_job:146:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:229:5)
    at async ModuleLoader.import (node:internal/modules/esm/loader:473:24)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:123:5)

Node.js v20.18.0

after some change

import express from 'express';
import pkg from '@codesandbox/sdk';
import dotenv from 'dotenv';
dotenv.config();

const { CodeSandbox } = pkg;

const app = express();
const sdk = new CodeSandbox(process.env.CODESANDBOX_API_KEY);
 
app.get('/api/start-sandbox/:id', async (req, res) => {
  const startData = await sdk.sandbox.start(req.params.id);
 
  res.json(startData);
});

error

node index.js

(node:71433) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/node_modules/@codesandbox/sdk/dist/esm/index.js:2
const require = createRequire(import.meta.url)
      ^

SyntaxError: Identifier 'require' has already been declared

using commonjs

const express = require('express');
const { CodeSandbox } = require('@codesandbox/sdk');
require('dotenv').config();
 
const app = express();
const sdk = new CodeSandbox(process.env.CODESANDBOX_API_KEY);
 
app.get('/api/start-sandbox/:id', async (req, res) => {
  const startData = await sdk.sandbox.start(req.params.id);
 
  res.json(startData);
});

during api call
error

Server is running on http://localhost:8000
/node_modules/@codesandbox/sdk/dist/cjs/index.js:40102
    throw new Error(errorPrefix + ": " + error);
          ^

Error: Failed to start sandbox newid: Cannot fulfill this request for a browser sandbox
    at handleResponse (/node_modules/@codesandbox/sdk/dist/cjs/index.js:40102:11)
    at SandboxClient.start (/node_modules/@codesandbox/sdk/dist/cjs/index.js:40226:18)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async /index.js:8:21

Node.js v20.18.0

@nalaso
Copy link
Author

nalaso commented Dec 14, 2024

may I know the node version, express version, etc., in which the package was tested so that I can stick with those versions for now until the fix is done?

@nalaso
Copy link
Author

nalaso commented Dec 14, 2024

it works if we are creating the sandbox inside express.

const express = require('express');
const { CodeSandbox } = require('@codesandbox/sdk');
const cors = require('cors');
require('dotenv').config();
 
const app = express();
const sdk = new CodeSandbox(process.env.CODESANDBOX_API_KEY);

app.use(cors());

app.get('/api/start-sandbox/:id', async (req, res) => {
  const sandbox = await sdk.sandbox.create();
  const startData = await sdk.sandbox.start(sandbox.id);
  console.log(startData);
  
  res.json(startData);
});

const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

prints

Server is running on http://localhost:8000
{
  id: 'abcde',
  cluster: 'fc-eu-3',
  reconnect_token: null,
  bootup_type: 'RUNNING',
  latest_pitcher_version: '1.350.3',
  pitcher_manager_version: '1.47.0',
  pitcher_token: 'abcdeabcdeabcde',
  pitcher_url: 'wss://abcde.abcde.codesandbox.io',
  pitcher_version: '0.310.2',
  user_workspace_path: '/project/workspace',
  workspace_path: '/project/sandbox'
}

This work fine. wondering if this correct?

import { create } from "zustand";
import { connectToSandbox } from '@codesandbox/sdk/browser'

interface CodeSandboxStore {
  sandbox: any | null;
  sandboxInitialized: boolean;
  setSandbox: (sandbox: any) => void;
  boot: (templateId: string) => Promise<void>;
}

export const useCodeSandboxStore = create<CodeSandboxStore>((set, get) => ({
  sandbox: null,
  sandboxInitialized: false,
  setSandbox: (sandbox: any) => set({ sandbox }),
  boot: async (templateId: string) => {
    if (get().sandbox) {
      return;
    }

    try {
      const response = await fetch('http://localhost:8000/api/start-sandbox/newid', {
        method: 'GET',
      });

      if (!response.ok) {
        throw new Error('Failed to start sandbox');
      }

      const startData = await response.json();
      console.log("startData", startData);
      const sandbox = await connectToSandbox(startData);

      set({
        sandbox,
        sandboxInitialized: true
      });
    } catch (error) {
      console.error("Failed to initialize CodeSandbox:", error);
      set({ sandboxInitialized: false });
    }
  }
}));

also sandbox created using const sandbox = await connectToSandbox(startData); doesnt have shutdown, hibernate methods. so do i have to create another api to shutdown it? or is there any other way?

image

@CompuIves
Copy link
Member

That is so weird, let me create an example where I have it working.

@CompuIves
Copy link
Member

also sandbox created using const sandbox = await connectToSandbox(startData); doesnt have shutdown, hibernate methods. so do i have to create another api to shutdown it? or is there any other way?

Right, we don't expose the shutdown and hibernate methods in the browser, because normally you need to use an API token to do actions on VMs, and we don't want to expose that token in the browser. We could add shutdown and hibernate actions directly to the VM, but I wonder if we want to allow users to use that API on their sandbox...

Generally I would recommend to do sandbox management (start, hibernate, shutdown) on the server, and then you can pass authorization to the browser for users to use the sandbox.

@CompuIves
Copy link
Member

I will try to reproduce your error and fix it in the library itself!

@CompuIves
Copy link
Member

Hey! We have published a new update (0.1.0) that might fix Next.js. Could you give it a try?

@nalaso
Copy link
Author

nalaso commented Jan 9, 2025 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants