Skip to content

Commit

Permalink
wip: download of Worker script
Browse files Browse the repository at this point in the history
Workaround for handling multipart/form-data slicing off top and bottom boundaries.
- [] Need to prevent download in existing projects
- [] Duplicate the logic for JS files

multipart/formdata not supported currently in Undici nodejs/undici#974
  • Loading branch information
JacobMGEvans committed Aug 10, 2022
1 parent 9e632cd commit 1bad926
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 1 deletion.
39 changes: 39 additions & 0 deletions packages/wrangler/src/cfetch/internal.ts
Expand Up @@ -179,3 +179,42 @@ export async function fetchR2Objects(
);
}
}

/**
* This is a wrapper STOPGAP for getting the script which returns a raw text response.
* TODO: remove this once the API is fixed and utilize fetchResult instead. - JACOB
*/
export async function fetchDashboardScript(
resource: string,
bodyInit: RequestInit = {}
): Promise<string> {
await requireLoggedIn();
const auth = requireApiToken();
const headers = cloneHeaders(bodyInit.headers);
addAuthorizationHeaderIfUnspecified(headers, auth);
addUserAgent(headers);

const response = await fetch(`${getCloudflareAPIBaseURL()}${resource}`, {
...bodyInit,
headers,
});

if (!response.ok || !response.body) {
throw new Error(
`Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
);
}

const usesModules = response.headers
.get("content-type")
?.startsWith("multipart");

// Follow up on issue in Undici about multipart/form-data support & replace the workaround: https://github.com/nodejs/undici/issues/974
if (usesModules) {
const file = await response.text();

return file.split("\n").slice(4, -4).join("\n");
} else {
return response.text();
}
}
41 changes: 40 additions & 1 deletion packages/wrangler/src/init.ts
Expand Up @@ -5,12 +5,16 @@ import TOML from "@iarna/toml";
import { findUp } from "find-up";
import { version as wranglerVersion } from "../package.json";

import { fetchDashboardScript } from "./cfetch/internal";
import { readConfig } from "./config";
import { confirm, select } from "./dialogs";
import { initializeGit, isGitInstalled, isInsideGitRepo } from "./git-client";
import { logger } from "./logger";
import { getPackageManager } from "./package-manager";
import { parsePackageJSON, parseTOML, readFileSync } from "./parse";
import { requireAuth } from "./user";
import { CommandLineArgsError, printWranglerBanner } from "./index";
import type { ConfigPath } from "./index";

import type { Argv, ArgumentsCamelCase } from "yargs";

Expand All @@ -36,6 +40,11 @@ export async function initOptions(yargs: Argv) {
describe: 'Answer "yes" to any prompts for new projects',
type: "boolean",
alias: "y",
})
.option("from-dash", {
describe: "Use script from the dashboard editor",
type: "string",
hidden: true,
});
}

Expand Down Expand Up @@ -431,13 +440,43 @@ export async function initHandler(args: ArgumentsCamelCase<InitArgs>) {

return {};
}

// This is where I need to replace the Source script
const fromDashboard = args["from-dash"] as string;
if (isTypescriptProject) {
if (!fs.existsSync(path.join(creationDirectory, "./src/index.ts"))) {
const newWorkerFilename = path.relative(
process.cwd(),
path.join(creationDirectory, "./src/index.ts")
);
if (fromDashboard) {
const config = readConfig(args.config as ConfigPath, args);
const accountId = await requireAuth(config);
await mkdir(path.join(creationDirectory, "./src"), {
recursive: true,
});

const dashScript = await fetchDashboardScript(
`/accounts/${accountId}/workers/scripts/${fromDashboard}`,
{
method: "GET",
}
);

await writeFile(
path.join(creationDirectory, "./src/index.ts"),
dashScript
);

await writePackageJsonScriptsAndUpdateWranglerToml(
shouldWritePackageJsonScripts,
justCreatedWranglerToml,
pathToPackageJson,
"src/index.ts",
{}
);

return;
}

const newWorkerType = yesFlag
? "fetch"
Expand Down

0 comments on commit 1bad926

Please sign in to comment.