Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master' into dataconnect
Browse files Browse the repository at this point in the history
  • Loading branch information
fredzqm committed May 13, 2024
2 parents 8f8ac06 + a83161d commit 8238169
Show file tree
Hide file tree
Showing 20 changed files with 641 additions and 329 deletions.
9 changes: 9 additions & 0 deletions firebase-vscode/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# Change Log

## 0.2.0

- Fix Auth on IDX

## 0.1.9

- Fix "Add Data" for nonnull and custom keys
- Emulator Bump 1.1.17

## 0.1.8

- Update Extensions page Logo
Expand Down
3 changes: 3 additions & 0 deletions firebase-vscode/common/messaging/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@ export interface WebviewToExtensionParamsMap {

// Initialize "result" tab.
getDataConnectResults: void;

// execute terminal tasks
executeLogin: void;
}

export interface DataConnectResults {
Expand Down
4 changes: 2 additions & 2 deletions firebase-vscode/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 6 additions & 4 deletions firebase-vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"publisher": "firebase",
"icon": "./resources/firebase_logo.png",
"description": "VSCode Extension for Firebase",
"version": "0.1.8",
"version": "0.2.0",
"engines": {
"vscode": "^1.69.0"
},
Expand All @@ -13,7 +13,9 @@
"categories": [
"Other"
],
"extensionDependencies": ["graphql.vscode-graphql-syntax"],
"extensionDependencies": [
"graphql.vscode-graphql-syntax"
],
"activationEvents": [
"onStartupFinished",
"onLanguage:graphql",
Expand Down Expand Up @@ -55,12 +57,12 @@
"properties": {
"firebase.debug": {
"type": "boolean",
"default": false,
"default": true,
"description": "Enable writing debug-level messages to the file provided in firebase.debugLogPath (requires restart)"
},
"firebase.debugLogPath": {
"type": "string",
"default": "",
"default": "/tmp/firebase-plugin.log",
"description": "If firebase.debug is true, appends debug-level messages to the provided file (requires restart)"
},
"firebase.npmPath": {
Expand Down
38 changes: 3 additions & 35 deletions firebase-vscode/scripts/swap-pkg.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,10 @@ const { writeFileSync } = require("fs");
const path = require("path");
const pkg = require(path.join(__dirname, "../package.json"));

// Swaps package.json config as appropriate for packaging for
// Monospace or VSCE marketplace.

// TODO(chholland): Don't overwrite the real package.json file and
// create a generated one in dist/ - redo .vscodeignore to package
// dist/

let target = "vsce";

process.argv.forEach((arg) => {
if (arg === "vsce" || arg === "monospace") {
target = arg;
}
});

if (target === "vsce") {
delete pkg.extensionDependencies;
console.log(
"Removing google.monospace extensionDependency for VSCE packaging."
);
pkg.contributes.configuration.properties["firebase.debug"].default = false;
pkg.contributes.configuration.properties["firebase.debugLogPath"].default =
"";
console.log("Setting default debug log settings to off for VSCE packaging.");
} else if (target === "monospace") {
pkg.extensionDependencies = ["google.monospace"];
console.log(
"Adding google.monospace extensionDependency for Monospace packaging."
);
pkg.contributes.configuration.properties["firebase.debug"].default = true;
pkg.contributes.configuration.properties["firebase.debugLogPath"].default =
"/tmp/firebase-plugin.log";
console.log(
"Setting default debug log settings to on for Monospace packaging."
);
}
pkg.contributes.configuration.properties["firebase.debug"].default = true;
pkg.contributes.configuration.properties["firebase.debugLogPath"].default =
"/tmp/firebase-plugin.log";

writeFileSync(
path.join(__dirname, "../package.json"),
Expand Down
6 changes: 3 additions & 3 deletions firebase-vscode/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,9 @@ async function getServiceAccount() {
*/
async function requireAuthWrapper(showError: boolean = true): Promise<boolean> {
// Try to get global default from configstore. For some reason this is
// often overwritten when restarting the extension.
pluginLogger.debug("requireAuthWrapper");
let account = getGlobalDefaultAccount();
// often overwritten when restarting the extension.
if (!account) {
// If nothing in configstore top level, grab the first "additionalAccount"
const accounts = getAllAccounts();
Expand Down Expand Up @@ -153,7 +153,7 @@ async function requireAuthWrapper(showError: boolean = true): Promise<boolean> {
// "error". Usually set on user-triggered actions such as
// init hosting and deploy.
pluginLogger.error(
`requireAuth error: ${e.original?.message || e.message}`
`requireAuth error: ${e.original?.message || e.message}`,
);
vscode.window.showErrorMessage("Not logged in", {
modal: true,
Expand All @@ -164,7 +164,7 @@ async function requireAuthWrapper(showError: boolean = true): Promise<boolean> {
// but we should log it for debugging purposes.
pluginLogger.debug(
"requireAuth error output: ",
e.original?.message || e.message
e.original?.message || e.message,
);
}
return false;
Expand Down
42 changes: 8 additions & 34 deletions firebase-vscode/src/core/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@ import { FirebaseProjectMetadata } from "../types/project";
import { currentUser, isServiceAccount } from "./user";
import { listProjects } from "../cli";
import { pluginLogger } from "../logger-wrapper";
import { selectProjectInMonospace } from "../../../src/monospace";
import { currentOptions } from "../options";
import { globalSignal } from "../utils/globals";
import { firstWhereDefined } from "../utils/signal";

/** Available projects */
export const projects = globalSignal<Record<string, FirebaseProjectMetadata[]>>(
{}
{},
);

/** Currently selected project ID */
Expand All @@ -22,7 +21,7 @@ export const currentProjectId = globalSignal("");
const userScopedProjects = computed<FirebaseProjectMetadata[] | undefined>(
() => {
return projects.value[currentUser.value?.email ?? ""];
}
},
);

/** Gets the currently selected project, fallback to first default project in RC file */
Expand All @@ -41,7 +40,7 @@ export const currentProject = computed<FirebaseProjectMetadata | undefined>(
}

return userScopedProjects.value?.find((p) => p.projectId === wantProjectId);
}
},
);

export function registerProject(broker: ExtensionBrokerImpl): Disposable {
Expand Down Expand Up @@ -87,32 +86,7 @@ export function registerProject(broker: ExtensionBrokerImpl): Disposable {
const command = vscode.commands.registerCommand(
"firebase.selectProject",
async () => {
if (process.env.MONOSPACE_ENV) {
pluginLogger.debug(
"selectProject: found MONOSPACE_ENV, " +
"prompting user using external flow"
);
/**
* Monospace case: use Monospace flow
*/
const monospaceExtension =
vscode.extensions.getExtension("google.monospace");
process.env.MONOSPACE_DAEMON_PORT =
monospaceExtension.exports.getMonospaceDaemonPort();
try {
const projectId = await selectProjectInMonospace({
projectRoot: currentOptions.value.cwd,
project: undefined,
isVSCE: true,
});

if (projectId) {
currentProjectId.value = projectId;
}
} catch (e) {
pluginLogger.error(e);
}
} else if (isServiceAccount.value) {
if (isServiceAccount.value) {
return;
} else {
try {
Expand All @@ -124,11 +98,11 @@ export function registerProject(broker: ExtensionBrokerImpl): Disposable {
vscode.window.showErrorMessage(e.message);
}
}
}
},
);

const sub6 = broker.on("selectProject", () =>
vscode.commands.executeCommand("firebase.selectProject")
vscode.commands.executeCommand("firebase.selectProject"),
);

return vscode.Disposable.from(
Expand All @@ -138,7 +112,7 @@ export function registerProject(broker: ExtensionBrokerImpl): Disposable {
{ dispose: sub3 },
{ dispose: sub4 },
{ dispose: sub5 },
{ dispose: sub6 }
{ dispose: sub6 },
);
}

Expand All @@ -149,7 +123,7 @@ export function registerProject(broker: ExtensionBrokerImpl): Disposable {
*/
export async function _promptUserForProject(
projects: Thenable<FirebaseProjectMetadata[]>,
token?: vscode.CancellationToken
token?: vscode.CancellationToken,
): Promise<string | undefined> {
const items = projects.then((projects) => {
return projects.map((p) => ({
Expand Down
15 changes: 10 additions & 5 deletions firebase-vscode/src/core/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,16 @@ export const isServiceAccount = computed(() => {
return (currentUser.value as ServiceAccountUser)?.type === "service_account";
});

export async function checkLogin() {
const accounts = await getAccounts();
users.value = accounts.reduce(
(cumm, curr) => ({ ...cumm, [curr.user.email]: curr.user }),
{}
);
}

export function registerUser(broker: ExtensionBrokerImpl): Disposable {

const sub1 = effect(() => {
broker.send("notifyUsers", { users: Object.values(users.value) });
});
Expand All @@ -33,11 +42,7 @@ export function registerUser(broker: ExtensionBrokerImpl): Disposable {
});

const sub3 = broker.on("getInitialData", async () => {
const accounts = await getAccounts();
users.value = accounts.reduce(
(cumm, curr) => ({ ...cumm, [curr.user.email]: curr.user }),
{}
);
checkLogin();
});

const sub4 = broker.on("addUser", async () => {
Expand Down
49 changes: 26 additions & 23 deletions firebase-vscode/src/data-connect/ad-hoc-mutations.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import vscode, { Disposable } from "vscode";
import { DocumentNode, Kind, ObjectTypeDefinitionNode } from "graphql";
import { DocumentNode, GraphQLInputObjectType, GraphQLScalarType, Kind, ObjectTypeDefinitionNode, buildClientSchema, buildSchema } from "graphql";
import { checkIfFileExists, upsertFile } from "./file-utils";
import { DataConnectService } from "./service";

export function registerAdHoc(): Disposable {
export function registerAdHoc(dataConnectService: DataConnectService): Disposable {
const defaultScalarValues = {
Any: "{}",
AuthUID: '""',
Expand Down Expand Up @@ -122,7 +123,7 @@ query {
// generate content for the file
const preamble =
"# This is a file for you to write an un-named mutation. \n# Only one un-named mutation is allowed per file.";
const adhocMutation = generateMutation(ast);
const adhocMutation = await generateMutation(ast);
const content = [preamble, adhocMutation].join("\n");

const basePath = vscode.workspace.rootPath + "/dataconnect/";
Expand All @@ -149,33 +150,35 @@ query {
}
}

function generateMutation(ast: ObjectTypeDefinitionNode): string {
const name =
async function generateMutation(
ast: ObjectTypeDefinitionNode,
): Promise<string> {
const introspect = (await dataConnectService.introspect())?.data;
const schema = buildClientSchema(introspect);

const name = ast.name.value;
const lowerCaseName =
ast.name.value.charAt(0).toLowerCase() + ast.name.value.slice(1);
const dataName = `${name}_Data`;
const mutationDataType: GraphQLInputObjectType = schema.getTypeMap()[dataName] as GraphQLInputObjectType;

// build mutation as string
const functionSpacing = "\t";
const fieldSpacing = "\t\t";
const mutation = [];

mutation.push("mutation {"); // mutation header
mutation.push(`${functionSpacing}${name}_insert(data: {`); // insert function
for (const field of ast.fields) {
mutation.push(`${functionSpacing}${lowerCaseName}_insert(data: {`);
for (const [fieldName, field] of Object.entries(mutationDataType.getFields())) {
// necessary to avoid type error
let fieldType: any = field.type;
// We unwrap NonNullType to obtain the actual type
if (fieldType.kind === Kind.NON_NULL_TYPE) {
fieldType = fieldType.type;
}
let fieldTypeName: string = fieldType.name.value;
let fieldName: string = field.name.value;
let defaultValue = defaultScalarValues[fieldTypeName] as string;
if (!isDataConnectScalarType(fieldTypeName)) {
fieldTypeName += "Id";
fieldName += "Id";
defaultValue = '""';
const fieldtype: any = field.type;
// use all argument types that are of scalar, except x_expr
if (isDataConnectScalarType(fieldtype.name) && !field.name.includes("_expr")) {
const defaultValue = defaultScalarValues[fieldtype.name] || "";
mutation.push(
`${fieldSpacing}${fieldName}: ${defaultValue} # ${fieldtype.name}`,
); // field name + temp value + comment
}
mutation.push(
`${fieldSpacing}${fieldName}: ${defaultValue} # ${fieldTypeName}`,
); // field name + temp value + comment

}
mutation.push(`${functionSpacing}})`, "}"); // closing braces/paren
return mutation.join("\n");
Expand Down
4 changes: 3 additions & 1 deletion firebase-vscode/src/data-connect/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { runDataConnectCompiler } from "./core-compiler";
import { Result } from "../result";
import { runEmulatorIssuesStream } from "./emulator-stream";
import { LanguageClient } from "vscode-languageclient/node";
import { registerTerminalTasks } from "./terminal";

class CodeActionsProvider implements vscode.CodeActionProvider {
constructor(
Expand Down Expand Up @@ -220,9 +221,10 @@ export function registerFdc(
registerExecution(context, broker, fdcService, emulatorController),
registerExplorer(context, broker, fdcService),
registerFirebaseDataConnectView(context, broker, emulatorController),
registerAdHoc(),
registerAdHoc(fdcService),
registerConnectors(context, broker, fdcService),
registerFdcDeploy(broker),
registerTerminalTasks(broker),
operationCodeLensProvider,
vscode.languages.registerCodeLensProvider(
// **Hack**: For testing purposes, enable code lenses on all graphql files
Expand Down
Loading

0 comments on commit 8238169

Please sign in to comment.