repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
sgsonu/covid-vaccine-distribution
services/server/src/models/getPatientTrend/index.ts
import { Brackets, getConnection } from "typeorm"; import { User } from "../../entity/User"; interface PatientTrend { count: number; isVaccinated: boolean; vaccinationDate: string; } export const getPatientTrend = async ( lastNumDays?: number, nextNumDays?: number ): Promise<PatientTrend[]> => { const dbConnection = getConnection(); try { let query = dbConnection .getRepository(User) .createQueryBuilder() .select(`COUNT(email) AS count`) .addSelect(`"isVaccinated"`) .addSelect(`"vaccinationDate"`) .where(`"isRoot" = false`) .andWhere(`"isSuperUser" = false`) .andWhere(`"isAdmin" = false`) .andWhere(`"adminEmail" IS NOT NULL`) .andWhere(`"vaccinationTimeSlot" IS NOT NULL`); if (lastNumDays && nextNumDays) { query = query.andWhere( new Brackets((qb) => qb .where( `TO_DATE(:currentDate, 'Dy Mon DD YYYY') - TO_DATE("vaccinationDate", 'Dy Mon DD YYYY') BETWEEN 0 AND :lastNumDays`, { currentDate: new Date().toDateString(), lastNumDays } ) .orWhere( `TO_DATE("vaccinationDate", 'Dy Mon DD YYYY') - TO_DATE(:currentDate, 'Dy Mon DD YYYY') BETWEEN 0 AND :nextNumDays`, { currentDate: new Date().toDateString(), nextNumDays } ) ) ); } else if (lastNumDays) { query = query.andWhere( `TO_DATE(:currentDate, 'Dy Mon DD YYYY') - TO_DATE("vaccinationDate", 'Dy Mon DD YYYY') <= :lastNumDays`, { currentDate: new Date().toDateString(), lastNumDays } ); } else if (nextNumDays) { query = query.andWhere( `TO_DATE("vaccinationDate", 'Dy Mon DD YYYY') - TO_DATE(:currentDate, 'Dy Mon DD YYYY') <= :nextNumDays`, { currentDate: new Date().toDateString(), nextNumDays } ); } const result: PatientTrend[] = await query .groupBy(`"isVaccinated"`) .addGroupBy(`"vaccinationDate"`) .orderBy(`TO_DATE("vaccinationDate", 'Dy Mon DD YYYY')`) .getRawMany(); return result; } catch (error) { throw new Error(error); } };
sgsonu/covid-vaccine-distribution
services/server/src/routers/user/index.ts
import { Router } from "express"; import { addProfileRouter } from "./addProfile"; export const userRouter = Router(); userRouter.use("/patient_profile", addProfileRouter);
sgsonu/covid-vaccine-distribution
services/server/src/models/utils/sendMail/index.ts
<gh_stars>0 import { createTransport } from "nodemailer"; export interface EmailProps { to: string; html: string; subject: string; } export const sendMail = async ({ to, html, subject }: EmailProps) => { const transporter = createTransport({ service: process.env.SMTP_SERVICE, host: process.env.SMTP_HOST!, auth: { user: process.env.SMTP_USER!, pass: <PASSWORD>!, }, ignoreTLS: Boolean(process.env.SMTP_IGNORE_TLS), }); await transporter.sendMail({ from: process.env.SMTP_USER!, to, html, subject, }); };
sgsonu/covid-vaccine-distribution
services/server/src/models/getAdmins/index.ts
import { Point } from "geojson"; import { getConnection } from "typeorm"; import { User } from "../../entity/User"; interface AdminType { email: string; location: Point; firstName: string; lastName?: string; } export const getAdmins = async (): Promise<AdminType[]> => { const dbConnection = getConnection(); try { const admins = await dbConnection .getRepository(User) .find({ isVerified: true, isAdmin: true }); return admins.map(({ email, firstName, lastName, location }) => ({ email, firstName, lastName, location, })); } catch (error) { throw new Error("Internal server error"); } };
sgsonu/covid-vaccine-distribution
services/server/src/routers/auth/logout.ts
<filename>services/server/src/routers/auth/logout.ts import { Response, Router } from "express"; import { logout } from "../../models/auth/logout"; export const logoutRouter = Router(); logoutRouter.post( "/", (_, res: Response): Response => { logout(res); return res.status(200).send({ success: true }); } );
sgsonu/covid-vaccine-distribution
services/server/src/models/middlewares/verifyAdmin.ts
<filename>services/server/src/models/middlewares/verifyAdmin.ts import { NextFunction, Request, Response } from "express"; export const verifyAdmin = ( req: Request, res: Response, next: NextFunction ): void | Response => { if (!req.user.isAdmin) return res.status(400).send({ error: "Not authorized" }); return next(); };
sgsonu/covid-vaccine-distribution
services/server/src/routers/auth/signUp/validate.ts
<filename>services/server/src/routers/auth/signUp/validate.ts<gh_stars>0 import { SignUpProps } from "../../../models/auth/signUp"; import { isEmail } from "../../utils/isEmail"; export const validate = ({ email, firstName, password, lat, lng, }: SignUpProps): string[] => { const errors: string[] = []; if (!email) { errors.push("email required"); } else if (!isEmail(email)) errors.push("Invalid email"); if (!firstName) errors.push("firstName required"); if (!password) { errors.push("password requried"); } else if (password.length < 5) errors.push("Invalid password"); if (!lat) { errors.push("lat required"); } else if (isNaN(lat)) errors.push("invalid lat"); if (!lng) { errors.push("lng required"); } else if (isNaN(lng)) errors.push("invalid lng"); return errors; };
sgsonu/covid-vaccine-distribution
services/server/src/models/auth/signUp/index.ts
<gh_stars>0 import { hash } from "bcryptjs"; import { getConnection } from "typeorm"; import { User } from "../../../entity/User"; import { sendMail } from "../../utils/sendMail"; import { v4 as genHash } from "uuid"; export interface SignUpProps { firstName: string; lastName?: string; email: string; password: string; lat: number; lng: number; isRoot?: boolean; isSuperUser?: boolean; isAdmin?: boolean; } export const signUp = async ({ password, lat, lng, isRoot, ...restUserDetails }: SignUpProps): Promise<boolean> => { const dbConnection = getConnection(); let user = new User(); user = Object.assign<User, typeof restUserDetails>(user, restUserDetails); const hashedPassword = await hash(password, 10); user.password = <PASSWORD>; user.location = { type: "Point", coordinates: [lat, lng], }; if (isRoot) { user.isRoot = true; user.isVerified = true; } const verifyEmailHash = genHash(); user.verifyEmailHash = verifyEmailHash; try { await dbConnection.getRepository(User).insert(user); } catch (error) { throw new Error(error); } !isRoot && sendMail({ to: restUserDetails.email, html: `<div>Click <a href="${process.env.WEB}/auth/verify_email?verify_email_hash=${verifyEmailHash}">here</a> to verify your email </div>`, subject: "Verify your email", }).catch(console.error); return true; };
sgsonu/covid-vaccine-distribution
services/server/src/routers/auth/refreshToken.ts
import { Router, Request, Response } from "express"; import { refreshToken } from "../../models/auth/refreshToken"; const refreshTokenRouter = Router(); refreshTokenRouter.post( "/", async (req: Request, res: Response): Promise<Response> => { const token: string = req.cookies.jid; if (!token) { return res .status(400) .send({ error: "TOKEN_REQUIRED", accessToken: null }); } try { const accessToken = await refreshToken(token); return res.send({ error: null, accessToken }); } catch (error) { return res.status(400).send({ error: error.message, accessToken: null }); } } ); export { refreshTokenRouter };
sgsonu/covid-vaccine-distribution
services/server/src/routers/utils/isDate.ts
<filename>services/server/src/routers/utils/isDate.ts export const isDate = (date: Date): boolean => Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date.getTime());
sgsonu/covid-vaccine-distribution
services/server/src/routers/user/addProfile/index.ts
import { Request, Response, Router } from "express"; import { addPatientProfile } from "../../../models/user/addPatientProfile"; import { verifyUser } from "../../../models/middlewares/verifyUser"; import { validate } from "./validate"; export const addProfileRouter = Router(); addProfileRouter.post( "/", verifyUser, async (req: Request, res: Response): Promise<Response> => { const errors: string[] = validate(req.body); if (errors.length) return res.status(400).send({ errors }); try { await addPatientProfile({ ...req.body, user: req.user }); return res.status(200).send({ success: true }); } catch (error) { return res.status(500).send({ errors: [error.message] }); } } );
sgsonu/covid-vaccine-distribution
services/server/src/routers/root/signUpAdmin/index.ts
import { Request, Response, Router } from "express"; import { signUp } from "../../../models/auth/signUp"; import { validate } from "../../auth/signUp/validate"; export const signUpAdminRouter = Router(); signUpAdminRouter.post( "/", async (req: Request, res: Response): Promise<Response> => { const errors: string[] = validate(req.body); if (errors.length) return res.status(400).send({ errors }); try { await signUp({ ...req.body, isAdmin: true }); return res.status(200).send({ success: true }); } catch (error) { error = error.message; if (error.includes("duplicate key")) error = "User already exists"; return res.status(400).send({ errors: [error] }); } } );
sgsonu/covid-vaccine-distribution
services/server/src/routers/auth/index.ts
import { Router } from "express"; import { loginRouter } from "./login"; import { logoutRouter } from "./logout"; import { refreshTokenRouter } from "./refreshToken"; import { signUpRouter } from "./signUp/signUp"; import { verifyEmailRouter } from "./verifyEmail"; export const authRouter = Router(); authRouter.use("/login", loginRouter); authRouter.use("/signup", signUpRouter); authRouter.use("/refresh_token", refreshTokenRouter); authRouter.use("/verify_email", verifyEmailRouter); authRouter.use("/logout", logoutRouter);
sgsonu/covid-vaccine-distribution
services/server/src/models/utils/pythonExec.ts
<filename>services/server/src/models/utils/pythonExec.ts import { resolve } from "path"; import { PythonShell } from "python-shell"; export const pythonExec = ( pythonScript: string, args: string[] ): Promise<string[]> => { return new Promise((done, reject) => PythonShell.run( resolve(pythonScript), { args, pythonPath: process.env.NODE_ENV === "development" ? "mlModel/venv/bin/python3" : undefined, }, (err, results?: string[]) => err ? reject(err) : !results ? reject("Error generating score") : done(results) ) ); };
sgsonu/covid-vaccine-distribution
services/server/src/models/user/addPatientProfile/index.ts
import fetch from "node-fetch"; import { getConnection } from "typeorm"; import { PatientProfile } from "../../../entity/PatientProfile"; import { User } from "../../../entity/User"; export interface AddPatientProfileProps extends PatientProfile { user: User; } const getDateDiff = (date1: string, date2: string): number => { const dateA = new Date(date1); const dateB = new Date(date2); return Math.round((dateA.getTime() - dateB.getTime()) / (1000 * 3600 * 24)); }; export const addPatientProfile = async ({ dateSymptoms, user, ...restPatientDetails }: AddPatientProfileProps): Promise<boolean> => { const dbConnection = getConnection(); const queryRunner = dbConnection.createQueryRunner(); // Start a transaction await queryRunner.startTransaction(); let patientProfile = new PatientProfile(); patientProfile = Object.assign<PatientProfile, typeof restPatientDetails>( patientProfile, restPatientDetails ); const dateEntry: string = new Date().toISOString(); patientProfile.dateSymptoms = new Date(dateSymptoms).toISOString(); patientProfile.dateEntry = dateEntry; try { await queryRunner.manager .getRepository(PatientProfile) .insert(patientProfile); // Call ML model to get covidVulnerabilityScore const res = await fetch(`${process.env.MODEL_SERVER}/score/`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ ...restPatientDetails, deltaDate: getDateDiff(dateEntry, dateSymptoms), }), }); const { death_prob: covidVulnerabilityScore } = await res.json(); // Update covidVulnerabilityScore in the user table await queryRunner.manager .getRepository(User) .update( { email: user.email }, { patientProfile, covidVulnerabilityScore } ); // Commit transaction await queryRunner.commitTransaction(); return true; } catch (error) { queryRunner.rollbackTransaction(); throw new Error("Internal Server error"); } finally { queryRunner.release(); } };
sgsonu/covid-vaccine-distribution
services/server/src/models/middlewares/verifyUser.ts
<filename>services/server/src/models/middlewares/verifyUser.ts<gh_stars>0 import { NextFunction, Request, Response } from "express"; import { verify } from "jsonwebtoken"; import { getConnection } from "typeorm"; import { User } from "../../entity/User"; import { Payload } from "../../types/Payload"; export const verifyUser = async ( req: Request, res: Response, next: NextFunction ): Promise<void | Response> => { if (!req.headers.authorization) return res.status(400).send({ error: "Authorization needed" }); const authorization = req.headers.authorization.split(" "); if (authorization.length !== 2) return res.status(400).send({ error: "Authorization needed" }); const token = authorization[1]; try { const { email } = verify( token!, process.env.ACCESS_TOKEN_SECRET! ) as Payload; const dbConnection = getConnection(); const user = await dbConnection .getRepository(User) .findOne({ email, isVerified: true }); if (!user) return res.status(400).send({ error: "Not authorized" }); req.user = user; return next(); } catch { return res.status(400).send({ error: "Not authorized" }); } };
sgsonu/covid-vaccine-distribution
services/server/src/models/admin/scheduleVaccination/timeSlots.ts
<filename>services/server/src/models/admin/scheduleVaccination/timeSlots.ts export const timeSlots: string[] = [ `9:00 AM - 10:00 AM`, `10:00 AM - 11:00 AM`, `11:00 AM - 12:00 PM`, `12:00 PM - 1:00 PM`, `2:00 PM - 3:00 PM`, `3:00 PM - 4:00 PM`, `4:00 PM - 5:00 PM`, `5:00 PM - 6:00 PM`, ];
sgsonu/covid-vaccine-distribution
services/server/src/routers/admin/scheduleVaccination/index.ts
<filename>services/server/src/routers/admin/scheduleVaccination/index.ts import { Request, Response, Router } from "express"; import { scheduleVaccination } from "../../../models/admin/scheduleVaccination"; export const scheduleVaccinationRouter = Router(); scheduleVaccinationRouter.post( "/", async (req: Request, res: Response): Promise<Response> => { if (req.user.isSuperUser) { return res.status(400).send({ error: "Unauthorized" }); } const { patientsPerSlot } = req.body; const { email } = req.user; if (!patientsPerSlot) return res.status(400).send({ error: "PatientsPerSlot is required" }); else if ( isNaN(patientsPerSlot) || patientsPerSlot < 0 || !Number.isInteger(patientsPerSlot) ) return res.status(400).send({ error: "Invalid PatientsPerSlot" }); try { const scheduledPatients = await scheduleVaccination( email, patientsPerSlot ); return res.status(200).send({ scheduledPatients }); } catch (error) { return res.status(500).send({ error: error.message }); } } );
sgsonu/covid-vaccine-distribution
services/server/src/models/auth/logout/index.ts
import { Response } from "express"; export const logout = (res: Response): boolean => { res.clearCookie("jid", { httpOnly: true, path: "/auth/refresh_token", }); return true; };
sgsonu/covid-vaccine-distribution
services/server/src/models/utils/createRefreshToken.ts
import { sign } from "jsonwebtoken"; import { Payload } from "../../types/Payload"; export const createRefreshToken = (payload: Payload): string => sign(payload, process.env.REFRESH_TOKEN_SECRET!, { expiresIn: "7d" });
sgsonu/covid-vaccine-distribution
services/server/src/routers/auth/login.ts
import { Request, Response, Router } from "express"; import { login } from "../../models/auth/login"; import { isEmail } from "../utils/isEmail"; export const loginRouter = Router(); loginRouter.post( "/", async (req: Request, res: Response): Promise<Response> => { const errors = []; const { email, password } = req.body; if (!email) { errors.push("email required"); } else if (!isEmail(email)) errors.push("Invalid email"); if (!password) errors.push("password required"); if (errors.length) res.status(400).send({ errors }); try { const { accessToken } = await login({ email, password, res }); return res.status(200).send({ accessToken }); } catch (error) { return res.status(400).send({ errors: [error.message] }); } } );
sgsonu/covid-vaccine-distribution
services/server/src/routers/getPatientTrend/index.ts
<filename>services/server/src/routers/getPatientTrend/index.ts import { Router, Response, Request } from "express"; import { getPatientTrend } from "../../models/getPatientTrend"; export const getPatientTrendRouter = Router(); getPatientTrendRouter.get( "/", async (req: Request, res: Response): Promise<Response> => { let { lastNumDays, nextNumDays } = req.query; try { const patients = await getPatientTrend( parseInt(lastNumDays as string), parseInt(nextNumDays as string) ); return res.status(200).send({ patients }); } catch (error) { return res.status(500).send({ error: error.message }); } } );
sgsonu/covid-vaccine-distribution
services/server/src/routers/root/experimental/index.ts
<filename>services/server/src/routers/root/experimental/index.ts import { Router } from "express"; import { signUpRandomAdminsUsersRouter } from "./signUpRandomAdminsUsers"; export const experimentalRootRouter = Router(); experimentalRootRouter.use( "/random_admins_users", signUpRandomAdminsUsersRouter );
sgsonu/covid-vaccine-distribution
services/server/src/routers/admin/index.ts
import { Router } from "express"; import { getNonScheduledPatientsRouter } from "./getNonScheduledPatients"; import { getRegisteredPatientsRouter } from "./getRegisteredPatients"; import { scheduleVaccinationRouter } from "./scheduleVaccination"; export const adminRouter = Router(); adminRouter.use("/schedule_vaccination", scheduleVaccinationRouter); adminRouter.use("/registered_patients", getRegisteredPatientsRouter); adminRouter.use("/non_scheduled_patients", getNonScheduledPatientsRouter);
sgsonu/covid-vaccine-distribution
services/server/src/types/Payload.ts
<gh_stars>0 import { Point } from "geojson"; export interface Payload { email: string; firstName: string; lastName: string; isAdmin: boolean; isSuperUser: boolean; isProfileAdded: boolean; vaccinationDate?: string; location: Point; }
sgsonu/covid-vaccine-distribution
services/server/src/routers/admin/getRegisteredPatients/index.ts
import { Request, Response, Router } from "express"; import { getRegisteredPatients } from "../../../models/admin/getRegisteredPatients"; export const getRegisteredPatientsRouter = Router(); getRegisteredPatientsRouter.get( "/", async (req: Request, res: Response): Promise<Response> => { const { lastNumDays, nextNumDays } = req.query; try { const patients = await getRegisteredPatients( req.user.email, parseInt(lastNumDays as string), parseInt(nextNumDays as string) ); return res.status(200).send({ patients }); } catch (error) { return res.status(500).send({ error: error.message }); } } );
Juansereina/protractor-workshop-2019
src/page/shipping-step.page.ts
import { $, ElementFinder } from 'protractor'; export class ShippingStepPage { private acceptButton: ElementFinder; private continueButton: ElementFinder; constructor () { this.acceptButton = $('#cgv'); this.continueButton = $('#form > p > button > span'); } public async acceptAndContinue(): Promise<void> { await this.acceptButton.click(); await this.continueButton.click(); } }
Juansereina/protractor-workshop-2019
src/page/product-list.page.ts
import { $, ElementFinder, element, by, browser } from 'protractor'; export class ProductListPage { private addToCartButton: ElementFinder; private product: ElementFinder; constructor () { this.addToCartButton = $('#center_column a.button.ajax_add_to_cart_button.btn.btn-default'); this.product = element(by.css('.product-container .product-image-container')); } public async productHover(): Promise<void> { await browser.actions().mouseMove(this.product).perform(); } public async addToCart(): Promise<void> { await this.addToCartButton.click(); } }
Juansereina/protractor-workshop-2019
src/page/order-summary.page.ts
import { $, ElementFinder } from 'protractor'; export class OrderSummaryPage { private order: ElementFinder; constructor () { this.order = $('#center_column > div > p > strong'); } public async getSummary():Promise<String> { return this.order.getText(); } }
Juansereina/protractor-workshop-2019
test/buy-tshirt.spec.ts
<gh_stars>0 import { browser } from 'protractor'; import { MenuContentPage, ProductListPage, ProductAddedModalPage, SummaryStepPage, SignInStepPage, AddressStepPage, ShippingStepPage, PaymentStepPage, BankPaymentPage, OrderSummaryPage } from '../src/page/'; describe('Buy a t-shirt', () => { const menuContentPage: MenuContentPage = new MenuContentPage(); const productListPage: ProductListPage = new ProductListPage(); const productAddedModalPage: ProductAddedModalPage = new ProductAddedModalPage(); const summaryStepPage: SummaryStepPage = new SummaryStepPage(); const signInStepPage: SignInStepPage = new SignInStepPage(); const addressStepPage: AddressStepPage = new AddressStepPage(); const ahippingStepPage: ShippingStepPage = new ShippingStepPage(); const paymentStepPage: PaymentStepPage = new PaymentStepPage(); const bankPaymentPage: BankPaymentPage = new BankPaymentPage(); const orderSummaryPage: OrderSummaryPage = new OrderSummaryPage(); beforeEach(() => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 120000; }); it('then should be bought a t-shirt', async () => { await browser.get('http://automationpractice.com/'); await(browser.sleep(3000)); await menuContentPage.goToTShirtMenu(); await(browser.sleep(3000)); await productListPage.productHover(); await(browser.sleep(1000)); await productListPage.addToCart(); await(browser.sleep(3000)); await productAddedModalPage.open(); await(browser.sleep(3000)); await summaryStepPage.checkout(); await(browser.sleep(3000)); await signInStepPage.signIn('<EMAIL>', 'WorkshopProtractor'); await(browser.sleep(3000)); await addressStepPage.proceed(); await(browser.sleep(3000)); await ahippingStepPage.acceptAndContinue(); await(browser.sleep(3000)); await paymentStepPage.pay(); await(browser.sleep(3000)); await bankPaymentPage.confirm(); await(browser.sleep(3000)); await expect(orderSummaryPage.getSummary()) .toBe('Your order on My Store is complete.'); }); });
Juansereina/protractor-workshop-2019
src/page/payment-step.page.ts
import { $, ElementFinder } from 'protractor'; export class PaymentStepPage { private paymentButton: ElementFinder; constructor () { this.paymentButton = $('#HOOK_PAYMENT > div:nth-child(1) > div > p > a'); } public async pay(): Promise<void> { await this.paymentButton.click(); } }
Juansereina/protractor-workshop-2019
src/page/product-added-modal.page.ts
<gh_stars>0 import { $, ElementFinder } from 'protractor'; export class ProductAddedModalPage { private modal: ElementFinder; constructor () { this.modal = $('[style*="display: block;"] .button-container > a'); } public async open(): Promise<void> { await this.modal.click(); } }
Juansereina/protractor-workshop-2019
src/page/summary-step.page.ts
import { $, ElementFinder } from 'protractor'; export class SummaryStepPage { private summaryPage: ElementFinder; constructor () { this.summaryPage = $('.cart_navigation span'); } public async checkout(): Promise<void> { await this.summaryPage.click(); } }
MECVxD/nest-library
src/test.ts
<reponame>MECVxD/nest-library export function getHello(name: string): string { return 'Hola' + name; } export function suma(x: number, y: number): number { return x + y; } export function resta(x: number, y: number): number { return x - y; }
tvalodia/battletron
webapp/src/app/game-view/game-view.service.spec.ts
import { TestBed } from '@angular/core/testing'; import { GameViewService } from './game-view.service'; describe('GameViewService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: GameViewService = TestBed.get(GameViewService); expect(service).toBeTruthy(); }); });
tvalodia/battletron
webapp/src/app/spectate-game/spectate-game.component.ts
<reponame>tvalodia/battletron<filename>webapp/src/app/spectate-game/spectate-game.component.ts import {Component, OnInit, ViewChild} from '@angular/core'; import {GameService} from "../api/game.service"; import {WebsocketService} from "../game-view/websocket.service"; import {Game, GameViewService} from "../game-view/game-view.service"; import {GameViewComponent} from "../game-view/game-view.component"; import {SpectateGame} from "./spectate-game"; @Component({ selector: 'app-spectate-game', templateUrl: './spectate-game.component.html', styleUrls: ['./spectate-game.component.css'], providers: [WebsocketService, GameViewService] }) export class SpectateGameComponent implements OnInit { spectateGameData: SpectateGame = new SpectateGame(); games: Array<Game>; @ViewChild('gameView') gameViewRef: GameViewComponent; constructor(private gameService: GameService) { } ngOnInit() { this.getGames(); } onSessionId(sessionId: string) { this.spectateGameData.sessionId = sessionId; } public getGames() { this.gameService.getGames().subscribe((data: Array<Game>) => { this.games = data; console.log(data); }); } public refresh() { this.getGames(); } public spectateGame(gameId: number) { this.gameService.spectateGame(gameId, this.spectateGameData).subscribe((data: Game) => { this.gameViewRef.setGame(data); console.log(gameId); }); } }
tvalodia/battletron
webapp/src/app/game-view/game-view.component.ts
<reponame>tvalodia/battletron import { Component, ElementRef, EventEmitter, NgZone, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'; import {Game, GameViewService} from "./game-view.service"; @Component({ selector: 'app-game-view', templateUrl: './game-view.component.html', styleUrls: ['./game-view.component.css'] }) export class GameViewComponent implements OnInit, OnDestroy { BLOCK_SIZE: number = 5; @ViewChild('gameViewCanvas') canvasRef: ElementRef; sessionId: string = ''; @Output() sessionIdEventEmitter = new EventEmitter<string>(); private game: Game; constructor(private ngZone: NgZone, private gameViewService: GameViewService) { gameViewService.subject.subscribe(msg => { if (msg.startsWith("id=")) { this.sessionId = msg.substr(3); this.sessionIdEventEmitter.emit(msg.substr(3)); } else { this.game = JSON.parse(msg); this.paint(); } }); } ngOnInit() { } ngOnDestroy() { this.gameViewService.subject.unsubscribe(); this.gameViewService.disconnect(); console.log("ngOnDestroy"); } private paint() { // Paint current frame let ctx: CanvasRenderingContext2D = this.canvasRef.nativeElement.getContext('2d'); // // Draw background (which also effectively clears any previous drawing) ctx.fillStyle = 'rgb(0, 0, 0)'; // Clear any previous content. ctx.fillRect(0, 0, 500, 500); ctx.lineWidth = 1; //Draw the players' trails for (let x = 0; x < this.game.width; x++) { for (let y = 0; y < this.game.height; y++) { if (this.game.playingField[x][y] == this.game.playerOne.id) { this.drawBlock(ctx, this.getScreenX(x), this.getScreenY(this.game.height, y), "blue"); } if (this.game.playingField[x][y] == this.game.playerTwo.id) { this.drawBlock(ctx, this.getScreenX(x), this.getScreenY(this.game.height, y), "magenta"); } } } //player 1's head this.drawBlock(ctx, this.getScreenX(this.game.playerOne.positionX), this.getScreenY(this.game.height, this.game.playerOne.positionY), "cyan"); //player 2's head this.drawBlock(ctx, this.getScreenX(this.game.playerTwo.positionX), this.getScreenY(this.game.height, this.game.playerTwo.positionY), "pink"); } getScreenX(gameX: number) { return gameX * this.BLOCK_SIZE; } getScreenY(playingFieldHeight: number, gameYCoordinate: number) { return ((playingFieldHeight - 1) * this.BLOCK_SIZE) - (gameYCoordinate * this.BLOCK_SIZE); } drawBlock(ctx: CanvasRenderingContext2D, x: number, y: number, color: string) { ctx.beginPath(); ctx.strokeStyle = color; ctx.fillStyle = color; ctx.fillRect(x, y, this.BLOCK_SIZE, this.BLOCK_SIZE); ctx.stroke() } onKeydown(event) { let key = event.which; if (key === 87) { this.sendMsg("W"); } else if (key === 83) { this.sendMsg("S"); } else if (key === 65) { this.sendMsg("A"); } else if (key === 68) { this.sendMsg("D"); } else if (key === 38) { this.sendMsg("UP"); } else if (key === 40) { this.sendMsg("DOWN"); } else if (key === 37) { this.sendMsg("LEFT"); } else if (key === 39) { this.sendMsg("RIGHT"); } } sendMsg(direction: string) { this.gameViewService.subject.next(direction); } public setGame(game: Game) { this.game = game; this.paint(); } }
tvalodia/battletron
webapp/src/app/new-game/new-game-player.ts
export class NewGamePlayer { playerType: string; aiRemoteHost: string; }
tvalodia/battletron
webapp/src/app/spectate-game/status.pipe.ts
<filename>webapp/src/app/spectate-game/status.pipe.ts import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'status' }) export class StatusPipe implements PipeTransform { transform(value: any, args?: any): any { if (value == "COMPLETED_WINNER") { return "WINNER"; } else if (value == "COMPLETED_DRAW") { return "DRAW"; } else if (value == "WAITING_FOR_READY") { return "NOT STARTED"; } else if (value == "STARTED") { return "IN PROGRESS"; } else if (value == "STOPPED") { return "STOPPED"; } else if (value == "TIMED_OUT") { return "TIMED OUT"; } else return "UNKNOWN"; } }
tvalodia/battletron
webapp/src/app/spectate-game/spectate-game.ts
export class SpectateGame { sessionId: string; }
tvalodia/battletron
webapp/src/app/api/game.service.ts
import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {NewGame} from "../new-game/new-game"; import {JoinGame} from "../join-game/join-game"; import {SpectateGame} from "../spectate-game/spectate-game"; @Injectable({ providedIn: 'root' }) export class GameService { API_URL: string = '/api/game'; constructor(private httpClient: HttpClient) { } getGames() { return this.httpClient.get(this.API_URL); } getJoinableGames() { return this.httpClient.get(this.API_URL + "/open"); } spectateGame(gameId: number, spectateGame: SpectateGame) { return this.httpClient.post(this.API_URL + "/" + gameId + "/spectate", JSON.stringify(spectateGame)); } createGame(newGame: NewGame) { return this.httpClient.post(this.API_URL, JSON.stringify(newGame)); } joinGame(gameId: number, joinGame: JoinGame) { return this.httpClient.post(this.API_URL + "/" + gameId + "/join", JSON.stringify(joinGame)); } }
tvalodia/battletron
webapp/src/app/game-view/game-view.service.ts
import {Injectable} from '@angular/core'; import {Subject} from 'rxjs/Rx'; import {WebsocketService} from './websocket.service'; const GAME_URL = 'ws://' + document.location.host + '/player'; export interface Game { id: number; width: number; height: number; gameStatus: string; tickCount: number; playerOne: Player; playerTwo: Player; playingField: number[][]; winner: Player; createdDate: number; } export interface Player { id: number; positionX: number; positionY: number; } @Injectable() export class GameViewService { public subject: Subject<string>; constructor(public wsService: WebsocketService) { console.log(document.location); this.subject = <Subject<string>>wsService .connect(GAME_URL) .map((response: MessageEvent): string => { return response.data; //JSON.parse(response.data); }); } public disconnect() { this.wsService.disconnect(); } }
tvalodia/battletron
webapp/src/app/new-game/new-game.ts
import {NewGamePlayer} from "./new-game-player"; export class NewGame { sessionId: string; playerOne: NewGamePlayer = new NewGamePlayer(); playerTwo: NewGamePlayer = new NewGamePlayer(); }
tvalodia/battletron
webapp/src/app/app.module.ts
import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {AppRoutingModule} from './app-routing.module'; import {AppComponent} from './app.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {FormsModule, ReactiveFormsModule} from "@angular/forms"; import {MainMenuComponent} from './main-menu/main-menu.component'; import {BattletronMaterialModule} from './material'; import {NewGameComponent} from './new-game/new-game.component'; import {GameViewComponent} from './game-view/game-view.component'; import {HttpClientModule, HTTP_INTERCEPTORS} from '@angular/common/http'; import {SpectateGameComponent} from './spectate-game/spectate-game.component'; import {StatusPipe} from './spectate-game/status.pipe'; import {JoinGameComponent} from './join-game/join-game.component'; import {ErrorDialogComponent} from './error-dialog/errordialog.component'; import {ErrorDialogService} from './error-dialog/errordialog.service'; import {HttpConfigInterceptor} from './interceptor/httpconfig.interceptor'; @NgModule({ declarations: [ AppComponent, MainMenuComponent, NewGameComponent, GameViewComponent, SpectateGameComponent, StatusPipe, JoinGameComponent, ErrorDialogComponent ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule, BattletronMaterialModule, HttpClientModule ], providers: [ ErrorDialogService, {provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true} ], entryComponents: [ErrorDialogComponent], bootstrap: [AppComponent] }) export class AppModule { }
tvalodia/battletron
webapp/src/app/join-game/join-game.ts
export class JoinGame { sessionId: string; }
tvalodia/battletron
webapp/src/app/app-routing.module.ts
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import {MainMenuComponent} from "./main-menu/main-menu.component"; import {NewGameComponent} from "./new-game/new-game.component"; import {SpectateGameComponent} from "./spectate-game/spectate-game.component"; import {JoinGameComponent} from "./join-game/join-game.component"; const routes: Routes = [ { path: '', component: MainMenuComponent }, { path: 'newgame', component: NewGameComponent }, { path: 'spectate', component: SpectateGameComponent }, { path: 'join', component: JoinGameComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
tvalodia/battletron
webapp/src/app/material.ts
<gh_stars>0 import { MatButtonModule, MatButtonToggleModule, MatCardModule, MatGridListModule, MatListModule, MatSelectModule, MatDialogModule, MatInputModule } from "@angular/material"; import {NgModule} from "@angular/core"; @NgModule({ imports: [MatCardModule, MatButtonModule, MatButtonToggleModule, MatSelectModule, MatGridListModule, MatListModule, MatDialogModule, MatInputModule], exports: [MatCardModule, MatButtonModule, MatButtonToggleModule, MatSelectModule, MatGridListModule, MatListModule, MatDialogModule, MatInputModule] }) export class BattletronMaterialModule { }
tvalodia/battletron
webapp/src/app/join-game/join-game.component.ts
<filename>webapp/src/app/join-game/join-game.component.ts import {Component, OnInit, ViewChild} from '@angular/core'; import {GameService} from "../api/game.service"; import {WebsocketService} from "../game-view/websocket.service"; import {Game, GameViewService} from "../game-view/game-view.service"; import {GameViewComponent} from "../game-view/game-view.component"; import {JoinGame} from "./join-game"; @Component({ selector: 'app-join-game', templateUrl: './join-game.component.html', styleUrls: ['./join-game.component.css'], providers: [WebsocketService, GameViewService] }) export class JoinGameComponent implements OnInit { joinGameData: JoinGame = new JoinGame(); games: Array<Game>; @ViewChild('gameView') gameViewRef: GameViewComponent; constructor(private gameService: GameService) { } ngOnInit() { this.getGames(); } onSessionId(sessionId: string) { this.joinGameData.sessionId = sessionId; } public getGames() { this.gameService.getJoinableGames().subscribe((data: Array<Game>) => { this.games = data; console.log(data); }); } public refresh() { this.getGames(); } public joinGame(gameId: number) { this.gameService.joinGame(gameId, this.joinGameData).subscribe((data: Game) => { this.gameViewRef.setGame(data); console.log(gameId); }); } }
tvalodia/battletron
webapp/src/app/new-game/new-game.component.ts
<reponame>tvalodia/battletron<filename>webapp/src/app/new-game/new-game.component.ts import {Component, OnInit} from '@angular/core'; import {GameViewService} from '../game-view/game-view.service'; import {WebsocketService} from "../game-view/websocket.service"; import {GameService} from "../api/game.service"; import {NewGame} from "./new-game"; import {FormBuilder, FormGroup, NgForm} from "@angular/forms"; export interface PlayerType { value: string; viewValue: string; } @Component({ selector: 'app-new-game', templateUrl: './new-game.component.html', styleUrls: ['./new-game.component.css'], providers: [WebsocketService, GameViewService] }) export class NewGameComponent implements OnInit { newGameForm: FormGroup; sessionId: string; playerTypes: PlayerType[] = [ {value: 'KEYBOARD_WASD_KEYS', viewValue: 'Human - WASD keys'}, {value: 'KEYWORD_ARROW_KEYS', viewValue: 'Human - Arrow keys'}, {value: 'AI_SIMPLE', viewValue: 'AI - Simple'}, {value: 'AI_DOWNLEFT', viewValue: 'AI - Down Left'}, {value: 'AI_REMOTE', viewValue: 'AI - Remote'}, {value: 'OPEN', viewValue: 'Open'} ]; constructor(private formBuilder: FormBuilder, private gameService: GameService) { this.newGameForm = formBuilder.group( { playerOneType: [this.playerTypes[0].value], playerTwoType: [this.playerTypes[0].value], playerOneAiRemoteHost: ["http://localhost:5000"], playerTwoAiRemoteHost: ["http://localhost:5000"] }); } ngOnInit() {} onNewPlayerId(sessionId: string) { this.sessionId = sessionId; } public start(newGameData: NewGame) { this.gameService.createGame(newGameData) .subscribe((data: Array<object>) => { console.log(data); }); } showPlayerOneHost() { return this.newGameForm.controls.playerOneType.value === "AI_REMOTE"; } showPlayerTwoHost() { return this.newGameForm.controls.playerTwoType.value === "AI_REMOTE"; } showHostRow() { return this.showPlayerOneHost() || this.showPlayerTwoHost(); } onFormSubmit(form:NgForm) { let newGameData: NewGame = new NewGame(); newGameData.sessionId = this.sessionId; newGameData.playerOne.playerType = form["playerOneType"]; if (this.showPlayerOneHost()) { newGameData.playerOne.aiRemoteHost = form["playerOneAiRemoteHost"]; } newGameData.playerTwo.playerType = form["playerTwoType"]; if (this.showPlayerTwoHost()) { newGameData.playerTwo.aiRemoteHost = form["playerTwoAiRemoteHost"]; } this.start(newGameData ); } }
xiaohuidong99/Ionic2-IonicClub
app/pages/topicDetail/topicDetail.ts
import {Page, Loading, NavController, NavParams, Storage, LocalStorage} from "ionic-angular"; import {IonicService} from "../../services/IonicService"; import {ConfigService} from "../../services/ConfigService"; import {AmTimeAgoPipe} from '../../pipe/AmTimeAgoPipe'; import {AvatarPipe} from "../../pipe/avatarPipe"; import {LinkPipe} from "../../pipe/linkPipe"; import {SocialSharing} from 'ionic-native'; @Page({ templateUrl: 'build/pages/topicDetail/topicDetail.html', providers: [IonicService, ConfigService], pipes: [AmTimeAgoPipe, LinkPipe, AvatarPipe] }) export class TopicDetailPage { private user; private local:LocalStorage; private isLogin:boolean = false; private id:string; private topicDetail = { author: { loginname: '', avatar_url: '' }, create_at: '', last_reply_at: '', content: '', visit_count: '', reply_count: '', replies: [] }; // 评论参数 private replyData = { accesstoken: '', content: '', reply_id: '' } // 收藏参数 private collectData = { accesstoken: '', topic_id: '' } // 分享参数 private shareData = { message: '', subject: '', link: '' }; constructor(private nav:NavController, private navParams:NavParams, private ionicService:IonicService) { this.local = new Storage(LocalStorage); } ngOnInit() { this.id = this.navParams.get('id'); this.collectData.topic_id = this.id; this.ionicService.getTopicById(this.id).subscribe( data => { this.topicDetail = data; this.shareData.message = data.content.substring(0, 150) + '......'; this.shareData.subject = data.title; this.shareData.link = 'http://ionichina.com/topic/' + data.id; }); this.local.get('User').then(u=> { if (u) { this.isLogin = true; this.user = JSON.parse(u); this.replyData.accesstoken = this.user.accesstoken; this.collectData.accesstoken = this.user.accesstoken; } }); } // 点赞 replieUps(replyId) { if (this.isLogin) { this.ionicService.postReplieUps(replyId, this.replyData.accesstoken).subscribe( data => { if (data.success) { if (data.action == 'up') { this.loading('赞一个', 500); } else { this.loading('取消点赞', 500); } } else { this.loading(data.error_msg, 500); } }, error=> { this.loading(error, 500); }); } else { this.loading('请登录后使用', '500'); } } // 回复 reReply(replyId, loginname) { if (this.isLogin) { this.replyData.content = '@' + loginname + ' '; this.replyData.reply_id = replyId; } else { this.loading('请登录后使用', '500'); } } // 收藏 collect() { if (this.isLogin) { this.ionicService.postTopicCollect(this.collectData).subscribe( data => { this.loading('收藏成功', 500); }); } else { this.loading('请登录后使用', '500'); } } // 分享 share() { SocialSharing.share(this.shareData.message, this.shareData.subject, this.shareData.link); } // 提交评论 saveReply() { if (this.replyData.content.indexOf('@') < 0) { this.replyData.reply_id = ''; } this.ionicService.postReplie(this.id, this.replyData).subscribe( data => { if (data.success) { let replie = { author: { loginname: this.user.loginname, avatar_url: this.user.avatar_url }, content: '<div class=\"markdown-text\"><p>' + this.replyData.content + '</p>\n</div>', id: data.reply_id }; this.topicDetail.replies.unshift(replie); this.loading('评论成功', 500); this.replyData.content = ''; } }) } loading(content, duration) { let loading = Loading.create({ spinner: 'hide', content: content, duration: duration }); this.nav.present(loading); } }
xiaohuidong99/Ionic2-IonicClub
app/pipe/DateFormatPipe.ts
<filename>app/pipe/DateFormatPipe.ts import {PipeTransform, Pipe} from "angular2/core"; @Pipe({ name: 'dateFormatPipe' }) export class DateFormatPipe implements PipeTransform { constructor() { } transform(value:string, args:any[]) { if (value && args) { value = this.Format(value,args[0]); } return value; } // 对Date的扩展,将 Date 转化为指定格式的String // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) // 例子: // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 // (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18 Format(value:string,fmt:string) { //author: meizz let date:Date = new Date(value); let o = { "M+": date.getMonth() + 1, //月份 "d+": date.getDate(), //日 "h+": date.getHours(), //小时 "m+": date.getMinutes(), //分 "s+": date.getSeconds(), //秒 "q+": Math.floor((date.getMonth() + 3) / 3), //季度 "S": date.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; } }
xiaohuidong99/Ionic2-IonicClub
app/pages/account/account.ts
<reponame>xiaohuidong99/Ionic2-IonicClub import {Page, NavController, Storage, LocalStorage, Modal, ViewController, Events} from 'ionic-angular'; import {IonicService} from "../../services/IonicService"; import {ConfigService} from "../../services/ConfigService"; import {MyCollectsPage} from "../modal/myCollects/myCollects"; import {AvatarPipe} from "../../pipe/avatarPipe"; import {MyTopicsPage} from "../modal/myTopics/myTopics"; import {MyMessagesPage} from "../modal/myMessages/myMessages"; import {AppVersion} from 'ionic-native'; import {TopicsPage} from "../topics/topics"; import {DateFormatPipe} from "../../pipe/DateFormatPipe"; @Page({ templateUrl: 'build/pages/account/account.html', providers: [IonicService, ConfigService], pipes: [AvatarPipe, DateFormatPipe] }) export class AccountPage { private local:LocalStorage; private versionNumber:string; private hasnot_read_messages_count:number = 0; private user = { avatar_url: '', loginname: '', score: '', create_at: '', recent_topics: [], recent_replies: [], collect_topics: [] }; private myTopics = { recent_topics: [], recent_replies: [] } private myMessages = { has_read_messages: [], hasnot_read_messages: [] } constructor(private viewCtrl:ViewController, private nav:NavController, private events:Events, private ionicService:IonicService) { this.events.subscribe('badge', (data)=> { this.hasnot_read_messages_count = data; }); this.local = new Storage(LocalStorage); } openMyCollects() { let modal = Modal.create(MyCollectsPage); this.nav.present(modal); } openMyMessages() { let modal = Modal.create(MyMessagesPage, {'messages': this.myMessages}); this.nav.present(modal); } openMyTopics() { let modal = Modal.create(MyTopicsPage, {'topics': this.myTopics}); this.nav.present(modal); } ngOnInit() { this.local.get('User').then(u=> { if (u) { let user = JSON.parse(u); this.ionicService.getUserByName(user.loginname).subscribe( data=> { this.user = data this.myTopics.recent_replies = data.recent_replies; this.myTopics.recent_topics = data.recent_topics; }); this.ionicService.getMessages(user.accesstoken).subscribe(data=> { this.myMessages = data }); this.ionicService.getMessageCount(user.accesstoken).subscribe(data=> { this.hasnot_read_messages_count = data; }); } }); AppVersion.getVersionNumber().then(data=> { this.versionNumber = data; }); } loginOut() { this.local.clear(); this.nav.setRoot(TopicsPage); } }
xiaohuidong99/Ionic2-IonicClub
app/pages/modal/myCollects/myCollects.ts
import {Page, NavParams, ViewController, Storage, LocalStorage} from 'ionic-angular'; import {IonicService} from "../../../services/IonicService"; import {ConfigService} from "../../../services/ConfigService"; import {AmTimeAgoPipe} from '../../../pipe/AmTimeAgoPipe'; import {AvatarPipe} from "../../../pipe/avatarPipe"; @Page({ templateUrl: 'build/pages/modal/myCollects/myCollects.html', providers: [IonicService, ConfigService], pipes: [AmTimeAgoPipe, AvatarPipe] }) export class MyCollectsPage { private user:any; private myCollects = { collect_topics: [] } private collectData = { accesstoken: '', topic_id: '' } private local:LocalStorage; constructor(private viewCtrl:ViewController, private ionicService:IonicService) { this.local = new Storage(LocalStorage); } ngOnInit() { this.local.get('User').then(u=> { if (u) { this.user = JSON.parse(u); this.ionicService.getUserByName(this.user.loginname).subscribe( data=> { this.collectData.accesstoken = this.user.accesstoken; this.myCollects.collect_topics = data.collect_topics; }); } }); } dismiss() { this.viewCtrl.dismiss(); } remove(topic_id:string) { this.collectData.topic_id = topic_id; this.ionicService.postTopicDeCollect(this.collectData).subscribe( data=> { if (data.success) { this.ionicService.getUserByName(this.user.loginname).subscribe( data=> { this.myCollects.collect_topics = []; this.myCollects.collect_topics = data.collect_topics; }); } }); } }
xiaohuidong99/Ionic2-IonicClub
app/services/CommonService.ts
import {Injectable} from 'angular2/core'; @Injectable() export class CommonService { constructor(){ } private _tabs = [{ value: 'share', label: '分享', icon:'share' }, { value: 'ask', label: '问答', icon:'help-circle' }, { value: 'job', label: '招聘', icon:'bowtie' }, { value: 'bb', label: '吐槽', icon:'text' }]; getTabs() { return this._tabs; } }
xiaohuidong99/Ionic2-IonicClub
app/pages/modal/myMessages/myMessages.ts
import {Page, NavParams, ViewController, Storage, LocalStorage, Events} from 'ionic-angular'; import {IonicService} from "../../../services/IonicService"; import {ConfigService} from "../../../services/ConfigService"; @Page({ templateUrl: 'build/pages/modal/myMessages/myMessages.html', providers: [IonicService, ConfigService] }) export class MyMessagesPage { private local:LocalStorage; private myMessages = { has_read_messages: [], hasnot_read_messages: [] } constructor(private viewCtrl:ViewController, private navParams:NavParams, private ionicService:IonicService, private events:Events) { this.local = new Storage(LocalStorage); } ngOnInit() { this.myMessages = this.navParams.get('messages'); this.local.get('User').then(u=> { if (u) { let user = JSON.parse(u); this.ionicService.postMessageMark_all(user.accesstoken).subscribe(data=> { if (data.success) { this.events.publish('badge', 0); console.log("标记全部已读"); } }); } }) } dismiss() { this.viewCtrl.dismiss(); } }
xiaohuidong99/Ionic2-IonicClub
app/services/ConfigService.ts
<reponame>xiaohuidong99/Ionic2-IonicClub<filename>app/services/ConfigService.ts import {Injectable} from 'angular2/core'; @Injectable() export class ConfigService { hostURL:string = "http://ionichina.com"; constructor() { } getHost() { return this.hostURL; } }
xiaohuidong99/Ionic2-IonicClub
app/app.ts
<reponame>xiaohuidong99/Ionic2-IonicClub import 'es6-shim'; import {App, Platform, IonicApp} from 'ionic-angular'; import {StatusBar} from 'ionic-native'; import {CommonService} from "./services/CommonService"; import {RouteConfig} from "angular2/router"; import {TopicsPage} from "./pages/topics/topics"; import {UserPage} from "./pages/user/user"; import {TopicDetailPage} from "./pages/topicDetail/topicDetail"; import {LoginPage} from "./pages/login/login"; import {AccountPage} from "./pages/account/account"; import {Toast} from 'ionic-native'; @App({ templateUrl: 'build/app.html', providers: [CommonService], config: { backButtonText: '', backButtonIcon: 'arrow-round-back', } }) @RouteConfig([ {path: '/topics', component: TopicsPage, as: 'Topic'}, {path: '/topics/:tab', component: TopicsPage, as: 'Topic'}, {path: '/topicDetail/:id', component: TopicDetailPage, as: 'TopicDetail'}, {path: '/user/:loginname', component: UserPage, as: 'User'}, {path: '/login', component: LoginPage, as: 'Login'}, {path: '/account', component: AccountPage, as: 'Account'} ]) export class MyApp { private rootPage = TopicsPage; private menuPage:any; private tabs = []; private backPressed:boolean = false; constructor(private app:IonicApp, platform:Platform, private commonService:CommonService) { platform.ready().then(() => { StatusBar.styleDefault(); this.registerBackButtonListener(); }); } registerBackButtonListener() { document.addEventListener('backbutton', ()=> { let nav = this.getNav(); if (nav.canGoBack()) { nav.pop(); return; } if (!this.backPressed) { this.backPressed = true; Toast.showShortBottom("再按一次退出应用").subscribe( toast => { console.log(toast); } ); setTimeout(()=>this.backPressed = false, 2000); return; } // 利用 cordova.js 退出应用(不影响使用) navigator.app.exitApp(); }, false); } getNav() { return this.app.getComponent('nav'); } setRootPage(tab:string) { this.getNav().setRoot(TopicsPage, {tab: tab}); } }
xiaohuidong99/Ionic2-IonicClub
app/directives/helpers.ts
<filename>app/directives/helpers.ts import {Directive, ElementRef, Renderer} from 'angular2/core'; import {Platform, Navbar} from 'ionic-angular'; export function debounce(func, wait, immediate) { var timeout; return function () { var context = this, args = arguments; var later = function () { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; function toQueryPair(key, value) { if (typeof value == 'undefined'){ return key; } return key + '=' + encodeURIComponent(value === null ? '' : String(value)); } export function toQueryString(obj) { var ret = []; for(var key in obj){ key = encodeURIComponent(key); var values = obj[key]; if(values && values.constructor == Array){//数组 var queryValues = []; for (var i = 0, len = values.length, value; i < len; i++) { value = values[i]; queryValues.push(toQueryPair(key, value)); } ret = ret.concat(queryValues); }else{ //字符串 ret.push(toQueryPair(key, values)); } } return '?'+ret.join('&'); } export function toBodyString(obj) { var ret = []; for(var key in obj){ key = encodeURIComponent(key); var values = obj[key]; if(values && values.constructor == Array){//数组 var queryValues = []; for (var i = 0, len = values.length, value; i < len; i++) { value = values[i]; queryValues.push(toQueryPair(key, value)); } ret = ret.concat(queryValues); }else{ //字符串 ret.push(toQueryPair(key, values)); } } return ret.join('&'); }
xiaohuidong99/Ionic2-IonicClub
app/pages/modal/topicAdd/topicAdd.ts
import {Page, NavController, ViewController, Loading, Storage, LocalStorage, Events} from 'ionic-angular'; import {IonicService} from "../../../services/IonicService"; import {ConfigService} from "../../../services/ConfigService"; @Page({ templateUrl: 'build/pages/modal/topicAdd/topicAdd.html', providers: [IonicService, ConfigService], }) export class TopicAddPage { private topicData:any = { accesstoken: '', title: '', tab: '', content: '' } private local:LocalStorage; constructor(private viewCtrl:ViewController, private nav:NavController, private ionicService:IonicService, private events:Events) { this.local = new Storage(LocalStorage); } ngOnInit() { this.local.get('User').then(u=> { if (u) { let user = JSON.parse(u); this.topicData.accesstoken = user.accesstoken; } else { this.loading('请登录后使用', 500); this.dismiss(); } }); } submit() { if (this.validate()) { this.ionicService.postTopic(this.topicData).subscribe(data=> { if (data.success) { this.events.publish('doRefresh'); this.loading('提交成功', 500); this.dismiss(); } else { this.loading('提交失败', 500); } }) } } dismiss() { this.viewCtrl.dismiss(); } validate() { if (this.topicData.tab == '') { this.loading('类别不能为空', 500); return false; } else if (this.topicData.title == '') { this.loading('标题不能为空', 500); return false; } else if (this.topicData.title.length <= 10) { this.loading('标题字数在10字以上', 500); return false; } else if (this.topicData.content == '') { this.loading('内容不能为空', 500); return false; } else { return true; } } loading(content, duration) { let loading = Loading.create({ spinner: 'hide', content: content, duration: duration }); this.nav.present(loading); } }
xiaohuidong99/Ionic2-IonicClub
app/services/IonicService.ts
import {Injectable, Inject} from 'angular2/core'; import {Http, HTTP_PROVIDERS, Response, Headers} from 'angular2/http'; import {Observable} from 'rxjs/Observable'; import {ConfigService} from "./ConfigService"; import * as helper from '../directives/helpers'; import 'rxjs/Rx'; @Injectable() export class IonicService { constructor(private http:Http, private configService:ConfigService) { } // 获取主题 getTopics(data) { let url = this.configService.getHost() + "/api/v1/topics"; return this.http.get(url + helper.toQueryString(data)).map( res=>res.json().data ).catch(this.handleError); } // 通过ID获取主题详情 getTopicById(id) { let url = this.configService.getHost() + "/api/v1/topic/" + id; return this.http.get(url).map( res=>res.json().data ).catch(this.handleError); } // 新增主题 postTopic(data) { let url = this.configService.getHost() + "/api/v1/topics"; let body = helper.toBodyString(data); let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); return this.http.post(url,body,{headers: headers}).map( res=>res.json() ).catch(this.handleError); } // 收藏主题 postTopicCollect(data) { let url = this.configService.getHost() + "/api/v1/topic/collect"; let body = helper.toBodyString(data); let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); return this.http.post(url,body,{headers: headers}).map( res=>res.json().data ).catch(this.handleError); } // 取消收藏主题 postTopicDeCollect(data) { let url = this.configService.getHost() + "/api/v1/topic/de_collect"; let body = helper.toBodyString(data); let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); return this.http.post(url,body,{headers: headers}).map( res=>res.json() ).catch(this.handleError); } // 新建评论 postReplie(id, data) { let url = this.configService.getHost() + "/api/v1/topic/" + id + "/replies"; let body = helper.toBodyString(data); let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); return this.http.post(url,body,{headers: headers}).map( res=>res.json() ).catch(this.handleError); } // 为评论点赞 postReplieUps(reply_id, accesstoken) { let url = this.configService.getHost() + "/api/v1/reply/" + reply_id + "/ups"; let body = 'accesstoken=' + accesstoken; let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); return this.http.post(url,body,{headers: headers}).map( res=>res.json() ).catch(this.handleError); } // 获取用户详情 getUserByName(loginname) { let url = this.configService.getHost() + "/api/v1/user/" + loginname; return this.http.get(url).map( res=>res.json().data ).catch(this.handleError); } // 验证 accessToken 的正确性 postUserLogin(accesstoken) { let url = this.configService.getHost() + "/api/v1/accesstoken"; let body = 'accesstoken=' + accesstoken; let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); return this.http.post(url, body, {headers: headers}).map( res=>res.json() ).catch(this.handleError); } // 获取未读消息数 getMessageCount(accessToken) { let url = this.configService.getHost() + "/api/v1/message/count?accesstoken=" + accessToken; return this.http.get(url).map( res=>res.json().data ).catch(this.handleError); } // 获取消息 getMessages(accessToken) { let url = this.configService.getHost() + "/api/v1/messages?accesstoken=" + accessToken; return this.http.get(url).map( res=>res.json().data ).catch(this.handleError); } // 标记全部已读 postMessageMark_all(accesstoken) { let url = this.configService.getHost() + "/api/v1/message/mark_all"; let body = 'accesstoken=' + accesstoken; let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); return this.http.post(url, body, {headers: headers}).map( res=>res.json() ).catch(this.handleError); } private handleError(error:Response) { console.log(error); return Observable.throw(error.json().error || 'Server Error'); } }
xiaohuidong99/Ionic2-IonicClub
app/pipe/TabNamePipe.ts
import {PipeTransform, Pipe} from "angular2/core"; import {CommonService} from "../services/CommonService"; @Pipe({ name: 'tabNamePipe' }) export class TabNamePipe implements PipeTransform { public tabList; constructor(private commonService:CommonService) { this.tabList = this.commonService.getTabs(); } transform(value:string, args:any[]) { for (var i in this.tabList) { if (this.tabList[i].value === value) { return this.tabList[i].label; } } } }
xiaohuidong99/Ionic2-IonicClub
app/pages/modal/myTopics/myTopics.ts
import {Page, NavParams, ViewController} from 'ionic-angular'; import {ConfigService} from "../../../services/ConfigService"; import {AmTimeAgoPipe} from '../../../pipe/AmTimeAgoPipe'; import {AvatarPipe} from "../../../pipe/avatarPipe"; @Page({ templateUrl: 'build/pages/modal/myTopics/myTopics.html', pipes: [AmTimeAgoPipe, AvatarPipe] }) export class MyTopicsPage { private myTopics = { recent_topics: [], recent_replies: [], } constructor(private viewCtrl:ViewController, private navParams:NavParams) { } ngOnInit() { this.myTopics = this.navParams.get('topics'); } dismiss() { this.viewCtrl.dismiss(); } }
xiaohuidong99/Ionic2-IonicClub
app/pipe/LinkPipe.ts
import {PipeTransform, Pipe} from "angular2/core"; @Pipe({ name: 'linkPipe' }) export class LinkPipe implements PipeTransform { constructor() { } transform(value:string, args:any[]) { if (typeof value === 'string') { var topicFullLinkRegex = /href="([\S]+)\/topic\/([\S]+)"/gi; var userFullLinkRegex = /href="([\S]+)\/user\/([\S]+)"/gi; var userLinkRegex = /href="\/user\/([\S]+)"/gi; var noProtocolSrcRegex = /src="\/\/([\S]+)"/gi; var externalLinkRegex = /href="((?!#\/user\/))[\S]+"/gi; return value .replace(topicFullLinkRegex, 'href="#/topicDetail/$2"') .replace(userFullLinkRegex, 'href="#/user/$2"') .replace(userLinkRegex, 'href="#/user/$1"') .replace(noProtocolSrcRegex, 'src="https://$1"') .replace(externalLinkRegex, "onClick=\"open('$1', '_blank', 'location=no')\"") } } }
xiaohuidong99/Ionic2-IonicClub
app/pages/topics/topics.ts
<filename>app/pages/topics/topics.ts import {Page, NavController, NavParams, Modal, Storage, LocalStorage, Events} from 'ionic-angular'; import {IonicService} from "../../services/IonicService"; import {ConfigService} from "../../services/ConfigService"; import {TabNamePipe} from "../../pipe/TabNamePipe"; import {AvatarPipe} from "../../pipe/avatarPipe"; import {AmTimeAgoPipe} from '../../pipe/AmTimeAgoPipe'; import {TopicAddPage} from "../modal/topicAdd/topicAdd"; import {LoginPage} from "../login/login"; import {AccountPage} from "../account/account"; @Page({ templateUrl: 'build/pages/topics/topics.html', providers: [IonicService, ConfigService], pipes: [AmTimeAgoPipe, TabNamePipe, AvatarPipe] }) export class TopicsPage { private topics = []; private local:LocalStorage; private rootPage:any = LoginPage; private badge:number = 0; //主题列表默认参数 private params = { page: 1, tab: 'all', limit: 20 }; constructor(private ionicService:IonicService, private nav:NavController, private navParams:NavParams, private events:Events) { if (navParams.get('tab')) { this.params.tab = navParams.get('tab'); } this.events.subscribe('badge', (data)=> { this.badge = data; }); this.events.subscribe('doRefresh', ()=> { this.params.page = 1; this.params.tab = 'all'; this.ionicService.getTopics(this.params).subscribe( data => { this.topics = data; this.params.page++; } ); }); this.local = new Storage(LocalStorage); } doInfinite(infiniteScroll) { setTimeout(() => { this.ionicService.getTopics(this.params) .subscribe( data => { this.topics = this.topics.concat(data); this.params.page++; } ); infiniteScroll.complete(); }, 500); // 延迟500ms } doRefresh(refresher) { this.params.page = 1; this.params.tab = 'all'; setTimeout(() => { this.ionicService.getTopics(this.params).subscribe( data => { this.topics = []; this.topics = data; this.params.page++; } ); refresher.complete(); }, 500);// 延迟500ms } ngOnInit() { this.ionicService.getTopics(this.params).subscribe( data => { this.topics = data; this.params.page++; } ); this.local.get('User').then(u=> { if (u) { this.rootPage = AccountPage; let user = JSON.parse(u); this.ionicService.getMessageCount(user.accesstoken).subscribe(data=> { this.badge = data }); } }); } addTopic() { let modal = Modal.create(TopicAddPage); this.nav.present(modal); } goTo() { this.local.get('User').then(u=> { if (u) { this.nav.push(AccountPage); } else { this.nav.push(LoginPage); } }); } }
xiaohuidong99/Ionic2-IonicClub
app/pipe/AvatarPipe.ts
import {PipeTransform, Pipe} from "angular2/core"; @Pipe({ name: 'avatarPipe' }) export class AvatarPipe implements PipeTransform { constructor() { } transform(value:string, args:any[]) { // add https protocol if (value) { value = value.replace("https://avatars.githubusercontent.com", "http://7xj5bc.com1.z0.glb.clouddn.com"); value = value + "&imageView2/2/w/120"; } return value; } }
xiaohuidong99/Ionic2-IonicClub
app/pages/login/login.ts
<reponame>xiaohuidong99/Ionic2-IonicClub<filename>app/pages/login/login.ts import {Page, Alert, NavController, Storage, LocalStorage, ViewController} from 'ionic-angular'; import {IonicService} from "../../services/IonicService"; import {ConfigService} from "../../services/ConfigService"; import {BarcodeScanner} from 'ionic-native'; import {AccountPage} from "../account/account"; import {AppVersion} from 'ionic-native'; @Page({ templateUrl: 'build/pages/login/login.html', providers: [IonicService, ConfigService] }) export class LoginPage { private local; private versionNumber; constructor(private viewCtrl:ViewController, private nav:NavController, private ionicService:IonicService) { this.local = new Storage(LocalStorage); } ngOnInit() { AppVersion.getVersionNumber().then(data=> { this.versionNumber = data; }); } login() { let confirm = Alert.create({ title: '扫码登录', message: 'PC登录 http://ionichina.com后,扫描设置页面的Access Token二维码即可完成登录', buttons: [ { text: '我知道了', handler: () => { BarcodeScanner.scan().then((barcodeData) => { let User = { accesstoken: '', loginname: '', avatar_url: '' } User.accesstoken = barcodeData.text; this.ionicService.postUserLogin(User.accesstoken).subscribe( data=> { User.loginname = data.loginname; User.avatar_url = data.avatar_url; this.local.set('User', JSON.stringify(User)); this.nav.push(AccountPage).then(()=> { let index = this.viewCtrl.index; this.nav.remove(index); }); }); }, (err) => { console.log(err); }); } } ] }); this.nav.present(confirm); } }
xiaohuidong99/Ionic2-IonicClub
app/pipe/AmTimeAgoPipe.ts
import {PipeTransform, Pipe} from "angular2/core"; @Pipe({ name: 'amTimeAgoPipe' }) export class AmTimeAgoPipe implements PipeTransform { constructor() { } transform(value:string, args:any[]) { if (value) { value = this.getDateDiff(value) } return value; } getDateDiff(pTime:string) { let result; let minute:number = 1000 * 60; let hour:number = minute * 60; let day:number = hour * 24; let month:number = day * 30; let now = new Date().getTime(); let old = new Date(pTime).getTime(); let diffValue = now - old; var monthC = diffValue / month; var weekC = diffValue / (7 * day); var dayC = diffValue / day; var hourC = diffValue / hour; var minC = diffValue / minute; if (monthC >= 1) { result = Math.round(monthC) + "个月前"; } else if (weekC >= 1) { result = Math.round(weekC) + "周前"; } else if (dayC >= 1) { result = Math.round(dayC) + "天前"; } else if (hourC >= 1) { result = Math.round(hourC) + "小时前"; } else if (minC >= 1) { result = Math.round(minC) + "分钟前"; } else result = "刚刚"; return result; } }
xiaohuidong99/Ionic2-IonicClub
app/pages/user/user.ts
import {Page, NavController, NavParams} from 'ionic-angular'; import {IonicService} from "../../services/IonicService"; import {ConfigService} from "../../services/ConfigService"; import {AmTimeAgoPipe} from '../../pipe/AmTimeAgoPipe'; import {AvatarPipe} from "../../pipe/avatarPipe"; import {DateFormatPipe} from "../../pipe/DateFormatPipe"; @Page({ templateUrl: 'build/pages/user/user.html', providers: [IonicService, ConfigService], pipes: [AmTimeAgoPipe,DateFormatPipe, AvatarPipe] }) export class UserPage { private loginname:string; private user = { avatar_url: '', loginname: '', score: '', create_at: '', recent_topics: [], recent_replies: [], collect_topics: [] }; constructor(private navParams:NavParams, private nav:NavController, private ionicService:IonicService) { } ngOnInit() { this.loginname = this.navParams.get('loginname'); this.ionicService.getUserByName(this.loginname).subscribe( data=> { this.user = data }); } }
andrewcaires/vue-fetch
src/vue-fetch.ts
import { EventEmitter, isDef } from '@andrewcaires/utils.js'; import Vue from 'vue'; export interface VueFetchOptions { url?: string; headers?: VueFetchHeaders; logging?: VueFetchLog; timeout?: number; } export interface VueFetchBody { json: boolean; parse: any; } export type VueFetchHeaders = { [key: string]: string } export interface VueFetchInit { url?: string; path: string; query?: VueFetchQuery; method: string; body?: any; headers?: VueFetchHeaders; timeout?: number; } export type VueFetchLog = (data: any) => void export type VueFetchQuery = { [key: string]: string } export interface VueFetchRequest { url: string; method: string body: any signal: AbortSignal; headers: VueFetchHeaders; } export interface VueFetchResponse { data?: any; error?: string; raw?: Response; } const DefaultOptions: VueFetchOptions = { headers: {}, timeout: 5000, }; let installed = false; export class VueFetch extends EventEmitter { private options: VueFetchOptions; constructor(options: VueFetchOptions = {}) { super(); this.options = { ...DefaultOptions, ...options }; } create(options: VueFetchOptions = {}) { return new VueFetch({ ...this.options, ...options }); } async del(path: string, query?: VueFetchQuery): Promise<VueFetchResponse> { return this.fetch({ method: 'delete', path, query }); } async get(path: string, query?: VueFetchQuery): Promise<VueFetchResponse> { return this.fetch({ method: 'get', path, query }); } async head(path: string, query?: VueFetchQuery): Promise<VueFetchResponse> { return this.fetch({ method: 'head', path, query }); } async patch(path: string, body: any, query?: VueFetchQuery): Promise<VueFetchResponse> { return this.fetch({ method: 'patch', path, query, body }); } async post(path: string, body: any, query?: VueFetchQuery): Promise<VueFetchResponse> { return this.fetch({ method: 'post', path, query, body }); } async put(path: string, body: any, query?: VueFetchQuery): Promise<VueFetchResponse> { return this.fetch({ method: 'put', path, query, body }); } async fetch(init: VueFetchInit): Promise<VueFetchResponse> { const request = this.request(init); const response: VueFetchResponse = {}; try { this.emit('before', request); response.raw = await fetch(request.url, request); response.data = await this.data(response.raw); if (!response.raw.ok) { response.error = response.raw.statusText; } this.emit('complete', response); this.options.logging && this.options.logging(response); } catch (e: any) { this.emit('error', e); response.error = e.message; this.options.logging && this.options.logging(e); } return response; } private data(response: Response) { const type = response.headers.get('Content-Type')?.toLowerCase() || ''; const text = type.indexOf('text/html') >= 0; const json = type.indexOf('application/json') >= 0; return !type || text ? response.text() : json ? response.json() : response.blob(); } private request({ url, path, query, method, body, headers, timeout }: VueFetchInit): VueFetchRequest { const params = this.query(query); url = this.url(url, path, params); method = method.toUpperCase(); const { json, parse } = this.body(body); headers = this.headers(headers); if (json) { headers['Content-Type'] = 'application/json'; } const signal = this.signal(timeout); return { url, method, body: parse, headers, signal }; } private body(body: any): VueFetchBody { const raw = typeof body === 'string' const json = !(body instanceof Blob || body instanceof FormData || raw); return { json, parse: json ? body ? JSON.stringify(body) : null : body }; } private headers(headers?: VueFetchHeaders) { return { ...this.options.headers, ...headers }; } private query(query?: VueFetchQuery): string | undefined { const keys = Object.keys(query || {}); const params = new URLSearchParams(); if (query) { keys.forEach((key) => params.set(key, query[key])); } return keys.length ? '?' + params.toString() : undefined } private signal(timeout?: number): AbortSignal { const controller = new AbortController; if (timeout || this.options.timeout) { setTimeout(() => controller.abort(), timeout || this.options.timeout); } return controller.signal; } private url(url?: string, path?: string, query?: string): string { url = url || this.options.url; return [url, path, query].filter(isDef).map((value) => { return value?.toString().replace(/(^\/+|\/+$)/mg, ''); }).join('/'); } static install(vue: any, options: VueFetchOptions = {}): void { if (installed) { return; } else { installed = true; } Vue.$fetch = new VueFetch(options); Vue.prototype.$fetch = Vue.$fetch; } } declare module 'vue/types/vue' { interface Vue { $fetch: VueFetch; } interface VueConstructor { $fetch: VueFetch; } } export default VueFetch;
c2d7fa/miscjs
src/spec.ts
<gh_stars>0 export type Rest<Xs extends any[]> = Xs extends [any, ...infer Ys] ? Ys : never; type LiteralIn<Ks extends string[]> = Ks[number]; type BasicTypes = { string: string; number: number; boolean: boolean; null: null; undefined: undefined; date: Date; }; const $_array = Symbol("arrayOf"); export const $array = <P extends Spec>(spec: P): [typeof $_array, P] => [$_array, spec]; const $_nullable = Symbol("nullable"); export const $nullable = <P extends Spec>(spec: P): [typeof $_nullable, P] => [$_nullable, spec]; export const $jsonDate = Symbol("jsonDate"); const $_literal = Symbol("literal"); export const $literal = <Ks extends readonly string[]>(options: Ks): [typeof $_literal, ...Ks] => [ $_literal, ...options, ]; const $_check = Symbol("check"); export const $check = <T>(f: (x: unknown) => x is T): [typeof $_check, (x: unknown) => x is T] => [$_check, f]; const $_or = Symbol("or"); export const $or = <Ps extends readonly Spec[]>(specs: Ps): [typeof $_or, Ps] => [$_or, specs]; export type Spec = | keyof BasicTypes | {[key: string]: Spec} | [typeof $_array, Spec] | [typeof $_nullable, Spec] | [typeof $_literal, ...string[]] | [typeof $_check, (x: unknown) => boolean] | [typeof $_or, readonly Spec[]]; export type Value<P> = P extends keyof BasicTypes ? BasicTypes[P] : P extends [typeof $_array, infer Q] ? Value<Q>[] : P extends [typeof $_literal, ...infer Ks] ? Ks extends string[] ? LiteralIn<Ks> : never : P extends [typeof $_nullable, infer Q] ? Value<Q> | null : P extends Record<infer K, Spec> ? {[L in K]: Value<P[L]>} : P extends [typeof $_check, (x: unknown) => x is infer T] ? T : P extends [typeof $_or, infer Qs] ? Qs extends readonly [] ? never : Qs extends readonly [infer R] ? Value<R> : Qs extends readonly [infer R, ...infer Rs] ? Value<R> | Value<[typeof $_or, Rs]> : never : never; export function isValid<P extends Spec>(spec: P, value: unknown): value is Value<P> { if (spec === "string") return typeof value === "string"; if (spec === "number") return typeof value === "number"; if (spec === "boolean") return typeof value === "boolean"; if (spec === "null") return value === null; if (spec === "undefined") return value === undefined; if (spec === "date") return value instanceof Date; if (spec instanceof Array && spec[0] === $_literal) { const validLiterals = spec.slice(1); if (typeof value !== "string") return false; return validLiterals.includes(value); } if (spec instanceof Array && spec[0] === $_nullable) { if (value === null) return true; return isValid(spec[1], value); } if (spec instanceof Array && spec[0] === $_array) { if (!(value instanceof Array)) return false; for (const subvalue of value) { if (!isValid(spec[1], subvalue)) return false; } return true; } if (spec instanceof Array && spec[0] === $_check) { return spec[1](value); } if (spec instanceof Array && spec[0] === $_or) { for (const subspec of spec[1]) { if (isValid(subspec, value)) return true; } return false; } if (typeof spec === "object") { if (typeof value !== "object") return false; if (value === null) return false; for (const key in spec) { if (!(key in value)) return false; // [TODO] Why don't types check below? if (!isValid(spec[key] as unknown as Spec, (value as any)[key])) return false; } return true; } return false; }
c2d7fa/miscjs
src/index.ts
<reponame>c2d7fa/miscjs export {default as choose} from "./choose"; export * as spec from "./spec"; export {get, set, update} from "./update"; // Returns `true` if the two arrays are equal, in the sense that they contain // the same elements at the same positions. If `eq` is given, it is used to // compare the elements, otherwise `===` is used. export function arrayEq<T>(a: T[], b: T[], eq?: (x: T, y: T) => boolean): boolean { const eq_ = eq ?? ((x, y) => x === y); if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) if (!eq_(a[i], b[i])) return false; return true; } // A variant of the built-in function `splice` that returns a new array rather // than modifying its input. export function splice<T>(a: T[], start: number, deleteCount?: number): T[]; export function splice<T>(a: T[], start: number, deleteCount: number, ...items: T[]): T[]; export function splice<T>(a: T[], start: number, deleteCount?: number, ...items: T[]): T[] { const result = [...a]; if (deleteCount !== undefined) { result.splice(start, deleteCount, ...items); } else { result.splice(start); } return result; } // Returns `true` if `a` has the element `x`, `false` otherwise. If `eq` is // given, it is used as the equality operator; otherwise, this is equivalent to // `a.includes(x)`. export function includesBy<T>(a: T[], x: T, eq?: (x: T, y: T) => boolean): boolean { const eq_ = eq ?? ((x, y) => x === y); for (const y of a) if (eq_(x, y)) return true; return false; } // Returns the first item in `a` equal to `x`. If `eq` is given, it is used as // the equality operator. export function indexOfBy<T>(a: T[], x: T, eq?: (x: T, y: T) => boolean): number | undefined { const eq_ = eq ?? ((x, y) => x === y); for (let i = 0; i < a.length; ++i) if (eq_(a[i], x)) return i; return undefined; } // Returns an identical object, but with the key `k` removed. export function removeKey<V>(o: {[x: string]: V}, k: string): {[x: string]: V} { const result = {...o}; delete result[k]; return result; } // Like `removeKey`, but takes a number as the key. export function removeKeyNumeric<V>(o: {[x: number]: V}, k: number): {[x: string]: V} { const result = {...o}; delete result[k]; return result; } // Remove the elements of `a` that are equal to `x`. When `eq` is given, use // this operator for equality. export function removeBy<T>(a: T[], x: T, eq?: (x: T, y: T) => boolean): T[] { const eq_ = eq ?? ((x, y) => x === y); return a.filter((y) => !eq_(x, y)); } // Returns the items of `a` that are not also in `a`. export function setMinus<T>(a: T[], b: T[]): T[] { let result = [...a]; for (const y of b) { result = removeBy(result, y); } return result; } // Takes a mapping of class names to booleans denoting whether each class is // enabled. Returns a string that can be used for the `class` attribute of an // element. export function classes(enabled: {[className: string]: boolean}): string { let enabledClasses = []; for (const className in enabled) { if (enabled[className]) enabledClasses.push(className); } return unwords(enabledClasses); } // Returns a string containing the given words separated by spaces. export function unwords(words: string[]): string { let result = ""; for (const word of words) { if (result == "") result = word; else result += " " + word; } return result; } // Returns `true` of `b` implies `c` (in the sense of a material conditional), // `false` otherwise. export function implies(b: boolean, c: boolean) { return !b || (b && c); } // Capitalizes the first character of the string. export function capitalize(s: string) { return s.substr(0, 1).toUpperCase() + s.substr(1); } // Returns `text` truncated to the length `maxLength`. If the string is too // large, three dots are inserted at the end such that the total length of the // string is at most `maxLength`. export function truncateEllipsis(text: string, maxLength: number) { if (text.length >= maxLength) { return text.substr(0, maxLength - 3) + "..."; } else { return text; } }
c2d7fa/miscjs
src/index.test.ts
/// <reference types="jest" /> import {implies} from "./index"; describe("implies", () => { it("false implies anything", () => { expect(implies(false, true)).toBeTruthy(); expect(implies(false, false)).toBeTruthy(); }); it("true only implies true", () => { expect(implies(true, true)).toBeTruthy(); expect(implies(true, false)).toBeFalsy(); }) });
c2d7fa/miscjs
src/update.test.ts
/// <reference types="@types/jest" /> import {get, set, update} from "./update"; describe("getting a value", () => { test("at an empty path is just the value itself", () => { expect(get({a: 1}, "")).toEqual({a: 1}); }); test("at a path with one key is the value at that key", () => { expect(get({a: 1}, "a")).toEqual(1); }); test("a path with multiple keys is the value at the end of the path", () => { expect(get({a: {b: {c: {d: 1, e: 2, f: 3}, g: 4}}}, "a.b.c.d")).toEqual(1); }); test("when the path has a null, it returns null", () => { expect(get({a: null} as {a: {b: number} | null}, "a.b")).toEqual(null); }); test("when the path has an undefined value, it returns undefined", () => { expect(get({a: undefined} as {a: {b: number} | undefined}, "a.b")).toEqual(undefined); }); }); describe("replacing a value", () => { test("at an empty path just returns the new value", () => { expect(set({a: 1}, "", {a: 3})).toEqual({a: 3}); }); test("at a path with one key replaces the value at that key", () => { expect(set({a: 1, b: 2, c: {d: 3}}, "a", -1)).toEqual({a: -1, b: 2, c: {d: 3}}); }); test("at a deeply nested key replaces the value at that key", () => { expect(set({a: {b: {c: 1, d: 2}, e: 3}, f: 4}, "a.b.c", -1)).toEqual({a: {b: {c: -1, d: 2}, e: 3}, f: 4}); }); describe("with array path", () => { test("with path '[]', every item in array is replaced with the same value", () => { expect(set([1, 2, 3, 4], "[]", -1)).toEqual([-1, -1, -1, -1]); }); test("key path before array replaces each value in the inner array", () => { expect(set({a: {b: [1, 2, 3]}}, "a.b[]", -1)).toEqual({a: {b: [-1, -1, -1]}}); }); test("with path inside array, those subpaths are replaced for each array value", () => { expect( set( { a: [ {b: 1, c: 1}, {b: 2, c: 2}, {b: 3, c: 3}, ], }, "a[b]", -1, ), ).toEqual({ a: [ {b: -1, c: 1}, {b: -1, c: 2}, {b: -1, c: 3}, ], }); }); }); }); describe("updating values", () => { describe("with array path", () => { test("with path '[]', every item in array is updated individually", () => { expect(update([1, 2, 3, 4], "[]", (x) => x + 10)).toEqual([11, 12, 13, 14]); }); test("key path before array updates each value in the inner array", () => { expect(update({a: {b: [1, 2, 3]}}, "a.b[]", (x) => x + 10)).toEqual({a: {b: [11, 12, 13]}}); }); test("with path inside array, those subpaths are updated for each array value", () => { expect( update( { a: [ {b: 1, c: 1}, {b: 2, c: 2}, {b: 3, c: 3}, ], }, "a[b]", (x) => x + 10, ), ).toEqual({ a: [ {b: 11, c: 1}, {b: 12, c: 2}, {b: 13, c: 3}, ], }); }); }); });
c2d7fa/miscjs
src/choose.ts
<reponame>c2d7fa/miscjs export default function choose<R>( choice: string, options: {[key: string]: () => R}, ): {found: true; value: R} | {found: false; value: undefined} { const found = choice in options; if (found) { return {found, value: options[choice]()}; } else { return {found, value: undefined}; } }
c2d7fa/miscjs
src/spec.test.ts
/// <reference types="@types/jest" /> import {$array, $check, $literal, $nullable, $or, isValid} from "./spec"; describe("basic types", () => { test("strings are strings", () => { expect(isValid("string", "this is a string")).toBeTruthy(); }); test("numbers are numbers", () => { expect(isValid("number", 0.5)).toBeTruthy(); }); test("null is null", () => { expect(isValid("null", null)).toBeTruthy(); }); test("undefined is undefined", () => { expect(isValid("undefined", undefined)).toBeTruthy(); }); test("booleans are booleans", () => { expect(isValid("boolean", true)).toBeTruthy(); }); test("dates are dates", () => { expect(isValid("date", new Date("2021-07-05T17:08:35Z"))).toBeTruthy(); }); }); describe("literals", () => { test("if a string is one of the given literals, it's valid", () => { expect(isValid($literal(["valid1", "valid2"]), "valid1")).toBeTruthy(); }); test("if a string is not one of the given literals, it's invalid", () => { expect(isValid($literal(["valid1", "valid2"]), "invalid")).toBeFalsy(); }); test("a non-string is never a valid literal, even if it would convert to the string representation", () => { expect(isValid($literal(["1"]), 1)).toBeFalsy(); }); }); describe("nullable", () => { test("null is a valid nullable type", () => { expect(isValid($nullable("number"), null)).toBeTruthy(); }); test("a non-null value is invalid when the inner spec doesn't match", () => { expect(isValid($nullable("number"), "this is a string")).toBeFalsy(); }); test("a non-null value is valid when the inner spec matches", () => { expect(isValid($nullable("number"), 0.5)).toBeTruthy(); }); }); describe("objects", () => { test("an empty object type matches any object", () => { expect(isValid({}, {a: 0.5})).toBeTruthy(); }); test("no non-objects are valid objects", () => { expect(isValid({}, 0.5)).toBeFalsy(); }); test("null is not a valid object", () => { expect(isValid({}, null)).toBeFalsy(); }); test("if an object is missing keys, it's invalid", () => { expect(isValid({a: "number", b: "string"}, {a: 0.5})).toBeFalsy(); }); test("if a key doesn't match the type, the object is invalid", () => { expect(isValid({a: "number", b: "string"}, {a: 0.5, b: -0.5})).toBeFalsy(); }); }); describe("arrays", () => { test("an empty array is always a valid array", () => { expect(isValid($array("number"), [])).toBeTruthy(); }); test("a non-array is never a valid array", () => { expect(isValid($array("number"), "[]")).toBeFalsy(); expect(isValid($array("number"), null)).toBeFalsy(); expect(isValid($array("number"), {})).toBeFalsy(); expect(isValid($array("number"), 0.5)).toBeFalsy(); }); test("if any array element doesn't match, the array is invalid", () => { expect(isValid($array("number"), [0, 1, "2", 3])).toBeFalsy(); }); test("if all array elements match, the array is valid", () => { expect(isValid($array("number"), [0, 1, 2, 3])).toBeTruthy(); }); }); describe("custom checks", () => { test("if the check fails, the value is invalid", () => { function isLongString(x: unknown): x is string { return isValid("string", x) && x.length > 3; } expect(isValid($check(isLongString), "ab")).toBeFalsy(); }); test("if the check succeeds, the value is valid", () => { function isLongString(x: unknown): x is string { return isValid("string", x) && x.length > 3; } expect(isValid($check(isLongString), "abcd")).toBeTruthy(); }); }); describe("or", () => { test("with no arguments, a value is always invalid", () => { expect(isValid($or([]), 0.5)).toBeFalsy(); }); test("with one argument, a value is valid if it matches the inner type", () => { expect(isValid($or(["number"]), 0.5)).toBeTruthy(); }); test("with one argument, a value is invalid if it doesn't match the inner type", () => { expect(isValid($or(["string"]), 0.5)).toBeFalsy(); }); test("with many arguments, a value is valid if it matches any one", () => { expect( isValid($or(["number", {value: "boolean"}, {value: "string"}]), { value: true, }), ).toBeTruthy(); }); test("with many arguments, a value is invalid if it matches none", () => { expect( isValid($or(["number", {value: "boolean"}, {value: "string"}]), { value: 0.5, }), ).toBeFalsy(); }); });
c2d7fa/miscjs
src/update.ts
<filename>src/update.ts type GetPath<O, P> = P extends "" ? O : P extends `${infer Left}.${infer Right}` ? | GetPath<NonNullable<GetPath<O, Left>>, Right> | (null extends GetPath<O, Left> ? null : never) | (undefined extends GetPath<O, Left> ? undefined : never) : P extends keyof O ? O[P] : never; type SetPath<O, P> = P extends "" ? O : P extends `${infer Left}[${infer Right}]` ? NonNullable<SetPath<O, Left>> extends Array<infer T> ? SetPath<NonNullable<T>, Right> : never : P extends `${infer Left}.${infer Right}` ? SetPath<NonNullable<SetPath<O, Left>>, Right> : P extends keyof O ? O[P] : never; export function get<O, P extends string>(o: O, path: P): GetPath<O, P> { let result: any = o; for (const segment of path.split(".")) { if (segment === "") continue; if (result === null || result === undefined) continue; if (!(segment in result)) throw "invalid segment: " + segment; result = result[segment]; } return result; } export function set<O, P extends string>(o: O, path: P, value: SetPath<O, P>): O { return update(o, path, () => value); } export type UpdateFunction<O, P extends string> = (x: SetPath<O, P>) => SetPath<O, P>; export function update<O, P extends string>(o: O, path: P, f: UpdateFunction<O, P>): O { if (path === "") return f(o as any) as any; const dotMatch = path.match(/([^[.]*)\.(.*)/); if (dotMatch) { const key = dotMatch[1]; if (!(key in o)) throw "invalid path segment: " + key; return {...o, [key]: update((o as any)[key as keyof O], dotMatch[2] as any, f)}; } const arrayMatch = path.match(/([^[.]*)\[(.*)\]/); if (arrayMatch) { const key = arrayMatch[1]; if (key !== "") { if (!(key in o)) throw "invalid path segment: " + key; return {...o, [key]: (o as any)[key as keyof O].map((x: any) => update(x, arrayMatch[2] as any, f))}; } else { return (o as any).map((x: any) => update(x, arrayMatch[2] as any, f)); } } return update(o, (path + ".") as any, f); }
c2d7fa/miscjs
src/choose.test.ts
<gh_stars>0 /// <reference types="jest" /> import choose from "./choose"; describe("choose", () => { describe("a valid option", () => { const result = choose("valid", { valid() { return 1; }, }); it("is found", () => { expect(result.found).toBe(true); }); it("is evaluated for its value", () => { expect(result.value).toBe(1); }); }); describe("an invalid option", () => { const result = choose("invalid", { valid() { return 1; }, }); it("isn't found", () => { expect(result.found).toBe(false); }); it("has no value", () => { expect(result.value).toBeUndefined(); }); }); describe("an option", () => { it("is evaluated only if chosen", () => { let evaluated = 0; const result = choose("invalid", { valid() { evaluated++; }, }); expect(result.found).toBe(false); expect(evaluated).toBe(0); }); it("is evaluated exactly once if chosen", () => { let evaluated = 0; const result = choose("valid", { valid() { evaluated++; }, }); expect(result.found).toBe(true); expect(evaluated).toBe(1); }); }); });
gzigzigzeo/protobuf-as
src/walker_as/prettify.ts
<gh_stars>1-10 import { File } from '../walker/index.js'; import prettier from 'prettier'; // Options for prettier, TODO: move to WalkerAS const prettierOptions: prettier.Options = { parser: 'typescript', tabWidth: 2, }; export function prettify(files: File[]): File[] { return files.map((file: File) => <File>{name: file.name, content: prettier.format(file.content, prettierOptions)}); }
gzigzigzeo/protobuf-as
tests/__fixtures__/build/nested.d.ts
<gh_stars>1-10 /** * tests/__fixtures__/assembly/nested/encode * @param obj `tests/__fixtures__/as_proto/nested/nested/Person` * @returns `~lib/arraybuffer/ArrayBuffer` */ export declare function encode(obj: __Record3<undefined>): ArrayBuffer; /** * tests/__fixtures__/assembly/nested/decode * @param buffer `~lib/arraybuffer/ArrayBuffer` * @returns `tests/__fixtures__/as_proto/nested/nested/Person` */ export declare function decode(buffer: ArrayBuffer): __Record3<never>; /** * tests/__fixtures__/assembly/nested/size * @param obj `tests/__fixtures__/as_proto/nested/nested/Person` * @returns `u32` */ export declare function size(obj: __Record3<undefined>): number; /** tests/__fixtures__/as_proto/nested/nested/Id */ declare interface __Record4<TOmittable> { /** @type `~lib/string/String` */ Number: string; /** @type `~lib/string/String` */ Serial: string; } /** tests/__fixtures__/as_proto/nested/nested/Person */ declare interface __Record3<TOmittable> { /** @type `~lib/string/String` */ Name: string; /** @type `~lib/string/String` */ Surname: string; /** @type `i32` */ Age: number | TOmittable; /** @type `f32` */ Weight: number | TOmittable; /** @type `tests/__fixtures__/as_proto/nested/nested/Id` */ Id: __Record4<undefined>; }
gzigzigzeo/protobuf-as
tests/__fixtures__/ts_proto/elementaries/main.ts
<reponame>gzigzigzeo/protobuf-as<gh_stars>1-10 /* eslint-disable */ import Long from 'long'; import _m0 from 'protobufjs/minimal.js'; export const protobufPackage = ''; export enum Enum { Zero = 0, One = 1, Two = 2, UNRECOGNIZED = -1, } export function enumFromJSON(object: any): Enum { switch (object) { case 0: case 'Zero': return Enum.Zero; case 1: case 'One': return Enum.One; case 2: case 'Two': return Enum.Two; case -1: case 'UNRECOGNIZED': default: return Enum.UNRECOGNIZED; } } export function enumToJSON(object: Enum): string { switch (object) { case Enum.Zero: return 'Zero'; case Enum.One: return 'One'; case Enum.Two: return 'Two'; default: return 'UNKNOWN'; } } export interface Elementaries { Double: number; Float: number; Int32: number; UInt32: number; SInt32: number; Fixed32: number; SFixed32: number; Int64: number; UInt64: number; SInt64: number; Fixed64: number; SFixed64: number; Bool: boolean; Enum: Enum; Bytes: Uint8Array; String: string; EmptyBytes: Uint8Array; EmptyString: string; EmptyInt64: number; EmptyInt32: number; EmptyBool: boolean; } function createBaseElementaries(): Elementaries { return { Double: 0, Float: 0, Int32: 0, UInt32: 0, SInt32: 0, Fixed32: 0, SFixed32: 0, Int64: 0, UInt64: 0, SInt64: 0, Fixed64: 0, SFixed64: 0, Bool: false, Enum: 0, Bytes: new Uint8Array(), String: '', EmptyBytes: new Uint8Array(), EmptyString: '', EmptyInt64: 0, EmptyInt32: 0, EmptyBool: false, }; } export const Elementaries = { encode( message: Elementaries, writer: _m0.Writer = _m0.Writer.create(), ): _m0.Writer { if (message.Double !== 0) { writer.uint32(9).double(message.Double); } if (message.Float !== 0) { writer.uint32(21).float(message.Float); } if (message.Int32 !== 0) { writer.uint32(24).int32(message.Int32); } if (message.UInt32 !== 0) { writer.uint32(32).uint32(message.UInt32); } if (message.SInt32 !== 0) { writer.uint32(40).sint32(message.SInt32); } if (message.Fixed32 !== 0) { writer.uint32(53).fixed32(message.Fixed32); } if (message.SFixed32 !== 0) { writer.uint32(61).sfixed32(message.SFixed32); } if (message.Int64 !== 0) { writer.uint32(64).int64(message.Int64); } if (message.UInt64 !== 0) { writer.uint32(72).uint64(message.UInt64); } if (message.SInt64 !== 0) { writer.uint32(80).sint64(message.SInt64); } if (message.Fixed64 !== 0) { writer.uint32(89).fixed64(message.Fixed64); } if (message.SFixed64 !== 0) { writer.uint32(97).sfixed64(message.SFixed64); } if (message.Bool === true) { writer.uint32(104).bool(message.Bool); } if (message.Enum !== 0) { writer.uint32(112).int32(message.Enum); } if (message.Bytes.length !== 0) { writer.uint32(122).bytes(message.Bytes); } if (message.String !== '') { writer.uint32(130).string(message.String); } if (message.EmptyBytes.length !== 0) { writer.uint32(138).bytes(message.EmptyBytes); } if (message.EmptyString !== '') { writer.uint32(146).string(message.EmptyString); } if (message.EmptyInt64 !== 0) { writer.uint32(152).int64(message.EmptyInt64); } if (message.EmptyInt32 !== 0) { writer.uint32(160).int64(message.EmptyInt32); } if (message.EmptyBool === true) { writer.uint32(168).bool(message.EmptyBool); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Elementaries { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = createBaseElementaries(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.Double = reader.double(); break; case 2: message.Float = reader.float(); break; case 3: message.Int32 = reader.int32(); break; case 4: message.UInt32 = reader.uint32(); break; case 5: message.SInt32 = reader.sint32(); break; case 6: message.Fixed32 = reader.fixed32(); break; case 7: message.SFixed32 = reader.sfixed32(); break; case 8: message.Int64 = longToNumber(reader.int64() as Long); break; case 9: message.UInt64 = longToNumber(reader.uint64() as Long); break; case 10: message.SInt64 = longToNumber(reader.sint64() as Long); break; case 11: message.Fixed64 = longToNumber(reader.fixed64() as Long); break; case 12: message.SFixed64 = longToNumber(reader.sfixed64() as Long); break; case 13: message.Bool = reader.bool(); break; case 14: message.Enum = reader.int32() as any; break; case 15: message.Bytes = reader.bytes(); break; case 16: message.String = reader.string(); break; case 17: message.EmptyBytes = reader.bytes(); break; case 18: message.EmptyString = reader.string(); break; case 19: message.EmptyInt64 = longToNumber(reader.int64() as Long); break; case 20: message.EmptyInt32 = longToNumber(reader.int64() as Long); break; case 21: message.EmptyBool = reader.bool(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Elementaries { return { Double: isSet(object.Double) ? Number(object.Double) : 0, Float: isSet(object.Float) ? Number(object.Float) : 0, Int32: isSet(object.Int32) ? Number(object.Int32) : 0, UInt32: isSet(object.UInt32) ? Number(object.UInt32) : 0, SInt32: isSet(object.SInt32) ? Number(object.SInt32) : 0, Fixed32: isSet(object.Fixed32) ? Number(object.Fixed32) : 0, SFixed32: isSet(object.SFixed32) ? Number(object.SFixed32) : 0, Int64: isSet(object.Int64) ? Number(object.Int64) : 0, UInt64: isSet(object.UInt64) ? Number(object.UInt64) : 0, SInt64: isSet(object.SInt64) ? Number(object.SInt64) : 0, Fixed64: isSet(object.Fixed64) ? Number(object.Fixed64) : 0, SFixed64: isSet(object.SFixed64) ? Number(object.SFixed64) : 0, Bool: isSet(object.Bool) ? Boolean(object.Bool) : false, Enum: isSet(object.Enum) ? enumFromJSON(object.Enum) : 0, Bytes: isSet(object.Bytes) ? bytesFromBase64(object.Bytes) : new Uint8Array(), String: isSet(object.String) ? String(object.String) : '', EmptyBytes: isSet(object.EmptyBytes) ? bytesFromBase64(object.EmptyBytes) : new Uint8Array(), EmptyString: isSet(object.EmptyString) ? String(object.EmptyString) : '', EmptyInt64: isSet(object.EmptyInt64) ? Number(object.EmptyInt64) : 0, EmptyInt32: isSet(object.EmptyInt32) ? Number(object.EmptyInt32) : 0, EmptyBool: isSet(object.EmptyBool) ? Boolean(object.EmptyBool) : false, }; }, toJSON(message: Elementaries): unknown { const obj: any = {}; message.Double !== undefined && (obj.Double = message.Double); message.Float !== undefined && (obj.Float = message.Float); message.Int32 !== undefined && (obj.Int32 = Math.round(message.Int32)); message.UInt32 !== undefined && (obj.UInt32 = Math.round(message.UInt32)); message.SInt32 !== undefined && (obj.SInt32 = Math.round(message.SInt32)); message.Fixed32 !== undefined && (obj.Fixed32 = Math.round(message.Fixed32)); message.SFixed32 !== undefined && (obj.SFixed32 = Math.round(message.SFixed32)); message.Int64 !== undefined && (obj.Int64 = Math.round(message.Int64)); message.UInt64 !== undefined && (obj.UInt64 = Math.round(message.UInt64)); message.SInt64 !== undefined && (obj.SInt64 = Math.round(message.SInt64)); message.Fixed64 !== undefined && (obj.Fixed64 = Math.round(message.Fixed64)); message.SFixed64 !== undefined && (obj.SFixed64 = Math.round(message.SFixed64)); message.Bool !== undefined && (obj.Bool = message.Bool); message.Enum !== undefined && (obj.Enum = enumToJSON(message.Enum)); message.Bytes !== undefined && (obj.Bytes = base64FromBytes( message.Bytes !== undefined ? message.Bytes : new Uint8Array(), )); message.String !== undefined && (obj.String = message.String); message.EmptyBytes !== undefined && (obj.EmptyBytes = base64FromBytes( message.EmptyBytes !== undefined ? message.EmptyBytes : new Uint8Array(), )); message.EmptyString !== undefined && (obj.EmptyString = message.EmptyString); message.EmptyInt64 !== undefined && (obj.EmptyInt64 = Math.round(message.EmptyInt64)); message.EmptyInt32 !== undefined && (obj.EmptyInt32 = Math.round(message.EmptyInt32)); message.EmptyBool !== undefined && (obj.EmptyBool = message.EmptyBool); return obj; }, fromPartial<I extends Exact<DeepPartial<Elementaries>, I>>( object: I, ): Elementaries { const message = createBaseElementaries(); message.Double = object.Double ?? 0; message.Float = object.Float ?? 0; message.Int32 = object.Int32 ?? 0; message.UInt32 = object.UInt32 ?? 0; message.SInt32 = object.SInt32 ?? 0; message.Fixed32 = object.Fixed32 ?? 0; message.SFixed32 = object.SFixed32 ?? 0; message.Int64 = object.Int64 ?? 0; message.UInt64 = object.UInt64 ?? 0; message.SInt64 = object.SInt64 ?? 0; message.Fixed64 = object.Fixed64 ?? 0; message.SFixed64 = object.SFixed64 ?? 0; message.Bool = object.Bool ?? false; message.Enum = object.Enum ?? 0; message.Bytes = object.Bytes ?? new Uint8Array(); message.String = object.String ?? ''; message.EmptyBytes = object.EmptyBytes ?? new Uint8Array(); message.EmptyString = object.EmptyString ?? ''; message.EmptyInt64 = object.EmptyInt64 ?? 0; message.EmptyInt32 = object.EmptyInt32 ?? 0; message.EmptyBool = object.EmptyBool ?? false; return message; }, }; declare var self: any | undefined; declare var window: any | undefined; declare var global: any | undefined; var globalThis: any = (() => { if (typeof globalThis !== 'undefined') return globalThis; if (typeof self !== 'undefined') return self; if (typeof window !== 'undefined') return window; if (typeof global !== 'undefined') return global; throw 'Unable to locate global object'; })(); const atob: (b64: string) => string = globalThis.atob || ((b64) => globalThis.Buffer.from(b64, 'base64').toString('binary')); function bytesFromBase64(b64: string): Uint8Array { const bin = atob(b64); const arr = new Uint8Array(bin.length); for (let i = 0; i < bin.length; ++i) { arr[i] = bin.charCodeAt(i); } return arr; } const btoa: (bin: string) => string = globalThis.btoa || ((bin) => globalThis.Buffer.from(bin, 'binary').toString('base64')); function base64FromBytes(arr: Uint8Array): string { const bin: string[] = []; for (const byte of arr) { bin.push(String.fromCharCode(byte)); } return btoa(bin.join('')); } type Builtin = | Date | Function | Uint8Array | string | number | boolean | undefined; export type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends { $case: string } ? { [K in keyof Omit<T, '$case'>]?: DeepPartial<T[K]> } & { $case: T['$case']; } : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> } : Partial<T>; type KeysOfUnion<T> = T extends T ? keyof T : never; export type Exact<P, I extends P> = P extends Builtin ? P : P & { [K in keyof P]: Exact<P[K], I[K]> } & Record< Exclude<keyof I, KeysOfUnion<P>>, never >; function longToNumber(long: Long): number { if (long.gt(Number.MAX_SAFE_INTEGER)) { throw new globalThis.Error( 'Value is larger than Number.MAX_SAFE_INTEGER', ); } return long.toNumber(); } if (_m0.util.Long !== Long) { _m0.util.Long = Long as any; _m0.configure(); } function isSet(value: any): boolean { return value !== null && value !== undefined; }
gzigzigzeo/protobuf-as
tests/__fixtures__/build/lists.d.ts
/** * tests/__fixtures__/assembly/lists/encode * @param obj `tests/__fixtures__/as_proto/lists/lists/Lists` * @returns `~lib/arraybuffer/ArrayBuffer` */ export declare function encode(obj: __Record3<undefined>): ArrayBuffer; /** * tests/__fixtures__/assembly/lists/decode * @param buffer `~lib/arraybuffer/ArrayBuffer` * @returns `tests/__fixtures__/as_proto/lists/lists/Lists` */ export declare function decode(buffer: ArrayBuffer): __Record3<never>; /** * tests/__fixtures__/assembly/lists/size * @param obj `tests/__fixtures__/as_proto/lists/lists/Lists` * @returns `u32` */ export declare function size(obj: __Record3<undefined>): number; /** tests/__fixtures__/as_proto/lists/lists/Message */ declare interface __Record8<TOmittable> { /** @type `~lib/string/String` */ String: string; } /** tests/__fixtures__/as_proto/lists/lists/Lists */ declare interface __Record3<TOmittable> { /** @type `~lib/array/Array<u32>` */ Enums: Array<number>; /** @type `~lib/array/Array<~lib/string/String>` */ Strings: Array<string>; /** @type `~lib/array/Array<~lib/array/Array<u8>>` */ Bytes: Array<Array<number>>; /** @type `~lib/array/Array<tests/__fixtures__/as_proto/lists/lists/Message>` */ Messages: Array<__Record8<undefined>>; /** @type `~lib/array/Array<i32>` */ Ints: Array<number>; }
gzigzigzeo/protobuf-as
tests/__fixtures__/assembly/nested.ts
import { Person } from '../as_proto/nested/nested'; export function encode(obj: Person): ArrayBuffer { return obj.encode() } export function decode(buffer: ArrayBuffer): Person { return Person.decode(buffer) } export function size(obj: Person): u32 { return obj.size() }
gzigzigzeo/protobuf-as
src/walker_as/namespace_single_file.ts
import { decorated } from "../proto/index.js"; import { Writer } from "./index.js"; /** * Namespace code blocks */ export class NamespaceSingleFile { constructor(private p:Writer) {} start(ns:decorated.Namespace) { if (ns.name == "") { return } ns.name.split(".").forEach(n => this.p(`export namespace ${n} {`)) } finish(ns:decorated.Namespace) { if (ns.name == "") { return } ns.name.split(".").forEach(n => this.p(`} // ${n}`)) } }
gzigzigzeo/protobuf-as
src/walker_as/size.ts
import { decorated } from '../proto/index.js'; import { Writer, GlobalsRegistry } from './index.js'; import { getTypeInfo, TypeInfo } from './type_info.js'; import { relativeName, embedNamespace } from './internal.js'; /** * Generates message size() and __size helper methods */ export class Size { private sizer = 'Sizer'; constructor( private p: Writer, private globals: GlobalsRegistry ) { this.sizer = [embedNamespace, 'Sizer'].join('.'); } start() { this.p(` public size():u32 { let size:u32 = 0; `); } field(field: decorated.Field) { switch (field.kind) { case 'field_elementary': this.elementary(field); break; case 'field_elementary_repeated': if (field.packed) { this.elementaryRepeatedPacked(field); } else { this.elementaryRepeated(field); } break; case 'field_message': this.message(field); break; case 'field_message_repeated': this.messageRepeated(field); break; case 'field_map': case 'field_map_message': this.map(field); break; } } finish() { this.p(` return size; } `); } private tagSize(field: decorated.Field): number { return this.valueSize((field.number << 3) | field.wireType); } // Returns the expression which calculates the length of a constant private length(varName: string): string { return `${this.sizer}.varint64(${varName})`; } // Returns the expression which calculates an elementary value size private elementarySize( field: decorated.FieldElementary | decorated.FieldElementaryRepeated, type: TypeInfo, varName: string, tag = true, // Caclculate tag size (false for packed array elements) skipZeroValue = true, // If true, zero length strings and zero values are not sized (false for lists) ): string { const el = []; // If the tag is required if (tag) { el.push(this.tagSize(field)); } // If a field is a string or bytes array, it is taken into account only when it's non empty // and is calculated at runtime if (field.isCollection) { el.push(this.length(`${varName}.length`), `${varName}.length`); // size = size of a tag + size of a length + length itself if (skipZeroValue) { return `${varName}.length > 0 ? ${el.join(' + ')} : 0`; } return el.join(' + '); } el.push( type.fixedSize ? type.fixedSize.toString() : `${this.sizer}.${type.method}(${varName})`, ); return skipZeroValue ? `${varName} == 0 ? 0 : ${el.join(' + ')}` : el.join(' + '); } // Elementary non repeated private elementary(field: decorated.FieldElementary) { const type = getTypeInfo(field); const s = this.elementarySize(field, type, `this.${field.name}`); if (s != '') { this.p(`size += ${s}`); } } // Elementary repeated private elementaryRepeated(field: decorated.FieldElementaryRepeated) { const type = getTypeInfo(field); const name = `__size_${type.method}_repeated`; this.globals.registerGlobal( name, ` function ${name}(value: ${type.collectionTypeName}): u32 { let size:u32 = 0; for (let n:i32 = 0; n < value.length; n++) { size += ${this.elementarySize( field, type, `value[n]`, true, false, )} } return size; } `, ); this.p(` size += ${name}(this.${field.name}); `); } // Elementary repeated, packed private elementaryRepeatedPacked(field: decorated.FieldElementaryRepeated) { const type = getTypeInfo(field); const name = `__size_${type.method}_repeated_packed`; this.globals.registerGlobal( name, ` function ${name}(value: ${type.collectionTypeName}): u32 { let size:u32 = 0; for (let n:i32 = 0; n < value.length; n++) { size += ${this.elementarySize( field, type, `value[n]`, false, false, )} } return size; } `, ); this.p(` if (this.${field.name}.length > 0) { const packedSize = ${name}(this.${field.name}); if (packedSize > 0) { size += ${this.tagSize(field)} + ${this.length( 'packedSize', )} + packedSize } } `); } // Singular message (if it's size > 0) private message(field: decorated.FieldMessage) { const type = getTypeInfo(field); const f = `this.${field.name}`; this.p(` if (${f} != null) { const f:${type.typeName} = ${f} as ${type.typeName}; const messageSize = f.size(); if (messageSize > 0) { size += ${this.tagSize(field)} + ${this.length( 'messageSize', )} + messageSize } } `); } // Repeated message private messageRepeated(field: decorated.Field) { const f = `this.${field.name}`; this.p(` for (let n:i32 = 0; n < ${f}.length; n++) { const messageSize = ${f}[n].size(); if (messageSize > 0) { size += ${this.tagSize(field)} + ${this.length( 'messageSize', )} + messageSize } } `); } private map(field: decorated.FieldMap | decorated.FieldMapMessage) { const type = getTypeInfo(field); const f = `this.${field.name}`; const keyTypeInfo = type.keyTypeInfo as TypeInfo; const valueTypeInfo = type.valueTypeInfo as TypeInfo; const name = `__sizeMapEntry_${relativeName( keyTypeInfo.typeName as string, )}_${relativeName(valueTypeInfo.typeName as string)}`; // Returns size of a map item when it's elementary => elementary if (field.value.kind == 'field_elementary') { this.globals.registerGlobal( name, ` function ${name}(key: ${keyTypeInfo.typeName}, value: ${ valueTypeInfo.typeName }): u32 { return (${this.elementarySize( field.key, keyTypeInfo, 'key', )}) + (${this.elementarySize( field.value, valueTypeInfo, 'value', )}); } `, ); } else { // Otherwise, that's a map of elementary => message this.globals.registerGlobal( name, ` function ${name}(key: ${keyTypeInfo.typeName}, value: ${ valueTypeInfo.typeName }): u32 { const keySize = ${this.elementarySize( field.key, keyTypeInfo, 'key', )}; const valueSize = value.size(); if (valueSize == 0) { return keySize; } return keySize + ${this.tagSize( field.value, )} + ${this.length('valueSize')} + valueSize; } `, ); } this.p(` if (${f}.size > 0) { const keys = ${f}.keys() for (let i = 0; i < keys.length; i++) { const key = keys[i] const value = ${f}.get(key) const itemSize = ${name}(key, value) if (itemSize > 0) { size += ${this.tagSize(field)} + ${this.length( 'itemSize', )} + itemSize; } } } `); } // Returns size of a value, that's the TS counterpart of the AS sizer method private valueSize(value: number) { return value < 128 ? 1 // 2^7 : value < 16384 ? 2 // 2^14 : value < 2097152 ? 3 // 2^21 : value < 268435456 ? 4 // 2^28 : value < 34359738368 ? 5 // 2^35 : value < 4398046511104 ? 6 // 2^42 : value < 562949953421312 ? 7 // 2^49 : value < 72057594037927936 ? 8 // 2^56 : value < 9223372036854775808 ? 9 // 2^63 : 10; } }
gzigzigzeo/protobuf-as
tests/__fixtures__/build/complex_struct.d.ts
<reponame>gzigzigzeo/protobuf-as /** * tests/__fixtures__/assembly/complex_struct/encode * @param obj `tests/__fixtures__/as_proto/complex_struct/complex_struct/Message` * @returns `~lib/arraybuffer/ArrayBuffer` */ export declare function encode(obj: __Record3<undefined>): ArrayBuffer; /** * tests/__fixtures__/assembly/complex_struct/decode * @param buffer `~lib/arraybuffer/ArrayBuffer` * @returns `tests/__fixtures__/as_proto/complex_struct/complex_struct/Message` */ export declare function decode(buffer: ArrayBuffer): __Record3<never>; /** * tests/__fixtures__/assembly/complex_struct/size * @param obj `tests/__fixtures__/as_proto/complex_struct/complex_struct/Message` * @returns `u32` */ export declare function size(obj: __Record3<undefined>): number; /** tests/__fixtures__/as_proto/complex_struct/complex_struct/Labels */ declare interface __Record4<TOmittable> { /** @type `~lib/array/Array<~lib/string/String>` */ Labels: Array<string>; } /** ~lib/map/Map<~lib/string/String,~lib/string/String> */ declare class __Internref6 extends Number { private __nominal6: symbol; } /** ~lib/map/Map<~lib/string/String,tests/__fixtures__/as_proto/complex_struct/complex_struct/Message_Message> */ declare class __Internref8 extends Number { private __nominal8: symbol; } /** tests/__fixtures__/as_proto/complex_struct/complex_struct/external.Properties */ declare interface __Record9<TOmittable> { /** @type `~lib/string/String` */ Properties: string; } /** tests/__fixtures__/as_proto/complex_struct/complex_struct/external.external.Properties */ declare interface __Record10<TOmittable> { /** @type `~lib/string/String` */ Properties: string; } /** tests/__fixtures__/as_proto/complex_struct/complex_struct/Message */ declare interface __Record3<TOmittable> { /** @type `~lib/string/String` */ String: string; /** @type `tests/__fixtures__/as_proto/complex_struct/complex_struct/Labels` */ Labels: __Record4<undefined>; /** @type `u32` */ Status1: number | TOmittable; /** @type `u32` */ Status2: number | TOmittable; /** @type `u32` */ Network: number | TOmittable; /** @type `~lib/array/Array<~lib/string/String>` */ Strings: Array<string>; /** @type `~lib/map/Map<~lib/string/String,~lib/string/String>` */ MapString: __Internref6; /** @type `~lib/map/Map<~lib/string/String,tests/__fixtures__/as_proto/complex_struct/complex_struct/Message_Message>` */ MapMessages: __Internref8; /** @type `tests/__fixtures__/as_proto/complex_struct/complex_struct/external.Properties` */ Properties1: __Record9<undefined>; /** @type `tests/__fixtures__/as_proto/complex_struct/complex_struct/external.external.Properties` */ Properties2: __Record10<undefined>; /** @type `~lib/array/Array<u32>` */ Services: Array<number>; }
gzigzigzeo/protobuf-as
assembly/ext/google.protobuf.Struct.ts
// Returns struct field by name. If field does not exists, it gets created and added to the fields collection. get(name: string): Value { if (this.fields.has(name)) { return this.fields.get(name); } const v = new Value() v.setNull() this.fields.set(name, v) return v }
gzigzigzeo/protobuf-as
tests/__fixtures__/assembly/lists.ts
import { Lists } from '../as_proto/lists/lists'; export function encode(obj: Lists): ArrayBuffer { return obj.encode() } export function decode(buffer: ArrayBuffer): Lists { return Lists.decode(buffer) } export function size(obj: Lists): u32 { return obj.size() }
gzigzigzeo/protobuf-as
src/walker_as/namespace_multi_file.ts
<reponame>gzigzigzeo/protobuf-as<filename>src/walker_as/namespace_multi_file.ts import { decorated } from "../proto/index.js"; import { Writer } from "./index.js"; import { namespaceToFileName, getRelPath } from './internal.js'; /** * Namespace code blocks */ export class NamespaceMultiFile { constructor(private p:Writer) {} // Generates statement which re-exports embedded namespace to the top level parentRef(ns: decorated.Namespace) { this.p(`import * as ${ns.name} from './${namespaceToFileName(ns)}'`) this.p(`export { ${ns.name} }`) } extRef(ns: decorated.Namespace, ext: string) { const parts = ext.split(".") const top = parts[0] this.p(`import * as ${top} from '${getRelPath(ns)}/${top}'`) } start(ns:decorated.Namespace) { this.p(` import * as __proto from '${getRelPath(ns)}/__proto' `); } finish(ns:decorated.Namespace, globals: Map<string, string>) { globals.forEach((value, key) => { this.p(` // ${key} ${value} `) }); } }
gzigzigzeo/protobuf-as
tests/__fixtures__/ts_proto/lists/main.ts
<reponame>gzigzigzeo/protobuf-as<gh_stars>1-10 /* eslint-disable */ import Long from 'long'; import _m0 from 'protobufjs/minimal.js'; export const protobufPackage = ''; export enum Enum { Zero = 0, One = 1, Two = 2, UNRECOGNIZED = -1, } export function enumFromJSON(object: any): Enum { switch (object) { case 0: case 'Zero': return Enum.Zero; case 1: case 'One': return Enum.One; case 2: case 'Two': return Enum.Two; case -1: case 'UNRECOGNIZED': default: return Enum.UNRECOGNIZED; } } export function enumToJSON(object: Enum): string { switch (object) { case Enum.Zero: return 'Zero'; case Enum.One: return 'One'; case Enum.Two: return 'Two'; default: return 'UNKNOWN'; } } export interface Message { String: string; } export interface Lists { Enums: Enum[]; Strings: string[]; Bytes: Uint8Array[]; Messages: Message[]; Ints: number[]; } function createBaseMessage(): Message { return { String: '' }; } export const Message = { encode( message: Message, writer: _m0.Writer = _m0.Writer.create(), ): _m0.Writer { if (message.String !== '') { writer.uint32(10).string(message.String); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Message { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = createBaseMessage(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.String = reader.string(); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Message { return { String: isSet(object.String) ? String(object.String) : '', }; }, toJSON(message: Message): unknown { const obj: any = {}; message.String !== undefined && (obj.String = message.String); return obj; }, fromPartial<I extends Exact<DeepPartial<Message>, I>>(object: I): Message { const message = createBaseMessage(); message.String = object.String ?? ''; return message; }, }; function createBaseLists(): Lists { return { Enums: [], Strings: [], Bytes: [], Messages: [], Ints: [] }; } export const Lists = { encode( message: Lists, writer: _m0.Writer = _m0.Writer.create(), ): _m0.Writer { writer.uint32(10).fork(); for (const v of message.Enums) { writer.int32(v); } writer.ldelim(); for (const v of message.Strings) { writer.uint32(18).string(v!); } for (const v of message.Bytes) { writer.uint32(26).bytes(v!); } for (const v of message.Messages) { Message.encode(v!, writer.uint32(34).fork()).ldelim(); } writer.uint32(42).fork(); for (const v of message.Ints) { writer.int32(v); } writer.ldelim(); return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): Lists { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = createBaseLists(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: if ((tag & 7) === 2) { const end2 = reader.uint32() + reader.pos; while (reader.pos < end2) { message.Enums.push(reader.int32() as any); } } else { message.Enums.push(reader.int32() as any); } break; case 2: message.Strings.push(reader.string()); break; case 3: message.Bytes.push(reader.bytes()); break; case 4: message.Messages.push( Message.decode(reader, reader.uint32()), ); break; case 5: if ((tag & 7) === 2) { const end2 = reader.uint32() + reader.pos; while (reader.pos < end2) { message.Ints.push(reader.int32()); } } else { message.Ints.push(reader.int32()); } break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): Lists { return { Enums: Array.isArray(object?.Enums) ? object.Enums.map((e: any) => enumFromJSON(e)) : [], Strings: Array.isArray(object?.Strings) ? object.Strings.map((e: any) => String(e)) : [], Bytes: Array.isArray(object?.Bytes) ? object.Bytes.map((e: any) => bytesFromBase64(e)) : [], Messages: Array.isArray(object?.Messages) ? object.Messages.map((e: any) => Message.fromJSON(e)) : [], Ints: Array.isArray(object?.Ints) ? object.Ints.map((e: any) => Number(e)) : [], }; }, toJSON(message: Lists): unknown { const obj: any = {}; if (message.Enums) { obj.Enums = message.Enums.map((e) => enumToJSON(e)); } else { obj.Enums = []; } if (message.Strings) { obj.Strings = message.Strings.map((e) => e); } else { obj.Strings = []; } if (message.Bytes) { obj.Bytes = message.Bytes.map((e) => base64FromBytes(e !== undefined ? e : new Uint8Array()), ); } else { obj.Bytes = []; } if (message.Messages) { obj.Messages = message.Messages.map((e) => e ? Message.toJSON(e) : undefined, ); } else { obj.Messages = []; } if (message.Ints) { obj.Ints = message.Ints.map((e) => Math.round(e)); } else { obj.Ints = []; } return obj; }, fromPartial<I extends Exact<DeepPartial<Lists>, I>>(object: I): Lists { const message = createBaseLists(); message.Enums = object.Enums?.map((e) => e) || []; message.Strings = object.Strings?.map((e) => e) || []; message.Bytes = object.Bytes?.map((e) => e) || []; message.Messages = object.Messages?.map((e) => Message.fromPartial(e)) || []; message.Ints = object.Ints?.map((e) => e) || []; return message; }, }; declare var self: any | undefined; declare var window: any | undefined; declare var global: any | undefined; var globalThis: any = (() => { if (typeof globalThis !== 'undefined') return globalThis; if (typeof self !== 'undefined') return self; if (typeof window !== 'undefined') return window; if (typeof global !== 'undefined') return global; throw 'Unable to locate global object'; })(); const atob: (b64: string) => string = globalThis.atob || ((b64) => globalThis.Buffer.from(b64, 'base64').toString('binary')); function bytesFromBase64(b64: string): Uint8Array { const bin = atob(b64); const arr = new Uint8Array(bin.length); for (let i = 0; i < bin.length; ++i) { arr[i] = bin.charCodeAt(i); } return arr; } const btoa: (bin: string) => string = globalThis.btoa || ((bin) => globalThis.Buffer.from(bin, 'binary').toString('base64')); function base64FromBytes(arr: Uint8Array): string { const bin: string[] = []; for (const byte of arr) { bin.push(String.fromCharCode(byte)); } return btoa(bin.join('')); } type Builtin = | Date | Function | Uint8Array | string | number | boolean | undefined; export type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends { $case: string } ? { [K in keyof Omit<T, '$case'>]?: DeepPartial<T[K]> } & { $case: T['$case']; } : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> } : Partial<T>; type KeysOfUnion<T> = T extends T ? keyof T : never; export type Exact<P, I extends P> = P extends Builtin ? P : P & { [K in keyof P]: Exact<P[K], I[K]> } & Record< Exclude<keyof I, KeysOfUnion<P>>, never >; if (_m0.util.Long !== Long) { _m0.util.Long = Long as any; _m0.configure(); } function isSet(value: any): boolean { return value !== null && value !== undefined; }
gzigzigzeo/protobuf-as
src/walker_as/walker_as_single_file.ts
<reponame>gzigzigzeo/protobuf-as<gh_stars>1-10 import { FlatWalker, File } from '../walker/index.js'; import { decorated } from '../proto/index.js'; import { BlocksSingleFile } from './blocks_single_file.js'; import { NamespaceSingleFile } from './namespace_single_file.js'; import { Enum } from './enum.js'; import { Message } from './message.js'; import { Field } from './field.js'; import { Options } from '../options.js'; import { Decode } from './decode.js'; import { Encode } from './encode.js'; import { Size } from './size.js'; import { OneOf } from './one_of.js'; import { prettify } from './prettify.js'; import { GlobalsRegistry } from './index.js'; /** * WalkerAS represents Walker implementing FlatWalker strategy producing AssemblyScript code. This is the composite class. */ export class WalkerASSingleFile implements FlatWalker, GlobalsRegistry { private chunks: string[] = new Array<string>(); private blocks: BlocksSingleFile; private namespace: NamespaceSingleFile; private enum: Enum; private message: Message; private decode: Decode; private encode: Encode; private size: Size; private field: Field; private oneOf: OneOf; private globals: Map<string, string> = new Map<string, string>(); constructor(private options: Readonly<Options>) { const p = this.p.bind(this); this.blocks = new BlocksSingleFile(p); this.namespace = new NamespaceSingleFile(p); this.enum = new Enum(p); this.message = new Message(p, this.options); this.field = new Field(p, this.options); this.decode = new Decode(p, this, this.options); this.encode = new Encode(p); this.size = new Size(p, this); this.oneOf = new OneOf(p, this.options); } public beforeAll() { this.blocks.beforeAll(); } public afterAll() { this.blocks.afterAll(this.globals); } public startNamespace(namespace: decorated.Namespace) { this.namespace.start(namespace); } // eslint-disable-next-line public referenceExternal(namespace:decorated.Namespace, ext: string): void { // noop } public finishNamespace(namespace: decorated.Namespace) { this.namespace.finish(namespace); } public startEnum(en: decorated.Enum) { this.enum.start(en); } public enumValue(value: decorated.EnumValue) { this.enum.value(value); } public finishEnum(en: decorated.Enum) { this.enum.finish(en); } public startMessage(message: decorated.Message) { this.message.start(message); } public finishMessage(message: decorated.Message) { this.message.finish(message); } public fieldDecl(field: decorated.Field) { this.field.decl(field); } public startDecode(message: decorated.Message) { this.decode.start(message); } public beginDecode() { this.decode.begin(); } public fieldInit() { // noop } public fieldDecode(field: decorated.Field) { this.decode.field(field); } public endDecode() { this.decode.end(); } public finishDecode(message: decorated.Message) { this.decode.finish(message); } public startEncode(message: decorated.Message) { this.encode.start(message); } public beginEncode() { this.encode.begin(); } public fieldEncode(field: decorated.Field) { this.encode.field(field); } public endEncode() { this.encode.end(); } public finishEncode(message: decorated.Message) { this.encode.finish(message); } public startSize() { this.size.start(); } public fieldSize(field: decorated.Field) { this.size.field(field); } public finishSize() { this.size.finish(); } public oneOfDiscriminatorDecl(desc: decorated.Message, group: string): void { this.oneOf.discriminatorDecl(desc, group); } public oneOfDiscriminatorConst(desc: decorated.Field): void { this.oneOf.discriminatorConst(desc); } public files():File[] { const files:File[] = [{ name: this.options.targetFileName, content: this.chunks.join('\n') }]; if (this.options.disablePrettier) { return files } return prettify(files) } p(s: string) { if (s != '') { this.chunks.push(s); } } public registerGlobal(key: string, content: string) { if (this.globals.has(key)) { return } this.globals.set(key, content); } }
gzigzigzeo/protobuf-as
tests/assembly/elementaries.test.ts
import { test } from 'uvu'; import * as assert from 'uvu/assert'; import { Elementaries, Enum } from '../__fixtures__/ts_proto/elementaries/main.js'; import { encode, decode, size } from '../__fixtures__/build/elementaries.js'; import { TextEncoder, TextDecoder } from 'util'; const subject: Elementaries = { Double: 4242.5, Float: 42.5, Int32: -38192, UInt32: 4424, SInt32: -54242, Fixed32: 642, SFixed32: -642, Int64: -7424242, UInt64: 9007199254740991, SInt64: -942424242, Fixed64: 10424242, SFixed64: -10424242, Bool: true, Enum: Enum.One, Bytes: new TextEncoder().encode('Test'), String: 'Test', EmptyString: '', EmptyBytes: new Uint8Array(), EmptyInt64: 0, EmptyInt32: 0, EmptyBool: false, }; const data = Elementaries.encode(subject).finish() const buf = data.buffer.slice(data.byteOffset, data.byteOffset+data.byteLength) const decoded = decode(buf) const encoded = encode(decoded) test('encode()', () => { assert.equal(size(decoded), data.length); assert.equal(decoded.Double, 4242.5); assert.equal(decoded.Float, 42.5); assert.equal(decoded.Int32, -38192); assert.equal(decoded.UInt32, 4424); assert.equal(decoded.SInt32, -54242); assert.equal(decoded.Fixed32, 642); assert.equal(decoded.SFixed32, -642); assert.equal(decoded.Int64.toString(), '-7424242'); assert.equal(decoded.UInt64.toString(), '9007199254740991'); assert.equal(decoded.SInt64.toString(), '-942424242'); assert.equal(decoded.Fixed64.toString(), '10424242'); assert.equal(decoded.SFixed64.toString(), '-10424242'); assert.equal(decoded.Bool, true) assert.equal(decoded.Enum, Enum.One); assert.equal(new TextDecoder().decode(new Uint8Array(decoded.Bytes)), 'Test') assert.equal(decoded.String, 'Test'); }) test('encode()', () => { assert.equal(encoded.byteLength, data.byteLength) assert.equal(encoded.byteLength, size(decoded)) assert.equal(encoded.byteLength, buf.byteLength) assert.equal(encoded, buf) }); test.run()
gzigzigzeo/protobuf-as
tests/assembly/lists.test.ts
<reponame>gzigzigzeo/protobuf-as import { test } from 'uvu'; import * as assert from 'uvu/assert'; import { Lists, Message, Enum } from '../__fixtures__/ts_proto/lists/main.js'; import { encode, decode, size } from '../__fixtures__/build/lists.js'; import { TextEncoder, TextDecoder } from 'util'; const subject: Lists = { Enums: [Enum.One, Enum.Two], Strings: ['String1', 'String2', 'String3', '', 'String4'], Bytes: [ new TextEncoder().encode('Bytes1'), new Uint8Array(0), new TextEncoder().encode('Bytes2') ], Messages: [ <Message>{ String: 'Message1' }, <Message>{ String: 'Message2' } ], Ints: [1024, 2048, 0, 4096], }; const data = Lists.encode(subject).finish() const buf = data.buffer.slice(data.byteOffset, data.byteOffset+data.byteLength) const decoded = decode(buf) const encoded = encode(decoded) test('decode()', () => { assert.equal(size(decoded), data.length); assert.equal(decoded.Enums[1], Enum.Two) assert.equal(decoded.Strings[1], 'String2') assert.equal(decoded.Strings[4], 'String4') assert.equal(new TextDecoder().decode(new Uint8Array(decoded.Bytes[2])), 'Bytes2') assert.equal(decoded.Messages[1].String, 'Message2') assert.equal(decoded.Ints[1], 2048) assert.equal(decoded.Ints[3], 4096) }) test('encode()', () => { assert.equal(encoded.byteLength, data.byteLength) assert.equal(encoded.byteLength, size(decoded)) assert.equal(encoded.byteLength, buf.byteLength) assert.equal(encoded, buf) }) test.run()
gzigzigzeo/protobuf-as
tests/__fixtures__/as_proto/lists/lists.ts
namespace __proto { /** * Decoder implements protobuf message decode interface. * * Useful references: * * Protocol Buffer encoding: https://developers.google.com/protocol-buffers/docs/encoding * LEB128 encoding AKA varint 128 encoding: https://en.wikipedia.org/wiki/LEB128 * ZigZag encoding/decoding (s32/s64): https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba */ export class Decoder { public view: DataView; public pos: i32; constructor(view: DataView) { this.view = view; this.pos = 0; } /** * Returns true if current reader has reached the buffer end * @returns True if current reader has reached the buffer end */ @inline eof(): bool { return this.pos >= this.view.byteLength; } /** * Returns current buffer length in bytes * @returns Length in bytes */ @inline get byteLength(): i32 { return this.view.byteLength; } /** * An alias method to fetch tag from the reader. Supposed to return tuple of [field number, wire_type]. * TODO: Replace with return tuple when tuples become implemented in AS. * @returns Message tag value */ @inline tag(): u32 { return this.uint32(); } /** * Returns byte at offset, alias for getUint8 * @param byteOffset Offset * @returns u8 */ @inline private u8at(byteOffset: i32): u8 { return this.view.getUint8(byteOffset); } /** * Reads and returns varint number (128 + 10 bits max) from a current position. * @returns Returns varint */ varint(): u64 { let value: u64; // u32 value = (u64(u8(this.u8at(this.pos))) & 127) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 7)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 14)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 21)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; // u32 remainder or u64 byte value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 28)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; // u64 value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 35)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 42)) /* 42!!! */ >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 49)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 28)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; // u64 remainder value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 35)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; if (this.pos > this.byteLength) { this.throwOutOfRange(); } return value; } @inline int32(): i32 { return i32(this.varint()); } @inline int64(): i64 { return i32(this.varint()); } @inline uint32(): u32 { return u32(this.varint()); } @inline uint64(): u64 { return u64(this.varint()); } @inline sint32(): i32 { const n: u64 = this.varint(); return i32((n >>> 1) ^ -(n & 1)); } @inline sint64(): i64 { const n: u64 = this.varint(); return i64((n >>> 1) ^ -(n & 1)); } fixed32(): u32 { this.pos += 4; if (this.pos > this.byteLength) { this.throwOutOfRange(); } // u32(u8) ensures that u8(-1) becomes u32(4294967295) instead of u8(255) return ( u32(u8(this.u8at(this.pos - 4))) | (u32(u8(this.u8at(this.pos - 3))) << 8) | (u32(u8(this.u8at(this.pos - 2))) << 16) | (u32(u8(this.u8at(this.pos - 1))) << 24) ); } @inline sfixed32(): i32 { return i32(this.fixed32()); } fixed64(): u64 { this.pos += 8; if (this.pos > this.byteLength) { this.throwOutOfRange(); } return ( u64(u8(this.u8at(this.pos - 8))) | (u64(u8(this.u8at(this.pos - 7))) << 8) | (u64(u8(this.u8at(this.pos - 6))) << 16) | (u64(u8(this.u8at(this.pos - 5))) << 24) | (u64(u8(this.u8at(this.pos - 4))) << 32) | (u64(u8(this.u8at(this.pos - 3))) << 40) | (u64(u8(this.u8at(this.pos - 2))) << 48) | (u64(u8(this.u8at(this.pos - 1))) << 56) ); } @inline sfixed64(): i64 { return i64(this.fixed64()); } @inline float(): f32 { return f32.reinterpret_i32(this.fixed32()); } @inline double(): f64 { return f64.reinterpret_i64(this.fixed64()); } @inline bool(): boolean { return this.uint32() > 0; } /** * Reads and returns UTF8 string. * @returns String */ string(): string { const length = this.uint32(); if (this.pos + length > this.byteLength) { this.throwOutOfRange(); } const p = this.pos + this.view.byteOffset; const value = String.UTF8.decode(this.view.buffer.slice(p, p + length)); this.pos += length; return value; } /** * Reads and returns bytes array. * @returns Array<u8> of bytes */ bytes(): Array<u8> { const len = this.uint32(); if (this.pos + len > this.byteLength) { this.throwOutOfRange(); } const a = new Array<u8>(len); for (let i: u32 = 0; i < len; i++) { a[i] = u8(this.u8at(this.pos++)); } return a; } /** * Skips a message field if it can'be recognized by an object's decode() method * @param wireType Current wire type */ skipType(wireType: u32): void { switch (wireType) { // int32, int64, uint32, uint64, sint32, sint64, bool, enum: varint, variable length case 0: this.varint(); // Just read a varint break; // fixed64, sfixed64, double: 8 bytes always case 1: this.skip(8); break; // length-delimited; length is determined by varint32; skip length bytes; case 2: this.skip(this.uint32()); break; // tart group: skip till the end of the group, then skip group end marker case 3: while ((wireType = this.uint32() & 7) !== 4) { this.skipType(wireType); } break; // fixed32, sfixed32, float: 4 bytes always case 5: this.skip(4); break; // Something went beyond our capability to understand default: throw new Error( `Invalid wire type ${wireType} at offset ${this.pos}` ); } } /** * Fast-forwards cursor by length with boundary check * @param length Byte length */ skip(length: u32): void { if (this.pos + length > this.byteLength) { this.throwOutOfRange(); } this.pos += length; } /** * OutOfRange check. Throws an exception if current position exceeds current buffer range */ @inline private throwOutOfRange(): void { throw new Error(`Decoder position ${this.pos} is out of range!`); } } /** * Encoder implements protobuf message encode interface. This is the simplest not very effective version, which uses * Array<u8>. * * Useful references: * * Protocol Buffer encoding: https://developers.google.com/protocol-buffers/docs/encoding * LEB128 encoding AKA varint 128 encoding: https://en.wikipedia.org/wiki/LEB128 * ZigZag encoding/decoding (s32/s64): https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba */ export class Encoder { public buf: Array<u8>; constructor(buf: Array<u8>) { this.buf = buf; } /** * Encodes varint at a current position * @returns Returns varint */ varint64(value: u64): void { let v: u64 = value; while (v > 127) { this.buf.push(u8((v & 127) | 128)); v = v >> 7; } this.buf.push(u8(v)); } @inline int32(value: i32): void { this.varint64(value); } @inline int64(value: i64): void { this.varint64(value); } @inline uint32(value: u32): void { this.varint64(value); } @inline uint64(value: u64): void { this.varint64(value); } @inline sint32(value: i32): void { this.varint64((value << 1) ^ (value >> 31)); } @inline sint64(value: i64): void { this.varint64((value << 1) ^ (value >> 63)); } @inline fixed32(value: u32): void { this.buf.push(u8(value & 255)); this.buf.push(u8((value >> 8) & 255)); this.buf.push(u8((value >> 16) & 255)); this.buf.push(u8(value >> 24)); } @inline sfixed32(value: i32): void { this.fixed32(u32(value)); } @inline fixed64(value: u64): void { this.buf.push(u8(value & 255)); this.buf.push(u8((value >> 8) & 255)); this.buf.push(u8((value >> 16) & 255)); this.buf.push(u8((value >> 24) & 255)); this.buf.push(u8((value >> 32) & 255)); this.buf.push(u8((value >> 40) & 255)); this.buf.push(u8((value >> 48) & 255)); this.buf.push(u8(value >> 56)); } @inline sfixed64(value: i64): void { this.fixed64(u64(value)); } @inline float(value: f32): void { this.fixed32(u32(i32.reinterpret_f32(value))); } @inline double(value: f64): void { this.fixed64(u64(i64.reinterpret_f64(value))); } @inline bool(value: boolean): void { this.buf.push(value ? 1 : 0); } string(value: string): void { const utf8string = new DataView(String.UTF8.encode(value)); for (let i = 0; i < utf8string.byteLength; i++) { this.buf.push(utf8string.getUint8(i)); } } @inline bytes(value: Array<u8>): void { for (let i = 0; i < value.length; i++) { this.buf.push(value[i]); } } } /** * Returns byte size required to encode a value of a certain type */ export class Sizer { static varint64(value: u64): u32 { return value < 128 ? 1 // 2^7 : value < 16384 ? 2 // 2^14 : value < 2097152 ? 3 // 2^21 : value < 268435456 ? 4 // 2^28 : value < 34359738368 ? 5 // 2^35 : value < 4398046511104 ? 6 // 2^42 : value < 562949953421312 ? 7 // 2^49 : value < 72057594037927936 ? 8 // 2^56 : value < 9223372036854775808 ? 9 // 2^63 : 10; } @inline static int32(value: i32): u32 { return Sizer.varint64(u64(value)); } @inline static int64(value: i64): u32 { return Sizer.varint64(u64(value)); } @inline static uint32(value: u32): u32 { return Sizer.varint64(value); } @inline static uint64(value: u64): u32 { return Sizer.varint64(value); } @inline static sint32(value: i32): u32 { return Sizer.varint64((value << 1) ^ (value >> 31)); } @inline static sint64(value: i64): u32 { return Sizer.varint64((value << 1) ^ (value >> 63)); } @inline static string(value: string): u32 { return value.length; } @inline static bytes(value: Array<u8>): u32 { return value.length; } } } export enum Enum { Zero = 0, One = 1, Two = 2, } // Enum export class Message { public String: string = ""; // Decodes Message from an ArrayBuffer static decode(buf: ArrayBuffer): Message { return Message.decodeDataView(new DataView(buf)); } // Decodes Message from a DataView static decodeDataView(view: DataView): Message { const decoder = new __proto.Decoder(view); const obj = new Message(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { obj.String = decoder.string(); break; } default: decoder.skipType(tag & 7); break; } } return obj; } // decode Message public size(): u32 { let size: u32 = 0; size += this.String.length > 0 ? 1 + __proto.Sizer.varint64(this.String.length) + this.String.length : 0; return size; } // Encodes Message to the ArrayBuffer encode(): ArrayBuffer { return changetype<ArrayBuffer>( StaticArray.fromArray<u8>(this.encodeU8Array()) ); } // Encodes Message to the Array<u8> encodeU8Array( encoder: __proto.Encoder = new __proto.Encoder(new Array<u8>()) ): Array<u8> { const buf = encoder.buf; if (this.String.length > 0) { encoder.uint32(0xa); encoder.uint32(this.String.length); encoder.string(this.String); } return buf; } // encode Message } // Message export class Lists { public Enums: Array<u32> = new Array<u32>(); public Strings: Array<string> = new Array<string>(); public Bytes: Array<Array<u8>> = new Array<Array<u8>>(); public Messages: Array<Message> = new Array<Message>(); public Ints: Array<i32> = new Array<i32>(); // Decodes Lists from an ArrayBuffer static decode(buf: ArrayBuffer): Lists { return Lists.decodeDataView(new DataView(buf)); } // Decodes Lists from a DataView static decodeDataView(view: DataView): Lists { const decoder = new __proto.Decoder(view); const obj = new Lists(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { const endPos = decoder.pos + decoder.uint32(); while (decoder.pos <= endPos) { obj.Enums.push(decoder.uint32()); } break; } case 2: { obj.Strings.push(decoder.string()); break; } case 3: { obj.Bytes.push(decoder.bytes()); break; } case 4: { const length = decoder.uint32(); obj.Messages.push( Message.decodeDataView( new DataView( decoder.view.buffer, decoder.pos + decoder.view.byteOffset, length ) ) ); decoder.skip(length); break; } case 5: { const endPos = decoder.pos + decoder.uint32(); while (decoder.pos <= endPos) { obj.Ints.push(decoder.int32()); } break; } default: decoder.skipType(tag & 7); break; } } return obj; } // decode Lists public size(): u32 { let size: u32 = 0; if (this.Enums.length > 0) { const packedSize = __size_uint32_repeated_packed(this.Enums); if (packedSize > 0) { size += 1 + __proto.Sizer.varint64(packedSize) + packedSize; } } size += __size_string_repeated(this.Strings); size += __size_bytes_repeated(this.Bytes); for (let n: i32 = 0; n < this.Messages.length; n++) { const messageSize = this.Messages[n].size(); if (messageSize > 0) { size += 1 + __proto.Sizer.varint64(messageSize) + messageSize; } } if (this.Ints.length > 0) { const packedSize = __size_int32_repeated_packed(this.Ints); if (packedSize > 0) { size += 1 + __proto.Sizer.varint64(packedSize) + packedSize; } } return size; } // Encodes Lists to the ArrayBuffer encode(): ArrayBuffer { return changetype<ArrayBuffer>( StaticArray.fromArray<u8>(this.encodeU8Array()) ); } // Encodes Lists to the Array<u8> encodeU8Array( encoder: __proto.Encoder = new __proto.Encoder(new Array<u8>()) ): Array<u8> { const buf = encoder.buf; if (this.Enums.length > 0) { encoder.uint32(0xa); encoder.uint32(__size_uint32_repeated_packed(this.Enums)); for (let n: i32 = 0; n < this.Enums.length; n++) { encoder.uint32(this.Enums[n]); } } if (this.Strings.length > 0) { for (let n: i32 = 0; n < this.Strings.length; n++) { encoder.uint32(0x12); encoder.uint32(this.Strings[n].length); encoder.string(this.Strings[n]); } } if (this.Bytes.length > 0) { for (let n: i32 = 0; n < this.Bytes.length; n++) { encoder.uint32(0x1a); encoder.uint32(this.Bytes[n].length); encoder.bytes(this.Bytes[n]); } } for (let n: i32 = 0; n < this.Messages.length; n++) { const messageSize = this.Messages[n].size(); if (messageSize > 0) { encoder.uint32(0x22); encoder.uint32(messageSize); this.Messages[n].encodeU8Array(encoder); } } if (this.Ints.length > 0) { encoder.uint32(0x2a); encoder.uint32(__size_int32_repeated_packed(this.Ints)); for (let n: i32 = 0; n < this.Ints.length; n++) { encoder.int32(this.Ints[n]); } } return buf; } // encode Lists } // Lists // __size_uint32_repeated_packed function __size_uint32_repeated_packed(value: Array<u32>): u32 { let size: u32 = 0; for (let n: i32 = 0; n < value.length; n++) { size += __proto.Sizer.uint32(value[n]); } return size; } // __size_string_repeated function __size_string_repeated(value: Array<string>): u32 { let size: u32 = 0; for (let n: i32 = 0; n < value.length; n++) { size += 1 + __proto.Sizer.varint64(value[n].length) + value[n].length; } return size; } // __size_bytes_repeated function __size_bytes_repeated(value: Array<Array<u8>>): u32 { let size: u32 = 0; for (let n: i32 = 0; n < value.length; n++) { size += 1 + __proto.Sizer.varint64(value[n].length) + value[n].length; } return size; } // __size_int32_repeated_packed function __size_int32_repeated_packed(value: Array<i32>): u32 { let size: u32 = 0; for (let n: i32 = 0; n < value.length; n++) { size += __proto.Sizer.int32(value[n]); } return size; }
gzigzigzeo/protobuf-as
src/proto/named_descriptor_index_reducer.ts
import { WeightMap, ImmutableFlatTree } from '../structs/index.js'; import * as named from './named_descriptor.js'; /** * Performs tree-shaking of the named descriptor index. * Removes unused descriptors. Removes explicitly requested descriptors. Performs integritiy check. */ export class NamedDescriptorIndexReducer implements named.DescriptorCollection { private weights: WeightMap<string>; private tree: ImmutableFlatTree<named.Descriptor>; /** * Creates DescriptorIndexReducer containing all required fields based on inclusion/exclusion list. * * @param index Parent index * @param include Set of descriptor names to mark as required * @param exclude Set of descriptor names to exclude */ constructor( index: named.DescriptorCollection, include: ReadonlySet<string>, exclude: ReadonlySet<string>, ) { this.weights = new WeightMap<string>(); this.tree = new ImmutableFlatTree<named.Descriptor>( index.values().map((v) => [v.id, v]), ); this.pin(new Set<string>(include)); this.unpin(new Set<string>(exclude)); } private pin(keys: ReadonlySet<string>) { keys.forEach((key) => { // Increase weight if a type is included this.weights.increase(key); // Increase weights of all referenced messages, enums and namespaces this.walk(key, (key) => this.weights.increase(key)); }); } private unpin(keys: ReadonlySet<string>) { keys.forEach((key) => { // Explicitly set weight to 0 if a type is excluded this.weights.setWeight(key, 0); // Decrease weights of all referenced messages, enums and namespaces this.walk(key, (key) => this.weights.decrease(key)); }); } private walk( key: string, cb: (key: string) => void, stack: Set<string> = new Set<string>(), ) { // Stack is used to prevent circular loops if (stack.has(key)) { return; } stack.add(key); // Get the item from a tree const item = this.tree.get(key); if (!item) { return; // Silently, we'll know if structure is broken on calculating brokenLinks() } const [, desc] = item; // Increase weight of referenced message or enum if (desc.kind == 'field' && desc.hasOne) { cb(desc.hasOne); this.walk(desc.hasOne, cb, stack); } // Increase weight of a namespace (if any) if ( ['namespace', 'message', 'enum'].includes(desc.kind) && desc.namespace != '' ) { cb(desc.namespace); this.walk(desc.namespace, cb, stack); } // Get all nested fields of a message, follow each hasOne and increase/decrease weight if (desc.kind == 'message' || desc.kind == 'enum') { this.tree.descendants(key).forEach(([key, desc]) => { if (desc.kind == 'field') { this.walk(key, cb, stack); // Go through field references } // Increase weight of a nested object if (desc.kind == 'field' || desc.kind == 'enum_value' || desc.kind == 'message') { cb(desc.id); } }); } } /** * Finds and returns broken references: references to a types which lead to removed items. * @returns Broken references in form of array of tuples [source, target] */ brokenReferences(): ReadonlyArray<[string, string]> { const broken = new Array<[string, string]>(); this.tree.forEach(([key, value]) => { if (this.weights.getWeight(key) > 0) { if (value.kind == 'field' && value.hasOne) { if (this.weights.getWeight(value.hasOne) < 1) { broken.push([key, value.hasOne]); } } } }); return broken; } /** * Returns array of leftover descriptors * @returns Array of descriptors */ values(): ReadonlyArray<named.Descriptor> { const values = new Array<named.Descriptor>(); this.tree.forEach(([key, value]) => { if (this.weights.getWeight(key) > 0) { values.push(value); } }); return values; } /** * Gets a descriptor from the collection * @param key Descriptor key * @returns Descriptor */ get(key: string): named.Descriptor | undefined { if (this.weights.getWeight(key) > 0 || !this.weights.has(key)) { const item = this.tree.get(key); if (item) { return item[1] } } return undefined; } }
gzigzigzeo/protobuf-as
tests/assembly/maps.test.ts
import { test } from 'uvu'; import * as assert from 'uvu/assert'; import { Maps } from '../__fixtures__/ts_proto/maps/main.js'; import { encode, decode, size } from '../__fixtures__/build/maps.js'; const subject: Maps = { StringStringMap: { key1: 'value1', key2: 'value2', key3: '', key4: 'value4', '': 'value5' }, StringInt32Map: { key1: 1, key2: 2 }, Int32StringMap: { 1: 'value1', 2: 'value2', 3: '', 4: 'value4' }, StringValueMap: { value1: { Int32s: [1, 2, 3] }, value2: { Int32s: [1, 2, 3] }, }, StringExternalMapValue: {}, }; const data = Maps.encode(subject).finish() const buf = data.buffer.slice(data.byteOffset, data.byteOffset+data.byteLength) const decoded = decode(buf) const encoded = encode(decoded) test('decode()', () => { assert.equal(size(decoded), data.length); }) test('encode()', () => { assert.equal(encoded.byteLength, data.byteLength) assert.equal(encoded.byteLength, size(decoded)) assert.equal(encoded.byteLength, buf.byteLength) assert.equal(encoded, buf) }) test.run()
gzigzigzeo/protobuf-as
tests/__fixtures__/as_proto/complex_struct/complex_struct.ts
namespace __proto { /** * Decoder implements protobuf message decode interface. * * Useful references: * * Protocol Buffer encoding: https://developers.google.com/protocol-buffers/docs/encoding * LEB128 encoding AKA varint 128 encoding: https://en.wikipedia.org/wiki/LEB128 * ZigZag encoding/decoding (s32/s64): https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba */ export class Decoder { public view: DataView; public pos: i32; constructor(view: DataView) { this.view = view; this.pos = 0; } /** * Returns true if current reader has reached the buffer end * @returns True if current reader has reached the buffer end */ @inline eof(): bool { return this.pos >= this.view.byteLength; } /** * Returns current buffer length in bytes * @returns Length in bytes */ @inline get byteLength(): i32 { return this.view.byteLength; } /** * An alias method to fetch tag from the reader. Supposed to return tuple of [field number, wire_type]. * TODO: Replace with return tuple when tuples become implemented in AS. * @returns Message tag value */ @inline tag(): u32 { return this.uint32(); } /** * Returns byte at offset, alias for getUint8 * @param byteOffset Offset * @returns u8 */ @inline private u8at(byteOffset: i32): u8 { return this.view.getUint8(byteOffset); } /** * Reads and returns varint number (128 + 10 bits max) from a current position. * @returns Returns varint */ varint(): u64 { let value: u64; // u32 value = (u64(u8(this.u8at(this.pos))) & 127) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 7)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 14)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 21)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; // u32 remainder or u64 byte value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 28)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; // u64 value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 35)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 42)) /* 42!!! */ >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 49)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 28)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; // u64 remainder value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 35)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; if (this.pos > this.byteLength) { this.throwOutOfRange(); } return value; } @inline int32(): i32 { return i32(this.varint()); } @inline int64(): i64 { return i32(this.varint()); } @inline uint32(): u32 { return u32(this.varint()); } @inline uint64(): u64 { return u64(this.varint()); } @inline sint32(): i32 { const n: u64 = this.varint(); return i32((n >>> 1) ^ -(n & 1)); } @inline sint64(): i64 { const n: u64 = this.varint(); return i64((n >>> 1) ^ -(n & 1)); } fixed32(): u32 { this.pos += 4; if (this.pos > this.byteLength) { this.throwOutOfRange(); } // u32(u8) ensures that u8(-1) becomes u32(4294967295) instead of u8(255) return ( u32(u8(this.u8at(this.pos - 4))) | (u32(u8(this.u8at(this.pos - 3))) << 8) | (u32(u8(this.u8at(this.pos - 2))) << 16) | (u32(u8(this.u8at(this.pos - 1))) << 24) ); } @inline sfixed32(): i32 { return i32(this.fixed32()); } fixed64(): u64 { this.pos += 8; if (this.pos > this.byteLength) { this.throwOutOfRange(); } return ( u64(u8(this.u8at(this.pos - 8))) | (u64(u8(this.u8at(this.pos - 7))) << 8) | (u64(u8(this.u8at(this.pos - 6))) << 16) | (u64(u8(this.u8at(this.pos - 5))) << 24) | (u64(u8(this.u8at(this.pos - 4))) << 32) | (u64(u8(this.u8at(this.pos - 3))) << 40) | (u64(u8(this.u8at(this.pos - 2))) << 48) | (u64(u8(this.u8at(this.pos - 1))) << 56) ); } @inline sfixed64(): i64 { return i64(this.fixed64()); } @inline float(): f32 { return f32.reinterpret_i32(this.fixed32()); } @inline double(): f64 { return f64.reinterpret_i64(this.fixed64()); } @inline bool(): boolean { return this.uint32() > 0; } /** * Reads and returns UTF8 string. * @returns String */ string(): string { const length = this.uint32(); if (this.pos + length > this.byteLength) { this.throwOutOfRange(); } const p = this.pos + this.view.byteOffset; const value = String.UTF8.decode(this.view.buffer.slice(p, p + length)); this.pos += length; return value; } /** * Reads and returns bytes array. * @returns Array<u8> of bytes */ bytes(): Array<u8> { const len = this.uint32(); if (this.pos + len > this.byteLength) { this.throwOutOfRange(); } const a = new Array<u8>(len); for (let i: u32 = 0; i < len; i++) { a[i] = u8(this.u8at(this.pos++)); } return a; } /** * Skips a message field if it can'be recognized by an object's decode() method * @param wireType Current wire type */ skipType(wireType: u32): void { switch (wireType) { // int32, int64, uint32, uint64, sint32, sint64, bool, enum: varint, variable length case 0: this.varint(); // Just read a varint break; // fixed64, sfixed64, double: 8 bytes always case 1: this.skip(8); break; // length-delimited; length is determined by varint32; skip length bytes; case 2: this.skip(this.uint32()); break; // tart group: skip till the end of the group, then skip group end marker case 3: while ((wireType = this.uint32() & 7) !== 4) { this.skipType(wireType); } break; // fixed32, sfixed32, float: 4 bytes always case 5: this.skip(4); break; // Something went beyond our capability to understand default: throw new Error( `Invalid wire type ${wireType} at offset ${this.pos}` ); } } /** * Fast-forwards cursor by length with boundary check * @param length Byte length */ skip(length: u32): void { if (this.pos + length > this.byteLength) { this.throwOutOfRange(); } this.pos += length; } /** * OutOfRange check. Throws an exception if current position exceeds current buffer range */ @inline private throwOutOfRange(): void { throw new Error(`Decoder position ${this.pos} is out of range!`); } } /** * Encoder implements protobuf message encode interface. This is the simplest not very effective version, which uses * Array<u8>. * * Useful references: * * Protocol Buffer encoding: https://developers.google.com/protocol-buffers/docs/encoding * LEB128 encoding AKA varint 128 encoding: https://en.wikipedia.org/wiki/LEB128 * ZigZag encoding/decoding (s32/s64): https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba */ export class Encoder { public buf: Array<u8>; constructor(buf: Array<u8>) { this.buf = buf; } /** * Encodes varint at a current position * @returns Returns varint */ varint64(value: u64): void { let v: u64 = value; while (v > 127) { this.buf.push(u8((v & 127) | 128)); v = v >> 7; } this.buf.push(u8(v)); } @inline int32(value: i32): void { this.varint64(value); } @inline int64(value: i64): void { this.varint64(value); } @inline uint32(value: u32): void { this.varint64(value); } @inline uint64(value: u64): void { this.varint64(value); } @inline sint32(value: i32): void { this.varint64((value << 1) ^ (value >> 31)); } @inline sint64(value: i64): void { this.varint64((value << 1) ^ (value >> 63)); } @inline fixed32(value: u32): void { this.buf.push(u8(value & 255)); this.buf.push(u8((value >> 8) & 255)); this.buf.push(u8((value >> 16) & 255)); this.buf.push(u8(value >> 24)); } @inline sfixed32(value: i32): void { this.fixed32(u32(value)); } @inline fixed64(value: u64): void { this.buf.push(u8(value & 255)); this.buf.push(u8((value >> 8) & 255)); this.buf.push(u8((value >> 16) & 255)); this.buf.push(u8((value >> 24) & 255)); this.buf.push(u8((value >> 32) & 255)); this.buf.push(u8((value >> 40) & 255)); this.buf.push(u8((value >> 48) & 255)); this.buf.push(u8(value >> 56)); } @inline sfixed64(value: i64): void { this.fixed64(u64(value)); } @inline float(value: f32): void { this.fixed32(u32(i32.reinterpret_f32(value))); } @inline double(value: f64): void { this.fixed64(u64(i64.reinterpret_f64(value))); } @inline bool(value: boolean): void { this.buf.push(value ? 1 : 0); } string(value: string): void { const utf8string = new DataView(String.UTF8.encode(value)); for (let i = 0; i < utf8string.byteLength; i++) { this.buf.push(utf8string.getUint8(i)); } } @inline bytes(value: Array<u8>): void { for (let i = 0; i < value.length; i++) { this.buf.push(value[i]); } } } /** * Returns byte size required to encode a value of a certain type */ export class Sizer { static varint64(value: u64): u32 { return value < 128 ? 1 // 2^7 : value < 16384 ? 2 // 2^14 : value < 2097152 ? 3 // 2^21 : value < 268435456 ? 4 // 2^28 : value < 34359738368 ? 5 // 2^35 : value < 4398046511104 ? 6 // 2^42 : value < 562949953421312 ? 7 // 2^49 : value < 72057594037927936 ? 8 // 2^56 : value < 9223372036854775808 ? 9 // 2^63 : 10; } @inline static int32(value: i32): u32 { return Sizer.varint64(u64(value)); } @inline static int64(value: i64): u32 { return Sizer.varint64(u64(value)); } @inline static uint32(value: u32): u32 { return Sizer.varint64(value); } @inline static uint64(value: u64): u32 { return Sizer.varint64(value); } @inline static sint32(value: i32): u32 { return Sizer.varint64((value << 1) ^ (value >> 31)); } @inline static sint64(value: i64): u32 { return Sizer.varint64((value << 1) ^ (value >> 63)); } @inline static string(value: string): u32 { return value.length; } @inline static bytes(value: Array<u8>): u32 { return value.length; } } } export namespace external { export class Properties { public Properties: string = ""; // Decodes Properties from an ArrayBuffer static decode(buf: ArrayBuffer): Properties { return Properties.decodeDataView(new DataView(buf)); } // Decodes Properties from a DataView static decodeDataView(view: DataView): Properties { const decoder = new __proto.Decoder(view); const obj = new Properties(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { obj.Properties = decoder.string(); break; } default: decoder.skipType(tag & 7); break; } } return obj; } // decode Properties public size(): u32 { let size: u32 = 0; size += this.Properties.length > 0 ? 1 + __proto.Sizer.varint64(this.Properties.length) + this.Properties.length : 0; return size; } // Encodes Properties to the ArrayBuffer encode(): ArrayBuffer { return changetype<ArrayBuffer>( StaticArray.fromArray<u8>(this.encodeU8Array()) ); } // Encodes Properties to the Array<u8> encodeU8Array( encoder: __proto.Encoder = new __proto.Encoder(new Array<u8>()) ): Array<u8> { const buf = encoder.buf; if (this.Properties.length > 0) { encoder.uint32(0xa); encoder.uint32(this.Properties.length); encoder.string(this.Properties); } return buf; } // encode Properties } // Properties export namespace external { export class Properties { public Properties: string = ""; // Decodes Properties from an ArrayBuffer static decode(buf: ArrayBuffer): Properties { return Properties.decodeDataView(new DataView(buf)); } // Decodes Properties from a DataView static decodeDataView(view: DataView): Properties { const decoder = new __proto.Decoder(view); const obj = new Properties(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { obj.Properties = decoder.string(); break; } default: decoder.skipType(tag & 7); break; } } return obj; } // decode Properties public size(): u32 { let size: u32 = 0; size += this.Properties.length > 0 ? 1 + __proto.Sizer.varint64(this.Properties.length) + this.Properties.length : 0; return size; } // Encodes Properties to the ArrayBuffer encode(): ArrayBuffer { return changetype<ArrayBuffer>( StaticArray.fromArray<u8>(this.encodeU8Array()) ); } // Encodes Properties to the Array<u8> encodeU8Array( encoder: __proto.Encoder = new __proto.Encoder(new Array<u8>()) ): Array<u8> { const buf = encoder.buf; if (this.Properties.length > 0) { encoder.uint32(0xa); encoder.uint32(this.Properties.length); encoder.string(this.Properties); } return buf; } // encode Properties } // Properties } // external } // external export namespace google { export namespace protobuf { /** * A Timestamp represents a point in time independent of any time zone or local * calendar, encoded as a count of seconds and fractions of seconds at * nanosecond resolution. The count is relative to an epoch at UTC midnight on * January 1, 1970, in the proleptic Gregorian calendar which extends the * Gregorian calendar backwards to year one. * * All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap * second table is needed for interpretation, using a [24-hour linear * smear](https://developers.google.com/time/smear). * * The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By * restricting to that range, we ensure that we can convert to and from [RFC * 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. * * # Examples * * Example 1: Compute Timestamp from POSIX `time()`. * * Timestamp timestamp; * timestamp.set_seconds(time(NULL)); * timestamp.set_nanos(0); * * Example 2: Compute Timestamp from POSIX `gettimeofday()`. * * struct timeval tv; * gettimeofday(&tv, NULL); * * Timestamp timestamp; * timestamp.set_seconds(tv.tv_sec); * timestamp.set_nanos(tv.tv_usec * 1000); * * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. * * FILETIME ft; * GetSystemTimeAsFileTime(&ft); * UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; * * // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z * // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. * Timestamp timestamp; * timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); * timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); * * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. * * long millis = System.currentTimeMillis(); * * Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) * .setNanos((int) ((millis % 1000) * 1000000)).build(); * * * Example 5: Compute Timestamp from Java `Instant.now()`. * * Instant now = Instant.now(); * * Timestamp timestamp = * Timestamp.newBuilder().setSeconds(now.getEpochSecond()) * .setNanos(now.getNano()).build(); * * * Example 6: Compute Timestamp from current time in Python. * * timestamp = Timestamp() * timestamp.GetCurrentTime() * * # JSON Mapping * * In JSON format, the Timestamp type is encoded as a string in the * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the * format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" * where {year} is always expressed using four digits while {month}, {day}, * {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional * seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), * are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone * is required. A proto3 JSON serializer should always use UTC (as indicated by * "Z") when printing the Timestamp type and a proto3 JSON parser should be * able to accept both UTC and other timezones (as indicated by an offset). * * For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past * 01:30 UTC on January 15, 2017. * * In JavaScript, one can convert a Date object to this format using the * standard * [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) * method. In Python, a standard `datetime.datetime` object can be converted * to this format using * [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with * the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use * the Joda Time's [`ISODateTimeFormat.dateTime()`]( * http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D * ) to obtain a formatter capable of generating timestamps in this format. */ export class Timestamp { /** * Represents seconds of UTC time since Unix epoch * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to * 9999-12-31T23:59:59Z inclusive. */ public seconds: i64; /** * Non-negative fractions of a second at nanosecond resolution. Negative * second values with fractions must still have non-negative nanos values * that count forward in time. Must be from 0 to 999,999,999 * inclusive. */ public nanos: i32; // Decodes Timestamp from an ArrayBuffer static decode(buf: ArrayBuffer): Timestamp { return Timestamp.decodeDataView(new DataView(buf)); } // Decodes Timestamp from a DataView static decodeDataView(view: DataView): Timestamp { const decoder = new __proto.Decoder(view); const obj = new Timestamp(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { obj.seconds = decoder.int64(); break; } case 2: { obj.nanos = decoder.int32(); break; } default: decoder.skipType(tag & 7); break; } } return obj; } // decode Timestamp public size(): u32 { let size: u32 = 0; size += this.seconds == 0 ? 0 : 1 + __proto.Sizer.int64(this.seconds); size += this.nanos == 0 ? 0 : 1 + __proto.Sizer.int32(this.nanos); return size; } // Encodes Timestamp to the ArrayBuffer encode(): ArrayBuffer { return changetype<ArrayBuffer>( StaticArray.fromArray<u8>(this.encodeU8Array()) ); } // Encodes Timestamp to the Array<u8> encodeU8Array( encoder: __proto.Encoder = new __proto.Encoder(new Array<u8>()) ): Array<u8> { const buf = encoder.buf; if (this.seconds != 0) { encoder.uint32(0x8); encoder.int64(this.seconds); } if (this.nanos != 0) { encoder.uint32(0x10); encoder.int32(this.nanos); } return buf; } // encode Timestamp } // Timestamp } // protobuf } // google // Status represents object status export enum Status { Draft = 0, Active = 1, Deleted = 2, } // Status // Labels represents object labels export class Labels { // Labels represents array of labels public Labels: Array<string> = new Array<string>(); // Decodes Labels from an ArrayBuffer static decode(buf: ArrayBuffer): Labels { return Labels.decodeDataView(new DataView(buf)); } // Decodes Labels from a DataView static decodeDataView(view: DataView): Labels { const decoder = new __proto.Decoder(view); const obj = new Labels(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { obj.Labels.push(decoder.string()); break; } default: decoder.skipType(tag & 7); break; } } return obj; } // decode Labels public size(): u32 { let size: u32 = 0; size += __size_string_repeated(this.Labels); return size; } // Encodes Labels to the ArrayBuffer encode(): ArrayBuffer { return changetype<ArrayBuffer>( StaticArray.fromArray<u8>(this.encodeU8Array()) ); } // Encodes Labels to the Array<u8> encodeU8Array( encoder: __proto.Encoder = new __proto.Encoder(new Array<u8>()) ): Array<u8> { const buf = encoder.buf; if (this.Labels.length > 0) { for (let n: i32 = 0; n < this.Labels.length; n++) { encoder.uint32(0xa); encoder.uint32(this.Labels[n].length); encoder.string(this.Labels[n]); } } return buf; } // encode Labels } // Labels // Message is the base message structure export class Message { public String: string = ""; public Labels: Labels = new Labels(); public Status1: u32; public Status2: u32; public Network: u32; public Strings: Array<string> = new Array<string>(); public MapString: Map<string, string> = new Map<string, string>(); public MapMessages: Map<string, Message_Message> = new Map< string, Message_Message >(); public Properties1: external.Properties = new external.Properties(); public Properties2: external.external.Properties = new external.external.Properties(); public Services: Array<u32> = new Array<u32>(); // Decodes Message from an ArrayBuffer static decode(buf: ArrayBuffer): Message { return Message.decodeDataView(new DataView(buf)); } // Decodes Message from a DataView static decodeDataView(view: DataView): Message { const decoder = new __proto.Decoder(view); const obj = new Message(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { obj.String = decoder.string(); break; } case 2: { const length = decoder.uint32(); obj.Labels = Labels.decodeDataView( new DataView( decoder.view.buffer, decoder.pos + decoder.view.byteOffset, length ) ); decoder.skip(length); break; } case 3: { obj.Status1 = decoder.uint32(); break; } case 4: { obj.Status2 = decoder.uint32(); break; } case 5: { obj.Network = decoder.uint32(); break; } case 6: { obj.Strings.push(decoder.string()); break; } case 7: { const length = decoder.uint32(); __decodeMap_string_string(decoder, length, obj.MapString); decoder.skip(length); break; } case 8: { const length = decoder.uint32(); __decodeMap_string_Message_Message(decoder, length, obj.MapMessages); decoder.skip(length); break; } case 11: { const length = decoder.uint32(); obj.Properties1 = external.Properties.decodeDataView( new DataView( decoder.view.buffer, decoder.pos + decoder.view.byteOffset, length ) ); decoder.skip(length); break; } case 12: { const length = decoder.uint32(); obj.Properties2 = external.external.Properties.decodeDataView( new DataView( decoder.view.buffer, decoder.pos + decoder.view.byteOffset, length ) ); decoder.skip(length); break; } case 13: { const endPos = decoder.pos + decoder.uint32(); while (decoder.pos <= endPos) { obj.Services.push(decoder.uint32()); } break; } default: decoder.skipType(tag & 7); break; } } return obj; } // decode Message public size(): u32 { let size: u32 = 0; size += this.String.length > 0 ? 1 + __proto.Sizer.varint64(this.String.length) + this.String.length : 0; if (this.Labels != null) { const f: Labels = this.Labels as Labels; const messageSize = f.size(); if (messageSize > 0) { size += 1 + __proto.Sizer.varint64(messageSize) + messageSize; } } size += this.Status1 == 0 ? 0 : 1 + __proto.Sizer.uint32(this.Status1); size += this.Status2 == 0 ? 0 : 1 + __proto.Sizer.uint32(this.Status2); size += this.Network == 0 ? 0 : 1 + __proto.Sizer.uint32(this.Network); size += __size_string_repeated(this.Strings); if (this.MapString.size > 0) { const keys = this.MapString.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.MapString.get(key); const itemSize = __sizeMapEntry_string_string(key, value); if (itemSize > 0) { size += 1 + __proto.Sizer.varint64(itemSize) + itemSize; } } } if (this.MapMessages.size > 0) { const keys = this.MapMessages.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.MapMessages.get(key); const itemSize = __sizeMapEntry_string_Message_Message(key, value); if (itemSize > 0) { size += 1 + __proto.Sizer.varint64(itemSize) + itemSize; } } } if (this.Properties1 != null) { const f: external.Properties = this.Properties1 as external.Properties; const messageSize = f.size(); if (messageSize > 0) { size += 1 + __proto.Sizer.varint64(messageSize) + messageSize; } } if (this.Properties2 != null) { const f: external.external.Properties = this .Properties2 as external.external.Properties; const messageSize = f.size(); if (messageSize > 0) { size += 1 + __proto.Sizer.varint64(messageSize) + messageSize; } } if (this.Services.length > 0) { const packedSize = __size_uint32_repeated_packed(this.Services); if (packedSize > 0) { size += 1 + __proto.Sizer.varint64(packedSize) + packedSize; } } return size; } // Encodes Message to the ArrayBuffer encode(): ArrayBuffer { return changetype<ArrayBuffer>( StaticArray.fromArray<u8>(this.encodeU8Array()) ); } // Encodes Message to the Array<u8> encodeU8Array( encoder: __proto.Encoder = new __proto.Encoder(new Array<u8>()) ): Array<u8> { const buf = encoder.buf; if (this.String.length > 0) { encoder.uint32(0xa); encoder.uint32(this.String.length); encoder.string(this.String); } if (this.Labels != null) { const f = this.Labels as Labels; const messageSize = f.size(); if (messageSize > 0) { encoder.uint32(0x12); encoder.uint32(messageSize); f.encodeU8Array(encoder); } } if (this.Status1 != 0) { encoder.uint32(0x18); encoder.uint32(this.Status1); } if (this.Status2 != 0) { encoder.uint32(0x20); encoder.uint32(this.Status2); } if (this.Network != 0) { encoder.uint32(0x28); encoder.uint32(this.Network); } if (this.Strings.length > 0) { for (let n: i32 = 0; n < this.Strings.length; n++) { encoder.uint32(0x32); encoder.uint32(this.Strings[n].length); encoder.string(this.Strings[n]); } } if (this.MapString.size > 0) { const keys = this.MapString.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.MapString.get(key); const size = __sizeMapEntry_string_string(key, value); if (size > 0) { encoder.uint32(0x3a); encoder.uint32(size); if (key.length > 0) { encoder.uint32(0xa); encoder.uint32(key.length); encoder.string(key); } if (value.length > 0) { encoder.uint32(0x12); encoder.uint32(value.length); encoder.string(value); } } } } if (this.MapMessages.size > 0) { const keys = this.MapMessages.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.MapMessages.get(key); const size = __sizeMapEntry_string_Message_Message(key, value); if (size > 0) { encoder.uint32(0x42); encoder.uint32(size); if (key.length > 0) { encoder.uint32(0xa); encoder.uint32(key.length); encoder.string(key); } const messageSize = value.size(); if (messageSize > 0) { encoder.uint32(0x12); encoder.uint32(messageSize); value.encodeU8Array(encoder); } } } } if (this.Properties1 != null) { const f = this.Properties1 as external.Properties; const messageSize = f.size(); if (messageSize > 0) { encoder.uint32(0x5a); encoder.uint32(messageSize); f.encodeU8Array(encoder); } } if (this.Properties2 != null) { const f = this.Properties2 as external.external.Properties; const messageSize = f.size(); if (messageSize > 0) { encoder.uint32(0x62); encoder.uint32(messageSize); f.encodeU8Array(encoder); } } if (this.Services.length > 0) { encoder.uint32(0x6a); encoder.uint32(__size_uint32_repeated_packed(this.Services)); for (let n: i32 = 0; n < this.Services.length; n++) { encoder.uint32(this.Services[n]); } } return buf; } // encode Message } // Message /** * NOTE: AssemblyScript crashes on generation of bindings for circular dependencies. Check in further versions. * * * message Circular { * string String = 1; * Circular Circular = 2; * } * * * message CircularA { * string String = 1; * CircularB CircularB = 2; * } * * * message CircularB { * string String = 1; * CircularA CircularA = 2; * } * Enum is nested enum */ export enum Message_Service { // None None = 0, // Facebook profile Facebook = 1, // Google profile Google = 2, } // Message_Service // Message.Message is the nested Message structure export class Message_Message { public String: string = ""; public Messages: Map<string, Message_Message> = new Map< string, Message_Message >(); // Decodes Message_Message from an ArrayBuffer static decode(buf: ArrayBuffer): Message_Message { return Message_Message.decodeDataView(new DataView(buf)); } // Decodes Message_Message from a DataView static decodeDataView(view: DataView): Message_Message { const decoder = new __proto.Decoder(view); const obj = new Message_Message(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { obj.String = decoder.string(); break; } case 2: { const length = decoder.uint32(); __decodeMap_string_Message_Message(decoder, length, obj.Messages); decoder.skip(length); break; } default: decoder.skipType(tag & 7); break; } } return obj; } // decode Message_Message public size(): u32 { let size: u32 = 0; size += this.String.length > 0 ? 1 + __proto.Sizer.varint64(this.String.length) + this.String.length : 0; if (this.Messages.size > 0) { const keys = this.Messages.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.Messages.get(key); const itemSize = __sizeMapEntry_string_Message_Message(key, value); if (itemSize > 0) { size += 1 + __proto.Sizer.varint64(itemSize) + itemSize; } } } return size; } // Encodes Message_Message to the ArrayBuffer encode(): ArrayBuffer { return changetype<ArrayBuffer>( StaticArray.fromArray<u8>(this.encodeU8Array()) ); } // Encodes Message_Message to the Array<u8> encodeU8Array( encoder: __proto.Encoder = new __proto.Encoder(new Array<u8>()) ): Array<u8> { const buf = encoder.buf; if (this.String.length > 0) { encoder.uint32(0xa); encoder.uint32(this.String.length); encoder.string(this.String); } if (this.Messages.size > 0) { const keys = this.Messages.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.Messages.get(key); const size = __sizeMapEntry_string_Message_Message(key, value); if (size > 0) { encoder.uint32(0x12); encoder.uint32(size); if (key.length > 0) { encoder.uint32(0xa); encoder.uint32(key.length); encoder.string(key); } const messageSize = value.size(); if (messageSize > 0) { encoder.uint32(0x12); encoder.uint32(messageSize); value.encodeU8Array(encoder); } } } } return buf; } // encode Message_Message } // Message_Message // Message.Message.Message is the Message structure nested into nested structure export class Message_Message_Message { // Example strings public Strings: Array<string> = new Array<string>(); // Protobuf timestamp public Timestamp: google.protobuf.Timestamp = new google.protobuf.Timestamp(); // Decodes Message_Message_Message from an ArrayBuffer static decode(buf: ArrayBuffer): Message_Message_Message { return Message_Message_Message.decodeDataView(new DataView(buf)); } // Decodes Message_Message_Message from a DataView static decodeDataView(view: DataView): Message_Message_Message { const decoder = new __proto.Decoder(view); const obj = new Message_Message_Message(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { obj.Strings.push(decoder.string()); break; } case 2: { const length = decoder.uint32(); obj.Timestamp = google.protobuf.Timestamp.decodeDataView( new DataView( decoder.view.buffer, decoder.pos + decoder.view.byteOffset, length ) ); decoder.skip(length); break; } default: decoder.skipType(tag & 7); break; } } return obj; } // decode Message_Message_Message public size(): u32 { let size: u32 = 0; size += __size_string_repeated(this.Strings); if (this.Timestamp != null) { const f: google.protobuf.Timestamp = this .Timestamp as google.protobuf.Timestamp; const messageSize = f.size(); if (messageSize > 0) { size += 1 + __proto.Sizer.varint64(messageSize) + messageSize; } } return size; } // Encodes Message_Message_Message to the ArrayBuffer encode(): ArrayBuffer { return changetype<ArrayBuffer>( StaticArray.fromArray<u8>(this.encodeU8Array()) ); } // Encodes Message_Message_Message to the Array<u8> encodeU8Array( encoder: __proto.Encoder = new __proto.Encoder(new Array<u8>()) ): Array<u8> { const buf = encoder.buf; if (this.Strings.length > 0) { for (let n: i32 = 0; n < this.Strings.length; n++) { encoder.uint32(0xa); encoder.uint32(this.Strings[n].length); encoder.string(this.Strings[n]); } } if (this.Timestamp != null) { const f = this.Timestamp as google.protobuf.Timestamp; const messageSize = f.size(); if (messageSize > 0) { encoder.uint32(0x12); encoder.uint32(messageSize); f.encodeU8Array(encoder); } } return buf; } // encode Message_Message_Message } // Message_Message_Message // __size_string_repeated function __size_string_repeated(value: Array<string>): u32 { let size: u32 = 0; for (let n: i32 = 0; n < value.length; n++) { size += 1 + __proto.Sizer.varint64(value[n].length) + value[n].length; } return size; } // __decodeMap_string_string function __decodeMap_string_string( parentDecoder: __proto.Decoder, length: i32, map: Map<string, string> ): void { const decoder = new __proto.Decoder( new DataView( parentDecoder.view.buffer, parentDecoder.pos + parentDecoder.view.byteOffset, length ) ); let key: string = ""; let value: string = ""; while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { key = decoder.string(); break; } case 2: { value = decoder.string(); break; } default: decoder.skipType(tag & 7); break; } } map.set(key as string, value as string); } // __decodeMap_string_Message_Message function __decodeMap_string_Message_Message( parentDecoder: __proto.Decoder, length: i32, map: Map<string, Message_Message> ): void { const decoder = new __proto.Decoder( new DataView( parentDecoder.view.buffer, parentDecoder.pos + parentDecoder.view.byteOffset, length ) ); let key: string = ""; let value: Message_Message = new Message_Message(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { key = decoder.string(); break; } case 2: { const length = decoder.uint32(); value = Message_Message.decodeDataView( new DataView( decoder.view.buffer, decoder.pos + decoder.view.byteOffset, length ) ); decoder.skip(length); break; } default: decoder.skipType(tag & 7); break; } } map.set(key as string, value as Message_Message); } // __sizeMapEntry_string_string function __sizeMapEntry_string_string(key: string, value: string): u32 { return ( (key.length > 0 ? 1 + __proto.Sizer.varint64(key.length) + key.length : 0) + (value.length > 0 ? 1 + __proto.Sizer.varint64(value.length) + value.length : 0) ); } // __sizeMapEntry_string_Message_Message function __sizeMapEntry_string_Message_Message( key: string, value: Message_Message ): u32 { const keySize = key.length > 0 ? 1 + __proto.Sizer.varint64(key.length) + key.length : 0; const valueSize = value.size(); if (valueSize == 0) { return keySize; } return keySize + 1 + __proto.Sizer.varint64(valueSize) + valueSize; } // __size_uint32_repeated_packed function __size_uint32_repeated_packed(value: Array<u32>): u32 { let size: u32 = 0; for (let n: i32 = 0; n < value.length; n++) { size += __proto.Sizer.uint32(value[n]); } return size; }
gzigzigzeo/protobuf-as
src/walker_as/index.ts
<filename>src/walker_as/index.ts export * from './walker_as_single_file.js'; export * from './walker_as_multi_file.js'; // Writer implements generic function which prints a code piece export type Writer = (value: string) => void; // Global code blocks registry export interface GlobalsRegistry { registerGlobal(key: string, content: string): void; }
gzigzigzeo/protobuf-as
tests/__fixtures__/as_proto/maps/maps.ts
<gh_stars>1-10 namespace __proto { /** * Decoder implements protobuf message decode interface. * * Useful references: * * Protocol Buffer encoding: https://developers.google.com/protocol-buffers/docs/encoding * LEB128 encoding AKA varint 128 encoding: https://en.wikipedia.org/wiki/LEB128 * ZigZag encoding/decoding (s32/s64): https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba */ export class Decoder { public view: DataView; public pos: i32; constructor(view: DataView) { this.view = view; this.pos = 0; } /** * Returns true if current reader has reached the buffer end * @returns True if current reader has reached the buffer end */ @inline eof(): bool { return this.pos >= this.view.byteLength; } /** * Returns current buffer length in bytes * @returns Length in bytes */ @inline get byteLength(): i32 { return this.view.byteLength; } /** * An alias method to fetch tag from the reader. Supposed to return tuple of [field number, wire_type]. * TODO: Replace with return tuple when tuples become implemented in AS. * @returns Message tag value */ @inline tag(): u32 { return this.uint32(); } /** * Returns byte at offset, alias for getUint8 * @param byteOffset Offset * @returns u8 */ @inline private u8at(byteOffset: i32): u8 { return this.view.getUint8(byteOffset); } /** * Reads and returns varint number (128 + 10 bits max) from a current position. * @returns Returns varint */ varint(): u64 { let value: u64; // u32 value = (u64(u8(this.u8at(this.pos))) & 127) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 7)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 14)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 21)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; // u32 remainder or u64 byte value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 28)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; // u64 value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 35)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 42)) /* 42!!! */ >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 49)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 28)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; // u64 remainder value = (value | ((u64(u8(this.u8at(this.pos))) & 127) << 35)) >>> 0; if (u8(this.u8at(this.pos++)) < 128) return value; if (this.pos > this.byteLength) { this.throwOutOfRange(); } return value; } @inline int32(): i32 { return i32(this.varint()); } @inline int64(): i64 { return i32(this.varint()); } @inline uint32(): u32 { return u32(this.varint()); } @inline uint64(): u64 { return u64(this.varint()); } @inline sint32(): i32 { const n: u64 = this.varint(); return i32((n >>> 1) ^ -(n & 1)); } @inline sint64(): i64 { const n: u64 = this.varint(); return i64((n >>> 1) ^ -(n & 1)); } fixed32(): u32 { this.pos += 4; if (this.pos > this.byteLength) { this.throwOutOfRange(); } // u32(u8) ensures that u8(-1) becomes u32(4294967295) instead of u8(255) return ( u32(u8(this.u8at(this.pos - 4))) | (u32(u8(this.u8at(this.pos - 3))) << 8) | (u32(u8(this.u8at(this.pos - 2))) << 16) | (u32(u8(this.u8at(this.pos - 1))) << 24) ); } @inline sfixed32(): i32 { return i32(this.fixed32()); } fixed64(): u64 { this.pos += 8; if (this.pos > this.byteLength) { this.throwOutOfRange(); } return ( u64(u8(this.u8at(this.pos - 8))) | (u64(u8(this.u8at(this.pos - 7))) << 8) | (u64(u8(this.u8at(this.pos - 6))) << 16) | (u64(u8(this.u8at(this.pos - 5))) << 24) | (u64(u8(this.u8at(this.pos - 4))) << 32) | (u64(u8(this.u8at(this.pos - 3))) << 40) | (u64(u8(this.u8at(this.pos - 2))) << 48) | (u64(u8(this.u8at(this.pos - 1))) << 56) ); } @inline sfixed64(): i64 { return i64(this.fixed64()); } @inline float(): f32 { return f32.reinterpret_i32(this.fixed32()); } @inline double(): f64 { return f64.reinterpret_i64(this.fixed64()); } @inline bool(): boolean { return this.uint32() > 0; } /** * Reads and returns UTF8 string. * @returns String */ string(): string { const length = this.uint32(); if (this.pos + length > this.byteLength) { this.throwOutOfRange(); } const p = this.pos + this.view.byteOffset; const value = String.UTF8.decode(this.view.buffer.slice(p, p + length)); this.pos += length; return value; } /** * Reads and returns bytes array. * @returns Array<u8> of bytes */ bytes(): Array<u8> { const len = this.uint32(); if (this.pos + len > this.byteLength) { this.throwOutOfRange(); } const a = new Array<u8>(len); for (let i: u32 = 0; i < len; i++) { a[i] = u8(this.u8at(this.pos++)); } return a; } /** * Skips a message field if it can'be recognized by an object's decode() method * @param wireType Current wire type */ skipType(wireType: u32): void { switch (wireType) { // int32, int64, uint32, uint64, sint32, sint64, bool, enum: varint, variable length case 0: this.varint(); // Just read a varint break; // fixed64, sfixed64, double: 8 bytes always case 1: this.skip(8); break; // length-delimited; length is determined by varint32; skip length bytes; case 2: this.skip(this.uint32()); break; // tart group: skip till the end of the group, then skip group end marker case 3: while ((wireType = this.uint32() & 7) !== 4) { this.skipType(wireType); } break; // fixed32, sfixed32, float: 4 bytes always case 5: this.skip(4); break; // Something went beyond our capability to understand default: throw new Error( `Invalid wire type ${wireType} at offset ${this.pos}` ); } } /** * Fast-forwards cursor by length with boundary check * @param length Byte length */ skip(length: u32): void { if (this.pos + length > this.byteLength) { this.throwOutOfRange(); } this.pos += length; } /** * OutOfRange check. Throws an exception if current position exceeds current buffer range */ @inline private throwOutOfRange(): void { throw new Error(`Decoder position ${this.pos} is out of range!`); } } /** * Encoder implements protobuf message encode interface. This is the simplest not very effective version, which uses * Array<u8>. * * Useful references: * * Protocol Buffer encoding: https://developers.google.com/protocol-buffers/docs/encoding * LEB128 encoding AKA varint 128 encoding: https://en.wikipedia.org/wiki/LEB128 * ZigZag encoding/decoding (s32/s64): https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba */ export class Encoder { public buf: Array<u8>; constructor(buf: Array<u8>) { this.buf = buf; } /** * Encodes varint at a current position * @returns Returns varint */ varint64(value: u64): void { let v: u64 = value; while (v > 127) { this.buf.push(u8((v & 127) | 128)); v = v >> 7; } this.buf.push(u8(v)); } @inline int32(value: i32): void { this.varint64(value); } @inline int64(value: i64): void { this.varint64(value); } @inline uint32(value: u32): void { this.varint64(value); } @inline uint64(value: u64): void { this.varint64(value); } @inline sint32(value: i32): void { this.varint64((value << 1) ^ (value >> 31)); } @inline sint64(value: i64): void { this.varint64((value << 1) ^ (value >> 63)); } @inline fixed32(value: u32): void { this.buf.push(u8(value & 255)); this.buf.push(u8((value >> 8) & 255)); this.buf.push(u8((value >> 16) & 255)); this.buf.push(u8(value >> 24)); } @inline sfixed32(value: i32): void { this.fixed32(u32(value)); } @inline fixed64(value: u64): void { this.buf.push(u8(value & 255)); this.buf.push(u8((value >> 8) & 255)); this.buf.push(u8((value >> 16) & 255)); this.buf.push(u8((value >> 24) & 255)); this.buf.push(u8((value >> 32) & 255)); this.buf.push(u8((value >> 40) & 255)); this.buf.push(u8((value >> 48) & 255)); this.buf.push(u8(value >> 56)); } @inline sfixed64(value: i64): void { this.fixed64(u64(value)); } @inline float(value: f32): void { this.fixed32(u32(i32.reinterpret_f32(value))); } @inline double(value: f64): void { this.fixed64(u64(i64.reinterpret_f64(value))); } @inline bool(value: boolean): void { this.buf.push(value ? 1 : 0); } string(value: string): void { const utf8string = new DataView(String.UTF8.encode(value)); for (let i = 0; i < utf8string.byteLength; i++) { this.buf.push(utf8string.getUint8(i)); } } @inline bytes(value: Array<u8>): void { for (let i = 0; i < value.length; i++) { this.buf.push(value[i]); } } } /** * Returns byte size required to encode a value of a certain type */ export class Sizer { static varint64(value: u64): u32 { return value < 128 ? 1 // 2^7 : value < 16384 ? 2 // 2^14 : value < 2097152 ? 3 // 2^21 : value < 268435456 ? 4 // 2^28 : value < 34359738368 ? 5 // 2^35 : value < 4398046511104 ? 6 // 2^42 : value < 562949953421312 ? 7 // 2^49 : value < 72057594037927936 ? 8 // 2^56 : value < 9223372036854775808 ? 9 // 2^63 : 10; } @inline static int32(value: i32): u32 { return Sizer.varint64(u64(value)); } @inline static int64(value: i64): u32 { return Sizer.varint64(u64(value)); } @inline static uint32(value: u32): u32 { return Sizer.varint64(value); } @inline static uint64(value: u64): u32 { return Sizer.varint64(value); } @inline static sint32(value: i32): u32 { return Sizer.varint64((value << 1) ^ (value >> 31)); } @inline static sint64(value: i64): u32 { return Sizer.varint64((value << 1) ^ (value >> 63)); } @inline static string(value: string): u32 { return value.length; } @inline static bytes(value: Array<u8>): u32 { return value.length; } } } export namespace external { export class MapValue { public Value: string = ""; // Decodes MapValue from an ArrayBuffer static decode(buf: ArrayBuffer): MapValue { return MapValue.decodeDataView(new DataView(buf)); } // Decodes MapValue from a DataView static decodeDataView(view: DataView): MapValue { const decoder = new __proto.Decoder(view); const obj = new MapValue(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { obj.Value = decoder.string(); break; } default: decoder.skipType(tag & 7); break; } } return obj; } // decode MapValue public size(): u32 { let size: u32 = 0; size += this.Value.length > 0 ? 1 + __proto.Sizer.varint64(this.Value.length) + this.Value.length : 0; return size; } // Encodes MapValue to the ArrayBuffer encode(): ArrayBuffer { return changetype<ArrayBuffer>( StaticArray.fromArray<u8>(this.encodeU8Array()) ); } // Encodes MapValue to the Array<u8> encodeU8Array( encoder: __proto.Encoder = new __proto.Encoder(new Array<u8>()) ): Array<u8> { const buf = encoder.buf; if (this.Value.length > 0) { encoder.uint32(0xa); encoder.uint32(this.Value.length); encoder.string(this.Value); } return buf; } // encode MapValue } // MapValue } // external export class Value { public Int32s: Array<i32> = new Array<i32>(); // Decodes Value from an ArrayBuffer static decode(buf: ArrayBuffer): Value { return Value.decodeDataView(new DataView(buf)); } // Decodes Value from a DataView static decodeDataView(view: DataView): Value { const decoder = new __proto.Decoder(view); const obj = new Value(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { const endPos = decoder.pos + decoder.uint32(); while (decoder.pos <= endPos) { obj.Int32s.push(decoder.int32()); } break; } default: decoder.skipType(tag & 7); break; } } return obj; } // decode Value public size(): u32 { let size: u32 = 0; if (this.Int32s.length > 0) { const packedSize = __size_int32_repeated_packed(this.Int32s); if (packedSize > 0) { size += 1 + __proto.Sizer.varint64(packedSize) + packedSize; } } return size; } // Encodes Value to the ArrayBuffer encode(): ArrayBuffer { return changetype<ArrayBuffer>( StaticArray.fromArray<u8>(this.encodeU8Array()) ); } // Encodes Value to the Array<u8> encodeU8Array( encoder: __proto.Encoder = new __proto.Encoder(new Array<u8>()) ): Array<u8> { const buf = encoder.buf; if (this.Int32s.length > 0) { encoder.uint32(0xa); encoder.uint32(__size_int32_repeated_packed(this.Int32s)); for (let n: i32 = 0; n < this.Int32s.length; n++) { encoder.int32(this.Int32s[n]); } } return buf; } // encode Value } // Value export class Maps { public StringStringMap: Map<string, string> = new Map<string, string>(); public StringInt32Map: Map<string, i32> = new Map<string, i32>(); public Int32StringMap: Map<i32, string> = new Map<i32, string>(); public StringValueMap: Map<string, Value> = new Map<string, Value>(); public StringExternalMapValue: Map<string, external.MapValue> = new Map< string, external.MapValue >(); // Decodes Maps from an ArrayBuffer static decode(buf: ArrayBuffer): Maps { return Maps.decodeDataView(new DataView(buf)); } // Decodes Maps from a DataView static decodeDataView(view: DataView): Maps { const decoder = new __proto.Decoder(view); const obj = new Maps(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { const length = decoder.uint32(); __decodeMap_string_string(decoder, length, obj.StringStringMap); decoder.skip(length); break; } case 2: { const length = decoder.uint32(); __decodeMap_string_i32(decoder, length, obj.StringInt32Map); decoder.skip(length); break; } case 3: { const length = decoder.uint32(); __decodeMap_i32_string(decoder, length, obj.Int32StringMap); decoder.skip(length); break; } case 4: { const length = decoder.uint32(); __decodeMap_string_Value(decoder, length, obj.StringValueMap); decoder.skip(length); break; } case 5: { const length = decoder.uint32(); __decodeMap_string_external_MapValue( decoder, length, obj.StringExternalMapValue ); decoder.skip(length); break; } default: decoder.skipType(tag & 7); break; } } return obj; } // decode Maps public size(): u32 { let size: u32 = 0; if (this.StringStringMap.size > 0) { const keys = this.StringStringMap.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.StringStringMap.get(key); const itemSize = __sizeMapEntry_string_string(key, value); if (itemSize > 0) { size += 1 + __proto.Sizer.varint64(itemSize) + itemSize; } } } if (this.StringInt32Map.size > 0) { const keys = this.StringInt32Map.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.StringInt32Map.get(key); const itemSize = __sizeMapEntry_string_i32(key, value); if (itemSize > 0) { size += 1 + __proto.Sizer.varint64(itemSize) + itemSize; } } } if (this.Int32StringMap.size > 0) { const keys = this.Int32StringMap.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.Int32StringMap.get(key); const itemSize = __sizeMapEntry_i32_string(key, value); if (itemSize > 0) { size += 1 + __proto.Sizer.varint64(itemSize) + itemSize; } } } if (this.StringValueMap.size > 0) { const keys = this.StringValueMap.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.StringValueMap.get(key); const itemSize = __sizeMapEntry_string_Value(key, value); if (itemSize > 0) { size += 1 + __proto.Sizer.varint64(itemSize) + itemSize; } } } if (this.StringExternalMapValue.size > 0) { const keys = this.StringExternalMapValue.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.StringExternalMapValue.get(key); const itemSize = __sizeMapEntry_string_external_MapValue(key, value); if (itemSize > 0) { size += 1 + __proto.Sizer.varint64(itemSize) + itemSize; } } } return size; } // Encodes Maps to the ArrayBuffer encode(): ArrayBuffer { return changetype<ArrayBuffer>( StaticArray.fromArray<u8>(this.encodeU8Array()) ); } // Encodes Maps to the Array<u8> encodeU8Array( encoder: __proto.Encoder = new __proto.Encoder(new Array<u8>()) ): Array<u8> { const buf = encoder.buf; if (this.StringStringMap.size > 0) { const keys = this.StringStringMap.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.StringStringMap.get(key); const size = __sizeMapEntry_string_string(key, value); if (size > 0) { encoder.uint32(0xa); encoder.uint32(size); if (key.length > 0) { encoder.uint32(0xa); encoder.uint32(key.length); encoder.string(key); } if (value.length > 0) { encoder.uint32(0x12); encoder.uint32(value.length); encoder.string(value); } } } } if (this.StringInt32Map.size > 0) { const keys = this.StringInt32Map.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.StringInt32Map.get(key); const size = __sizeMapEntry_string_i32(key, value); if (size > 0) { encoder.uint32(0x12); encoder.uint32(size); if (key.length > 0) { encoder.uint32(0xa); encoder.uint32(key.length); encoder.string(key); } if (value != 0) { encoder.uint32(0x10); encoder.int32(value); } } } } if (this.Int32StringMap.size > 0) { const keys = this.Int32StringMap.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.Int32StringMap.get(key); const size = __sizeMapEntry_i32_string(key, value); if (size > 0) { encoder.uint32(0x1a); encoder.uint32(size); if (key != 0) { encoder.uint32(0x8); encoder.int32(key); } if (value.length > 0) { encoder.uint32(0x12); encoder.uint32(value.length); encoder.string(value); } } } } if (this.StringValueMap.size > 0) { const keys = this.StringValueMap.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.StringValueMap.get(key); const size = __sizeMapEntry_string_Value(key, value); if (size > 0) { encoder.uint32(0x22); encoder.uint32(size); if (key.length > 0) { encoder.uint32(0xa); encoder.uint32(key.length); encoder.string(key); } const messageSize = value.size(); if (messageSize > 0) { encoder.uint32(0x12); encoder.uint32(messageSize); value.encodeU8Array(encoder); } } } } if (this.StringExternalMapValue.size > 0) { const keys = this.StringExternalMapValue.keys(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = this.StringExternalMapValue.get(key); const size = __sizeMapEntry_string_external_MapValue(key, value); if (size > 0) { encoder.uint32(0x2a); encoder.uint32(size); if (key.length > 0) { encoder.uint32(0xa); encoder.uint32(key.length); encoder.string(key); } const messageSize = value.size(); if (messageSize > 0) { encoder.uint32(0x12); encoder.uint32(messageSize); value.encodeU8Array(encoder); } } } } return buf; } // encode Maps } // Maps // __size_int32_repeated_packed function __size_int32_repeated_packed(value: Array<i32>): u32 { let size: u32 = 0; for (let n: i32 = 0; n < value.length; n++) { size += __proto.Sizer.int32(value[n]); } return size; } // __decodeMap_string_string function __decodeMap_string_string( parentDecoder: __proto.Decoder, length: i32, map: Map<string, string> ): void { const decoder = new __proto.Decoder( new DataView( parentDecoder.view.buffer, parentDecoder.pos + parentDecoder.view.byteOffset, length ) ); let key: string = ""; let value: string = ""; while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { key = decoder.string(); break; } case 2: { value = decoder.string(); break; } default: decoder.skipType(tag & 7); break; } } map.set(key as string, value as string); } // __decodeMap_string_i32 function __decodeMap_string_i32( parentDecoder: __proto.Decoder, length: i32, map: Map<string, i32> ): void { const decoder = new __proto.Decoder( new DataView( parentDecoder.view.buffer, parentDecoder.pos + parentDecoder.view.byteOffset, length ) ); let key: string = ""; let value: i32; while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { key = decoder.string(); break; } case 2: { value = decoder.int32(); break; } default: decoder.skipType(tag & 7); break; } } map.set(key as string, value as i32); } // __decodeMap_i32_string function __decodeMap_i32_string( parentDecoder: __proto.Decoder, length: i32, map: Map<i32, string> ): void { const decoder = new __proto.Decoder( new DataView( parentDecoder.view.buffer, parentDecoder.pos + parentDecoder.view.byteOffset, length ) ); let key: i32; let value: string = ""; while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { key = decoder.int32(); break; } case 2: { value = decoder.string(); break; } default: decoder.skipType(tag & 7); break; } } map.set(key as i32, value as string); } // __decodeMap_string_Value function __decodeMap_string_Value( parentDecoder: __proto.Decoder, length: i32, map: Map<string, Value> ): void { const decoder = new __proto.Decoder( new DataView( parentDecoder.view.buffer, parentDecoder.pos + parentDecoder.view.byteOffset, length ) ); let key: string = ""; let value: Value = new Value(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { key = decoder.string(); break; } case 2: { const length = decoder.uint32(); value = Value.decodeDataView( new DataView( decoder.view.buffer, decoder.pos + decoder.view.byteOffset, length ) ); decoder.skip(length); break; } default: decoder.skipType(tag & 7); break; } } map.set(key as string, value as Value); } // __decodeMap_string_external_MapValue function __decodeMap_string_external_MapValue( parentDecoder: __proto.Decoder, length: i32, map: Map<string, external.MapValue> ): void { const decoder = new __proto.Decoder( new DataView( parentDecoder.view.buffer, parentDecoder.pos + parentDecoder.view.byteOffset, length ) ); let key: string = ""; let value: external.MapValue = new external.MapValue(); while (!decoder.eof()) { const tag = decoder.tag(); const number = tag >>> 3; switch (number) { case 1: { key = decoder.string(); break; } case 2: { const length = decoder.uint32(); value = external.MapValue.decodeDataView( new DataView( decoder.view.buffer, decoder.pos + decoder.view.byteOffset, length ) ); decoder.skip(length); break; } default: decoder.skipType(tag & 7); break; } } map.set(key as string, value as external.MapValue); } // __sizeMapEntry_string_string function __sizeMapEntry_string_string(key: string, value: string): u32 { return ( (key.length > 0 ? 1 + __proto.Sizer.varint64(key.length) + key.length : 0) + (value.length > 0 ? 1 + __proto.Sizer.varint64(value.length) + value.length : 0) ); } // __sizeMapEntry_string_i32 function __sizeMapEntry_string_i32(key: string, value: i32): u32 { return ( (key.length > 0 ? 1 + __proto.Sizer.varint64(key.length) + key.length : 0) + (value == 0 ? 0 : 1 + __proto.Sizer.int32(value)) ); } // __sizeMapEntry_i32_string function __sizeMapEntry_i32_string(key: i32, value: string): u32 { return ( (key == 0 ? 0 : 1 + __proto.Sizer.int32(key)) + (value.length > 0 ? 1 + __proto.Sizer.varint64(value.length) + value.length : 0) ); } // __sizeMapEntry_string_Value function __sizeMapEntry_string_Value(key: string, value: Value): u32 { const keySize = key.length > 0 ? 1 + __proto.Sizer.varint64(key.length) + key.length : 0; const valueSize = value.size(); if (valueSize == 0) { return keySize; } return keySize + 1 + __proto.Sizer.varint64(valueSize) + valueSize; } // __sizeMapEntry_string_external_MapValue function __sizeMapEntry_string_external_MapValue( key: string, value: external.MapValue ): u32 { const keySize = key.length > 0 ? 1 + __proto.Sizer.varint64(key.length) + key.length : 0; const valueSize = value.size(); if (valueSize == 0) { return keySize; } return keySize + 1 + __proto.Sizer.varint64(valueSize) + valueSize; }
gzigzigzeo/protobuf-as
tests/__fixtures__/assembly/maps.ts
import { Maps } from '../as_proto/maps/maps'; export function encode(obj: Maps): ArrayBuffer { return obj.encode() } export function decode(buffer: ArrayBuffer): Maps { return Maps.decode(buffer) } export function size(obj: Maps): u32 { return obj.size() }
gzigzigzeo/protobuf-as
src/walker_as/internal.ts
import { decorated, named } from '../proto/index.js'; import path from 'path'; import { fileURLToPath } from 'url'; import changeCase from 'change-case'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // embedNamespace represents Decode, Encode and Size namespace name export const embedNamespace = "__proto"; // staticFiles represents list of static files to embed/copy export const staticFiles = [ path.join(__dirname, '../../assembly/decoder.ts'), path.join(__dirname, '../../assembly/encoder.ts'), path.join(__dirname, '../../assembly/sizer.ts'), ] // Generates "// DEPRECATED" comment export function deprecatedComment(obj: decorated.Depricable) { return `${obj.deprecated ? "// DEPRECATED" : ""}` } // Returns message name relative to current namespace, replacing nesting with "_" export function relativeName(name: string):string { return named.normalize(name).replace(/[.]+/g, "_") } // Returns message name with namespace (if required), replacing nesting with "_" export function absoluteName(obj: decorated.Named, ns: string): string { if (obj.namespace != ns) { return named.normalize(obj.namespace + "." + relativeName(obj.relativeName)) } return relativeName(obj.relativeName) } // Returns formatted multiline comment export function comment(obj: decorated.Commented): string { if (obj.comment.trim() == "") { return ""; } const lines = obj.comment.split("\n"); if (lines.length == 1) { return "// " + lines.join().trim() } return "/**\n" + lines.map((value) => " * " + value).join("\n") + "\n */"; } // Converts namespace to ts file name export function namespaceToFileName(obj: decorated.Namespace):string { return obj.id.split(".").map(v => changeCase.snakeCase(v)).join("/") } // Returns relative component of the ts file export function getRelPath(ns: decorated.Namespace):string { const level = ns.id.split(".").length // Relative import path to __proto.ts let rel = ["."] // Nested namespace if (level > 1) { rel = Array<string>(level-1).fill("..") } return rel.join("/") }