From 23bbe7db7bc83c23fb6431376836a2005796bcbb Mon Sep 17 00:00:00 2001 From: Pavel Jbanov Date: Tue, 21 May 2024 15:19:36 -0400 Subject: [PATCH 1/2] A simple angular streaming client app with firebase hosting --- samples/js-firebase/.firebaserc | 1 + samples/js-firebase/.gitignore | 66 +++++++++++ samples/js-firebase/README.md | 17 +++ samples/js-firebase/firebase.json | 25 ++++ samples/js-firebase/functions/.gitignore | 10 ++ samples/js-firebase/functions/package.json | 37 ++++++ samples/js-firebase/functions/src/index.ts | 76 ++++++++++++ samples/js-firebase/functions/tsconfig.json | 17 +++ samples/js-firebase/my-app/.editorconfig | 16 +++ samples/js-firebase/my-app/.gitignore | 42 +++++++ samples/js-firebase/my-app/README.md | 27 +++++ samples/js-firebase/my-app/angular.json | 95 +++++++++++++++ samples/js-firebase/my-app/package.json | 38 ++++++ .../my-app/src/app/app.component.css | 0 .../my-app/src/app/app.component.html | 18 +++ .../my-app/src/app/app.component.spec.ts | 16 +++ .../my-app/src/app/app.component.ts | 43 +++++++ .../js-firebase/my-app/src/app/app.config.ts | 8 ++ .../js-firebase/my-app/src/app/app.routes.ts | 3 + .../js-firebase/my-app/src/assets/.gitkeep | 0 samples/js-firebase/my-app/src/index.html | 13 ++ samples/js-firebase/my-app/src/main.ts | 6 + samples/js-firebase/my-app/src/styles.css | 1 + samples/js-firebase/my-app/src/utils/flow.ts | 111 ++++++++++++++++++ samples/js-firebase/my-app/tsconfig.app.json | 14 +++ samples/js-firebase/my-app/tsconfig.json | 32 +++++ samples/js-firebase/my-app/tsconfig.spec.json | 14 +++ samples/js-firebase/package.json | 6 + 28 files changed, 752 insertions(+) create mode 100644 samples/js-firebase/.firebaserc create mode 100644 samples/js-firebase/.gitignore create mode 100644 samples/js-firebase/README.md create mode 100644 samples/js-firebase/firebase.json create mode 100644 samples/js-firebase/functions/.gitignore create mode 100644 samples/js-firebase/functions/package.json create mode 100644 samples/js-firebase/functions/src/index.ts create mode 100644 samples/js-firebase/functions/tsconfig.json create mode 100644 samples/js-firebase/my-app/.editorconfig create mode 100644 samples/js-firebase/my-app/.gitignore create mode 100644 samples/js-firebase/my-app/README.md create mode 100644 samples/js-firebase/my-app/angular.json create mode 100644 samples/js-firebase/my-app/package.json create mode 100644 samples/js-firebase/my-app/src/app/app.component.css create mode 100644 samples/js-firebase/my-app/src/app/app.component.html create mode 100644 samples/js-firebase/my-app/src/app/app.component.spec.ts create mode 100644 samples/js-firebase/my-app/src/app/app.component.ts create mode 100644 samples/js-firebase/my-app/src/app/app.config.ts create mode 100644 samples/js-firebase/my-app/src/app/app.routes.ts create mode 100644 samples/js-firebase/my-app/src/assets/.gitkeep create mode 100644 samples/js-firebase/my-app/src/index.html create mode 100644 samples/js-firebase/my-app/src/main.ts create mode 100644 samples/js-firebase/my-app/src/styles.css create mode 100644 samples/js-firebase/my-app/src/utils/flow.ts create mode 100644 samples/js-firebase/my-app/tsconfig.app.json create mode 100644 samples/js-firebase/my-app/tsconfig.json create mode 100644 samples/js-firebase/my-app/tsconfig.spec.json create mode 100644 samples/js-firebase/package.json diff --git a/samples/js-firebase/.firebaserc b/samples/js-firebase/.firebaserc new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/samples/js-firebase/.firebaserc @@ -0,0 +1 @@ +{} diff --git a/samples/js-firebase/.gitignore b/samples/js-firebase/.gitignore new file mode 100644 index 0000000000..dbb58ffbfa --- /dev/null +++ b/samples/js-firebase/.gitignore @@ -0,0 +1,66 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +firebase-debug.log* +firebase-debug.*.log* + +# Firebase cache +.firebase/ + +# Firebase config + +# Uncomment this if you'd like others to create their own Firebase project. +# For a team working on the same Firebase project(s), it is recommended to leave +# it commented so all members can deploy to the same project(s) in .firebaserc. +# .firebaserc + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env diff --git a/samples/js-firebase/README.md b/samples/js-firebase/README.md new file mode 100644 index 0000000000..5d6bfd18d9 --- /dev/null +++ b/samples/js-firebase/README.md @@ -0,0 +1,17 @@ +# Angular and Genkit streaming sample + +This is a simple UI for streaming RPG character generator. + +To build: + +```bash +npm run build +``` + +Run: + +```bash +npm run start -- --project YOUR_PROJECT_ID +``` + +Point your browser to http://127.0.0.1:5000 \ No newline at end of file diff --git a/samples/js-firebase/firebase.json b/samples/js-firebase/firebase.json new file mode 100644 index 0000000000..fb11cebe74 --- /dev/null +++ b/samples/js-firebase/firebase.json @@ -0,0 +1,25 @@ +{ + "functions": [ + { + "source": "functions", + "codebase": "default", + "predeploy": [ + "npm --prefix \"$RESOURCE_DIR\" run build" + ] + } + ], + "hosting": { + "public": "my-app/dist/my-app/browser", + "ignore": [ + "firebase.json", + "**/.*", + "**/node_modules/**" + ], + "rewrites": [ + { + "source": "**", + "destination": "/index.html" + } + ] + } +} diff --git a/samples/js-firebase/functions/.gitignore b/samples/js-firebase/functions/.gitignore new file mode 100644 index 0000000000..9be0f014f4 --- /dev/null +++ b/samples/js-firebase/functions/.gitignore @@ -0,0 +1,10 @@ +# Compiled JavaScript files +lib/**/*.js +lib/**/*.js.map + +# TypeScript v1 declaration files +typings/ + +# Node.js dependency directory +node_modules/ +*.local \ No newline at end of file diff --git a/samples/js-firebase/functions/package.json b/samples/js-firebase/functions/package.json new file mode 100644 index 0000000000..4a35e29d79 --- /dev/null +++ b/samples/js-firebase/functions/package.json @@ -0,0 +1,37 @@ +{ + "main": "lib/index.js", + "scripts": { + "start": "npm run shell", + "compile": "tsc", + "build": "tsc", + "build:clean": "rm -rf ./lib", + "build:watch": "tsc --watch", + "serve": "npm run build && firebase emulators:start --only functions", + "shell": "npm run build && firebase functions:shell", + "deploy": "firebase deploy --only functions", + "logs": "firebase functions:log" + }, + "name": "functions", + "engines": { + "node": "20" + }, + "dependencies": { + "@genkit-ai/ai": "^0.5.0", + "@genkit-ai/core": "^0.5.0", + "@genkit-ai/dotprompt": "^0.5.0", + "@genkit-ai/firebase": "^0.5.0", + "@genkit-ai/flow": "^0.5.0", + "@genkit-ai/vertexai": "^0.5.0", + "express": "^4.19.2", + "firebase-admin": "^12.1.0", + "firebase-functions": "^5.0.0", + "partial-json": "^0.1.7", + "zod": "^3.23.8" + }, + "devDependencies": { + "firebase-functions-test": "^3.1.0", + "genkit": "^0.5.0", + "typescript": "^4.9.5" + }, + "private": true +} diff --git a/samples/js-firebase/functions/src/index.ts b/samples/js-firebase/functions/src/index.ts new file mode 100644 index 0000000000..c41fe428c3 --- /dev/null +++ b/samples/js-firebase/functions/src/index.ts @@ -0,0 +1,76 @@ +import { generateStream } from '@genkit-ai/ai'; +import { configureGenkit } from '@genkit-ai/core'; +import { firebase } from '@genkit-ai/firebase'; +import { noAuth, onFlow } from '@genkit-ai/firebase/functions'; +import { geminiPro, vertexAI } from '@genkit-ai/vertexai'; +import { Allow, parse } from 'partial-json'; +import * as z from 'zod'; + +configureGenkit({ + plugins: [firebase(), vertexAI({ location: 'us-central1' })], + logLevel: 'debug', + enableTracingAndMetrics: true, +}); + +const GameCharactersSchema = z.object({ + characters: z + .array( + z + .object({ + name: z.string().describe('Name of a character'), + abilities: z + .array(z.string()) + .describe('Various abilities (strength, magic, archery, etc.)'), + }) + .describe('Game character') + ) + .describe('Characters'), +}); + +export const streamCharacters = onFlow( + { + name: 'streamCharacters', + inputSchema: z.number(), + outputSchema: z.string(), + streamSchema: GameCharactersSchema, + authPolicy: noAuth(), + httpsOptions: { + cors: '*' + } + }, + async (count, streamingCallback) => { + if (!streamingCallback) { + throw new Error('this flow only works in streaming mode'); + } + + const { response, stream } = await generateStream({ + model: geminiPro, + output: { + schema: GameCharactersSchema, + }, + config: { + temperature: 1, + }, + prompt: `Respond as JSON only. Generate ${count} different RPG game characters.`, + }); + + let buffer = ''; + for await (const chunk of stream()) { + buffer += chunk.content[0].text!; + if (buffer.length > 10) { + streamingCallback(parse(maybeStripMarkdown(buffer), Allow.ALL)); + } + } + + return (await response()).text(); + } +); + +const markdownRegex = /^\s*(```json)?((.|\n)*?)(```)?\s*$/i; +function maybeStripMarkdown(withMarkdown: string) { + const mdMatch = markdownRegex.exec(withMarkdown); + if (!mdMatch) { + return withMarkdown; + } + return mdMatch[2]; +} diff --git a/samples/js-firebase/functions/tsconfig.json b/samples/js-firebase/functions/tsconfig.json new file mode 100644 index 0000000000..70f95eb3f5 --- /dev/null +++ b/samples/js-firebase/functions/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compileOnSave": true, + "include": [ + "src" + ], + "compilerOptions": { + "module": "commonjs", + "noImplicitReturns": true, + "outDir": "lib", + "sourceMap": true, + "strict": true, + "target": "es2017", + "skipLibCheck": true, + "esModuleInterop": true, + "noUnusedLocals": true + } +} \ No newline at end of file diff --git a/samples/js-firebase/my-app/.editorconfig b/samples/js-firebase/my-app/.editorconfig new file mode 100644 index 0000000000..59d9a3a3e7 --- /dev/null +++ b/samples/js-firebase/my-app/.editorconfig @@ -0,0 +1,16 @@ +# Editor configuration, see https://editorconfig.org +root = true + +[*] +charset = utf-8 +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.ts] +quote_type = single + +[*.md] +max_line_length = off +trim_trailing_whitespace = false diff --git a/samples/js-firebase/my-app/.gitignore b/samples/js-firebase/my-app/.gitignore new file mode 100644 index 0000000000..cc7b141350 --- /dev/null +++ b/samples/js-firebase/my-app/.gitignore @@ -0,0 +1,42 @@ +# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files. + +# Compiled output +/dist +/tmp +/out-tsc +/bazel-out + +# Node +/node_modules +npm-debug.log +yarn-error.log + +# IDEs and editors +.idea/ +.project +.classpath +.c9/ +*.launch +.settings/ +*.sublime-workspace + +# Visual Studio Code +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +.history/* + +# Miscellaneous +/.angular/cache +.sass-cache/ +/connect.lock +/coverage +/libpeerconnection.log +testem.log +/typings + +# System files +.DS_Store +Thumbs.db diff --git a/samples/js-firebase/my-app/README.md b/samples/js-firebase/my-app/README.md new file mode 100644 index 0000000000..fe2d6aea2c --- /dev/null +++ b/samples/js-firebase/my-app/README.md @@ -0,0 +1,27 @@ +# MyApp + +This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 17.3.7. + +## Development server + +Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files. + +## Code scaffolding + +Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. + +## Build + +Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. + +## Running unit tests + +Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). + +## Running end-to-end tests + +Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities. + +## Further help + +To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page. diff --git a/samples/js-firebase/my-app/angular.json b/samples/js-firebase/my-app/angular.json new file mode 100644 index 0000000000..f7dcd3f3a0 --- /dev/null +++ b/samples/js-firebase/my-app/angular.json @@ -0,0 +1,95 @@ +{ + "$schema": "./node_modules/@angular/cli/lib/config/schema.json", + "version": 1, + "newProjectRoot": "projects", + "projects": { + "my-app": { + "projectType": "application", + "schematics": {}, + "root": "", + "sourceRoot": "src", + "prefix": "app", + "architect": { + "build": { + "builder": "@angular-devkit/build-angular:application", + "options": { + "outputPath": "dist/my-app", + "index": "src/index.html", + "browser": "src/main.ts", + "polyfills": [ + "zone.js" + ], + "tsConfig": "tsconfig.app.json", + "assets": [ + "src/favicon.ico", + "src/assets" + ], + "styles": [ + "src/styles.css" + ], + "scripts": [] + }, + "configurations": { + "production": { + "budgets": [ + { + "type": "initial", + "maximumWarning": "500kb", + "maximumError": "1mb" + }, + { + "type": "anyComponentStyle", + "maximumWarning": "2kb", + "maximumError": "4kb" + } + ], + "outputHashing": "all" + }, + "development": { + "optimization": false, + "extractLicenses": false, + "sourceMap": true + } + }, + "defaultConfiguration": "production" + }, + "serve": { + "builder": "@angular-devkit/build-angular:dev-server", + "configurations": { + "production": { + "buildTarget": "my-app:build:production" + }, + "development": { + "buildTarget": "my-app:build:development" + } + }, + "defaultConfiguration": "development" + }, + "extract-i18n": { + "builder": "@angular-devkit/build-angular:extract-i18n", + "options": { + "buildTarget": "my-app:build" + } + }, + "test": { + "builder": "@angular-devkit/build-angular:karma", + "options": { + "polyfills": [ + "zone.js", + "zone.js/testing" + ], + "tsConfig": "tsconfig.spec.json", + "assets": [ + "src/favicon.ico", + "src/assets" + ], + "styles": [ + "src/styles.css" + ], + "scripts": [] + } + } + } + } + } +} diff --git a/samples/js-firebase/my-app/package.json b/samples/js-firebase/my-app/package.json new file mode 100644 index 0000000000..984b9d70cd --- /dev/null +++ b/samples/js-firebase/my-app/package.json @@ -0,0 +1,38 @@ +{ + "name": "my-app", + "version": "0.0.0", + "scripts": { + "ng": "ng", + "start": "ng serve", + "build": "ng build", + "watch": "ng build --watch --configuration development", + "test": "ng test" + }, + "private": true, + "dependencies": { + "@angular/animations": "^17.3.0", + "@angular/common": "^17.3.0", + "@angular/compiler": "^17.3.0", + "@angular/core": "^17.3.0", + "@angular/forms": "^17.3.0", + "@angular/platform-browser": "^17.3.0", + "@angular/platform-browser-dynamic": "^17.3.0", + "@angular/router": "^17.3.0", + "rxjs": "~7.8.0", + "tslib": "^2.3.0", + "zone.js": "~0.14.3" + }, + "devDependencies": { + "@angular-devkit/build-angular": "^17.3.7", + "@angular/cli": "^17.3.7", + "@angular/compiler-cli": "^17.3.0", + "@types/jasmine": "~5.1.0", + "jasmine-core": "~5.1.0", + "karma": "~6.4.0", + "karma-chrome-launcher": "~3.2.0", + "karma-coverage": "~2.2.0", + "karma-jasmine": "~5.1.0", + "karma-jasmine-html-reporter": "~2.1.0", + "typescript": "~5.4.2" + } +} diff --git a/samples/js-firebase/my-app/src/app/app.component.css b/samples/js-firebase/my-app/src/app/app.component.css new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/js-firebase/my-app/src/app/app.component.html b/samples/js-firebase/my-app/src/app/app.component.html new file mode 100644 index 0000000000..49a2db7e7b --- /dev/null +++ b/samples/js-firebase/my-app/src/app/app.component.html @@ -0,0 +1,18 @@ +

RPG Character Generator

+Generator URL:

+How many chatacters do you need? + +
+ Loading... +
+
+ {{error}} +
+
+
+ {{character.name}} +
    +
  • {{ability}}
  • +
+
+
\ No newline at end of file diff --git a/samples/js-firebase/my-app/src/app/app.component.spec.ts b/samples/js-firebase/my-app/src/app/app.component.spec.ts new file mode 100644 index 0000000000..7cd488c94e --- /dev/null +++ b/samples/js-firebase/my-app/src/app/app.component.spec.ts @@ -0,0 +1,16 @@ +import { TestBed } from '@angular/core/testing'; +import { AppComponent } from './app.component'; + +describe('AppComponent', () => { + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [AppComponent], + }).compileComponents(); + }); + + it('should create the app', () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.componentInstance; + expect(app).toBeTruthy(); + }); +}); diff --git a/samples/js-firebase/my-app/src/app/app.component.ts b/samples/js-firebase/my-app/src/app/app.component.ts new file mode 100644 index 0000000000..ae4bb33481 --- /dev/null +++ b/samples/js-firebase/my-app/src/app/app.component.ts @@ -0,0 +1,43 @@ +import { Component } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { streamFlow } from '../utils/flow'; +import { CommonModule } from '@angular/common'; + +@Component({ + selector: 'app-root', + standalone: true, + imports: [FormsModule, CommonModule], + templateUrl: './app.component.html', + styleUrl: './app.component.css' +}) +export class AppComponent { + count: string = '3'; + url: string = 'http://127.0.0.1:5001/YOUR-PROJECT-ID/us-central1/streamCharacters'; + characters: any = undefined; + error?: string = undefined; + loading: boolean = false; + + async callFlow() { + this.characters = undefined; + this.error = undefined; + this.loading = true; + try { + const response = streamFlow({ + url: this.url, + payload: parseInt(this.count), + }); + for await (const chunk of response.stream()) { + this.characters = chunk; + } + console.log("streamConsumer done", await response.output()); + this.loading = false; + } catch(e) { + this.loading = false; + if ((e as any).cause) { + this.error = `${(e as any).cause}`; + } else { + this.error = `${e}`; + } + } + } +} diff --git a/samples/js-firebase/my-app/src/app/app.config.ts b/samples/js-firebase/my-app/src/app/app.config.ts new file mode 100644 index 0000000000..6c6ef6035f --- /dev/null +++ b/samples/js-firebase/my-app/src/app/app.config.ts @@ -0,0 +1,8 @@ +import { ApplicationConfig } from '@angular/core'; +import { provideRouter } from '@angular/router'; + +import { routes } from './app.routes'; + +export const appConfig: ApplicationConfig = { + providers: [provideRouter(routes)] +}; diff --git a/samples/js-firebase/my-app/src/app/app.routes.ts b/samples/js-firebase/my-app/src/app/app.routes.ts new file mode 100644 index 0000000000..dc39edb5f2 --- /dev/null +++ b/samples/js-firebase/my-app/src/app/app.routes.ts @@ -0,0 +1,3 @@ +import { Routes } from '@angular/router'; + +export const routes: Routes = []; diff --git a/samples/js-firebase/my-app/src/assets/.gitkeep b/samples/js-firebase/my-app/src/assets/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/js-firebase/my-app/src/index.html b/samples/js-firebase/my-app/src/index.html new file mode 100644 index 0000000000..7fa8cd90cc --- /dev/null +++ b/samples/js-firebase/my-app/src/index.html @@ -0,0 +1,13 @@ + + + + + MyApp + + + + + + + + diff --git a/samples/js-firebase/my-app/src/main.ts b/samples/js-firebase/my-app/src/main.ts new file mode 100644 index 0000000000..35b00f3463 --- /dev/null +++ b/samples/js-firebase/my-app/src/main.ts @@ -0,0 +1,6 @@ +import { bootstrapApplication } from '@angular/platform-browser'; +import { appConfig } from './app/app.config'; +import { AppComponent } from './app/app.component'; + +bootstrapApplication(AppComponent, appConfig) + .catch((err) => console.error(err)); diff --git a/samples/js-firebase/my-app/src/styles.css b/samples/js-firebase/my-app/src/styles.css new file mode 100644 index 0000000000..90d4ee0072 --- /dev/null +++ b/samples/js-firebase/my-app/src/styles.css @@ -0,0 +1 @@ +/* You can add global styles to this file, and also import other style files */ diff --git a/samples/js-firebase/my-app/src/utils/flow.ts b/samples/js-firebase/my-app/src/utils/flow.ts new file mode 100644 index 0000000000..45103ccc66 --- /dev/null +++ b/samples/js-firebase/my-app/src/utils/flow.ts @@ -0,0 +1,111 @@ +const __flowStreamDelimiter = '\n'; + +export function streamFlow({ + url, + payload, + headers, +}: { + url: string; + payload: any; + headers?: Record; +}) { + let chunkStreamController: ReadableStreamDefaultController | undefined = + undefined; + const chunkStream = new ReadableStream({ + start(controller) { + chunkStreamController = controller; + }, + pull() {}, + cancel() {}, + }); + + const operationPromise = __flowRunEnvelope({ + url, + payload, + streamingCallback: (c) => { + chunkStreamController?.enqueue(c); + }, + headers, + }); + operationPromise.then((o) => { + chunkStreamController?.close(); + return o; + }); + + return { + output() { + return operationPromise.then((op) => { + if (!op.done) { + throw new Error(`flow ${op.name} did not finish execution`); + } + if (op.result?.error) { + throw new Error(op.name, op.result?.error + op.result?.stacktrace); + } + return op.result?.response; + }); + }, + async *stream() { + const reader = chunkStream.getReader(); + while (true) { + const chunk = await reader.read(); + if (chunk.value) { + yield chunk.value; + } + if (chunk.done) { + break; + } + } + return await operationPromise; + }, + }; +} + +async function __flowRunEnvelope({ + url, + payload, + streamingCallback, + headers, +}: { + url: string; + payload: any; + streamingCallback: (chunk: any) => void; + headers?: Record; +}) { + let response; + response = await fetch(url + '?stream=true', { + method: 'POST', + body: JSON.stringify({ + data: payload, + }), + headers: { + 'Content-Type': 'application/json', + ...headers, + }, + }); + if (!response.body) { + throw new Error('Response body is empty'); + } + var reader = response.body.getReader(); + var decoder = new TextDecoder(); + + let buffer = ''; + while (true) { + const result = await reader.read(); + const decodedValue = decoder.decode(result.value); + if (decodedValue) { + buffer += decodedValue; + } + // If buffer includes the delimiter that means we are still recieving chunks. + while (buffer.includes(__flowStreamDelimiter)) { + streamingCallback( + JSON.parse(buffer.substring(0, buffer.indexOf(__flowStreamDelimiter))) + ); + buffer = buffer.substring( + buffer.indexOf(__flowStreamDelimiter) + __flowStreamDelimiter.length + ); + } + if (result.done) { + return JSON.parse(buffer); + } + } +} diff --git a/samples/js-firebase/my-app/tsconfig.app.json b/samples/js-firebase/my-app/tsconfig.app.json new file mode 100644 index 0000000000..374cc9d294 --- /dev/null +++ b/samples/js-firebase/my-app/tsconfig.app.json @@ -0,0 +1,14 @@ +/* To learn more about this file see: https://angular.io/config/tsconfig. */ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "./out-tsc/app", + "types": [] + }, + "files": [ + "src/main.ts" + ], + "include": [ + "src/**/*.d.ts" + ] +} diff --git a/samples/js-firebase/my-app/tsconfig.json b/samples/js-firebase/my-app/tsconfig.json new file mode 100644 index 0000000000..eb49734a43 --- /dev/null +++ b/samples/js-firebase/my-app/tsconfig.json @@ -0,0 +1,32 @@ +/* To learn more about this file see: https://angular.io/config/tsconfig. */ +{ + "compileOnSave": false, + "compilerOptions": { + "outDir": "./dist/out-tsc", + "strict": true, + "noImplicitOverride": true, + "noPropertyAccessFromIndexSignature": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "skipLibCheck": true, + "esModuleInterop": true, + "sourceMap": true, + "declaration": false, + "experimentalDecorators": true, + "moduleResolution": "node", + "importHelpers": true, + "target": "ES2022", + "module": "ES2022", + "useDefineForClassFields": false, + "lib": [ + "ES2022", + "dom" + ] + }, + "angularCompilerOptions": { + "enableI18nLegacyMessageIdFormat": false, + "strictInjectionParameters": true, + "strictInputAccessModifiers": true, + "strictTemplates": true + } +} diff --git a/samples/js-firebase/my-app/tsconfig.spec.json b/samples/js-firebase/my-app/tsconfig.spec.json new file mode 100644 index 0000000000..be7e9da76f --- /dev/null +++ b/samples/js-firebase/my-app/tsconfig.spec.json @@ -0,0 +1,14 @@ +/* To learn more about this file see: https://angular.io/config/tsconfig. */ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "./out-tsc/spec", + "types": [ + "jasmine" + ] + }, + "include": [ + "src/**/*.spec.ts", + "src/**/*.d.ts" + ] +} diff --git a/samples/js-firebase/package.json b/samples/js-firebase/package.json new file mode 100644 index 0000000000..b2e290c898 --- /dev/null +++ b/samples/js-firebase/package.json @@ -0,0 +1,6 @@ +{ + "scripts": { + "build": "cd functions && npm i && npm run build && cd .. && cd my-app && npm i && npm run build", + "start": "firebase emulators:start" + } +} From adeaad771d76603c4c5d300ca6884a9612b6b1c0 Mon Sep 17 00:00:00 2001 From: Pavel Jbanov Date: Tue, 21 May 2024 15:26:47 -0400 Subject: [PATCH 2/2] format --- samples/js-firebase/README.md | 2 +- samples/js-firebase/firebase.json | 10 ++---- samples/js-firebase/functions/src/index.ts | 20 +++++++++-- samples/js-firebase/functions/tsconfig.json | 6 ++-- samples/js-firebase/my-app/angular.json | 27 ++++---------- .../my-app/src/app/app.component.html | 34 +++++++++++++----- .../my-app/src/app/app.component.spec.ts | 16 +++++++++ .../my-app/src/app/app.component.ts | 27 +++++++++++--- .../js-firebase/my-app/src/app/app.config.ts | 18 +++++++++- .../js-firebase/my-app/src/app/app.routes.ts | 16 +++++++++ samples/js-firebase/my-app/src/index.html | 36 +++++++++++++------ samples/js-firebase/my-app/src/main.ts | 23 ++++++++++-- samples/js-firebase/my-app/src/utils/flow.ts | 16 +++++++++ samples/js-firebase/my-app/tsconfig.app.json | 8 ++--- samples/js-firebase/my-app/tsconfig.json | 5 +-- samples/js-firebase/my-app/tsconfig.spec.json | 9 ++--- 16 files changed, 192 insertions(+), 81 deletions(-) diff --git a/samples/js-firebase/README.md b/samples/js-firebase/README.md index 5d6bfd18d9..1231ce451c 100644 --- a/samples/js-firebase/README.md +++ b/samples/js-firebase/README.md @@ -14,4 +14,4 @@ Run: npm run start -- --project YOUR_PROJECT_ID ``` -Point your browser to http://127.0.0.1:5000 \ No newline at end of file +Point your browser to http://127.0.0.1:5000 diff --git a/samples/js-firebase/firebase.json b/samples/js-firebase/firebase.json index fb11cebe74..b0f342dc83 100644 --- a/samples/js-firebase/firebase.json +++ b/samples/js-firebase/firebase.json @@ -3,18 +3,12 @@ { "source": "functions", "codebase": "default", - "predeploy": [ - "npm --prefix \"$RESOURCE_DIR\" run build" - ] + "predeploy": ["npm --prefix \"$RESOURCE_DIR\" run build"] } ], "hosting": { "public": "my-app/dist/my-app/browser", - "ignore": [ - "firebase.json", - "**/.*", - "**/node_modules/**" - ], + "ignore": ["firebase.json", "**/.*", "**/node_modules/**"], "rewrites": [ { "source": "**", diff --git a/samples/js-firebase/functions/src/index.ts b/samples/js-firebase/functions/src/index.ts index c41fe428c3..baf3cd2052 100644 --- a/samples/js-firebase/functions/src/index.ts +++ b/samples/js-firebase/functions/src/index.ts @@ -1,3 +1,19 @@ +/** + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + import { generateStream } from '@genkit-ai/ai'; import { configureGenkit } from '@genkit-ai/core'; import { firebase } from '@genkit-ai/firebase'; @@ -35,8 +51,8 @@ export const streamCharacters = onFlow( streamSchema: GameCharactersSchema, authPolicy: noAuth(), httpsOptions: { - cors: '*' - } + cors: '*', + }, }, async (count, streamingCallback) => { if (!streamingCallback) { diff --git a/samples/js-firebase/functions/tsconfig.json b/samples/js-firebase/functions/tsconfig.json index 70f95eb3f5..c927bfd28f 100644 --- a/samples/js-firebase/functions/tsconfig.json +++ b/samples/js-firebase/functions/tsconfig.json @@ -1,8 +1,6 @@ { "compileOnSave": true, - "include": [ - "src" - ], + "include": ["src"], "compilerOptions": { "module": "commonjs", "noImplicitReturns": true, @@ -14,4 +12,4 @@ "esModuleInterop": true, "noUnusedLocals": true } -} \ No newline at end of file +} diff --git a/samples/js-firebase/my-app/angular.json b/samples/js-firebase/my-app/angular.json index f7dcd3f3a0..d5c6ba1b18 100644 --- a/samples/js-firebase/my-app/angular.json +++ b/samples/js-firebase/my-app/angular.json @@ -16,17 +16,10 @@ "outputPath": "dist/my-app", "index": "src/index.html", "browser": "src/main.ts", - "polyfills": [ - "zone.js" - ], + "polyfills": ["zone.js"], "tsConfig": "tsconfig.app.json", - "assets": [ - "src/favicon.ico", - "src/assets" - ], - "styles": [ - "src/styles.css" - ], + "assets": ["src/favicon.ico", "src/assets"], + "styles": ["src/styles.css"], "scripts": [] }, "configurations": { @@ -74,18 +67,10 @@ "test": { "builder": "@angular-devkit/build-angular:karma", "options": { - "polyfills": [ - "zone.js", - "zone.js/testing" - ], + "polyfills": ["zone.js", "zone.js/testing"], "tsConfig": "tsconfig.spec.json", - "assets": [ - "src/favicon.ico", - "src/assets" - ], - "styles": [ - "src/styles.css" - ], + "assets": ["src/favicon.ico", "src/assets"], + "styles": ["src/styles.css"], "scripts": [] } } diff --git a/samples/js-firebase/my-app/src/app/app.component.html b/samples/js-firebase/my-app/src/app/app.component.html index 49a2db7e7b..17d1020388 100644 --- a/samples/js-firebase/my-app/src/app/app.component.html +++ b/samples/js-firebase/my-app/src/app/app.component.html @@ -1,18 +1,34 @@ + +

RPG Character Generator

-Generator URL:

-How many chatacters do you need? +Generator URL: +

+How many chatacters do you need? + -
- Loading... -
+
Loading...
- {{error}} + {{ error }}
- {{character.name}} + {{ character.name }}
    -
  • {{ability}}
  • +
  • {{ ability }}
-
\ No newline at end of file + diff --git a/samples/js-firebase/my-app/src/app/app.component.spec.ts b/samples/js-firebase/my-app/src/app/app.component.spec.ts index 7cd488c94e..481ebedf90 100644 --- a/samples/js-firebase/my-app/src/app/app.component.spec.ts +++ b/samples/js-firebase/my-app/src/app/app.component.spec.ts @@ -1,3 +1,19 @@ +/** + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + import { TestBed } from '@angular/core/testing'; import { AppComponent } from './app.component'; diff --git a/samples/js-firebase/my-app/src/app/app.component.ts b/samples/js-firebase/my-app/src/app/app.component.ts index ae4bb33481..043773752f 100644 --- a/samples/js-firebase/my-app/src/app/app.component.ts +++ b/samples/js-firebase/my-app/src/app/app.component.ts @@ -1,18 +1,35 @@ +/** + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CommonModule } from '@angular/common'; import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { streamFlow } from '../utils/flow'; -import { CommonModule } from '@angular/common'; @Component({ selector: 'app-root', standalone: true, imports: [FormsModule, CommonModule], templateUrl: './app.component.html', - styleUrl: './app.component.css' + styleUrl: './app.component.css', }) export class AppComponent { count: string = '3'; - url: string = 'http://127.0.0.1:5001/YOUR-PROJECT-ID/us-central1/streamCharacters'; + url: string = + 'http://127.0.0.1:5001/YOUR-PROJECT-ID/us-central1/streamCharacters'; characters: any = undefined; error?: string = undefined; loading: boolean = false; @@ -29,9 +46,9 @@ export class AppComponent { for await (const chunk of response.stream()) { this.characters = chunk; } - console.log("streamConsumer done", await response.output()); + console.log('streamConsumer done', await response.output()); this.loading = false; - } catch(e) { + } catch (e) { this.loading = false; if ((e as any).cause) { this.error = `${(e as any).cause}`; diff --git a/samples/js-firebase/my-app/src/app/app.config.ts b/samples/js-firebase/my-app/src/app/app.config.ts index 6c6ef6035f..8dbbb7f8bf 100644 --- a/samples/js-firebase/my-app/src/app/app.config.ts +++ b/samples/js-firebase/my-app/src/app/app.config.ts @@ -1,8 +1,24 @@ +/** + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + import { ApplicationConfig } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { - providers: [provideRouter(routes)] + providers: [provideRouter(routes)], }; diff --git a/samples/js-firebase/my-app/src/app/app.routes.ts b/samples/js-firebase/my-app/src/app/app.routes.ts index dc39edb5f2..a29a0f3d08 100644 --- a/samples/js-firebase/my-app/src/app/app.routes.ts +++ b/samples/js-firebase/my-app/src/app/app.routes.ts @@ -1,3 +1,19 @@ +/** + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + import { Routes } from '@angular/router'; export const routes: Routes = []; diff --git a/samples/js-firebase/my-app/src/index.html b/samples/js-firebase/my-app/src/index.html index 7fa8cd90cc..f5ada95b84 100644 --- a/samples/js-firebase/my-app/src/index.html +++ b/samples/js-firebase/my-app/src/index.html @@ -1,13 +1,29 @@ + + - - - MyApp - - - - - - - + + + MyApp + + + + + + + diff --git a/samples/js-firebase/my-app/src/main.ts b/samples/js-firebase/my-app/src/main.ts index 35b00f3463..b1be530a21 100644 --- a/samples/js-firebase/my-app/src/main.ts +++ b/samples/js-firebase/my-app/src/main.ts @@ -1,6 +1,23 @@ +/** + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + import { bootstrapApplication } from '@angular/platform-browser'; -import { appConfig } from './app/app.config'; import { AppComponent } from './app/app.component'; +import { appConfig } from './app/app.config'; -bootstrapApplication(AppComponent, appConfig) - .catch((err) => console.error(err)); +bootstrapApplication(AppComponent, appConfig).catch((err) => + console.error(err) +); diff --git a/samples/js-firebase/my-app/src/utils/flow.ts b/samples/js-firebase/my-app/src/utils/flow.ts index 45103ccc66..0e2ca92eac 100644 --- a/samples/js-firebase/my-app/src/utils/flow.ts +++ b/samples/js-firebase/my-app/src/utils/flow.ts @@ -1,3 +1,19 @@ +/** + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + const __flowStreamDelimiter = '\n'; export function streamFlow({ diff --git a/samples/js-firebase/my-app/tsconfig.app.json b/samples/js-firebase/my-app/tsconfig.app.json index 374cc9d294..84f1f992d2 100644 --- a/samples/js-firebase/my-app/tsconfig.app.json +++ b/samples/js-firebase/my-app/tsconfig.app.json @@ -5,10 +5,6 @@ "outDir": "./out-tsc/app", "types": [] }, - "files": [ - "src/main.ts" - ], - "include": [ - "src/**/*.d.ts" - ] + "files": ["src/main.ts"], + "include": ["src/**/*.d.ts"] } diff --git a/samples/js-firebase/my-app/tsconfig.json b/samples/js-firebase/my-app/tsconfig.json index eb49734a43..67d2944378 100644 --- a/samples/js-firebase/my-app/tsconfig.json +++ b/samples/js-firebase/my-app/tsconfig.json @@ -18,10 +18,7 @@ "target": "ES2022", "module": "ES2022", "useDefineForClassFields": false, - "lib": [ - "ES2022", - "dom" - ] + "lib": ["ES2022", "dom"] }, "angularCompilerOptions": { "enableI18nLegacyMessageIdFormat": false, diff --git a/samples/js-firebase/my-app/tsconfig.spec.json b/samples/js-firebase/my-app/tsconfig.spec.json index be7e9da76f..47e3dd7551 100644 --- a/samples/js-firebase/my-app/tsconfig.spec.json +++ b/samples/js-firebase/my-app/tsconfig.spec.json @@ -3,12 +3,7 @@ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", - "types": [ - "jasmine" - ] + "types": ["jasmine"] }, - "include": [ - "src/**/*.spec.ts", - "src/**/*.d.ts" - ] + "include": ["src/**/*.spec.ts", "src/**/*.d.ts"] }