repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
culmat/bal-ui-library
|
src/components/bal-field/bal-field.tsx
|
<gh_stars>0
import {Component, Host, h, Prop} from "@stencil/core";
@Component({
tag: "bal-field",
styleUrl: "bal-field.scss",
})
export class BalField {
/**
* Label text
*/
@Prop() label: string = "";
/**
* If `true` a asterix (*) is added to the label text
*/
@Prop() required: boolean = false;
/**
* Validation message text
*/
@Prop() validationMessage: string = "";
/**
* Baloise icon for the right side of the input
*/
@Prop() iconRight: string = "";
/**
* Baloise icon for the left side of the input
*/
@Prop() iconLeft: string = "";
render() {
return (
<Host>
<div class="form">
<label class="label">{this.label}{this.required === true ? "*" : ""}</label>
<div
class={"control" + (this.iconLeft ? " has-icons-left" : "") + (this.iconRight ? " has-icons-right" : "")}>
<slot></slot>
{this.iconLeft ? <span class="icon is-small is-left">
<i class={this.iconLeft}></i>
</span> : ""}
{this.iconRight ? <span class="icon is-small is-right">
<i class={this.iconRight}></i>
</span> : ""}
</div>
<p class="help is-danger">{this.validationMessage}</p>
</div>
</Host>
);
}
}
|
culmat/bal-ui-library
|
src/components/autocomplete/autocomplete.tsx
|
import {Component, Host, h, State, Element, Method, Prop, Watch, Event, EventEmitter, Listen} from "@stencil/core";
@Component({
tag: "bal-autocomplete",
styleUrl: "autocomplete.scss",
shadow: true,
})
export class Autocomplete {
@Element() element!: HTMLElement;
inputElement!: HTMLInputElement;
dropdownContent!: HTMLDivElement;
hasNoData = false;
isPristine = true;
activeItemIndex = -1;
@State() isActive = false;
@Watch("isActive")
async isActiveWatcher(newIsActive: boolean) {
if (newIsActive) {
this.activeItemIndex = 0;
this.isPristine = true;
const items = this.children;
if (items.length > 0) {
const firstVisibleItemIndex = (await this.childrenWithHiddenState).indexOf(false);
this.activeItemIndex = firstVisibleItemIndex;
items.forEach((child, index) =>
child.activated = index === firstVisibleItemIndex);
}
}
}
/**
* If `true` the field expands over the whole width.
*/
@Prop() expanded: boolean = false;
/**
* If `true` the field is disabled
*/
@Prop() disabled: boolean = false;
@Watch("disabled")
disabledWatcher(newValue: boolean) {
if (newValue === true) {
this.isActive = false;
}
}
/**
* The value of the autocomplete.
*/
@Prop() value: string = "";
@Watch("value")
valueWatcher(newValue: string) {
this.inputElement.value = newValue;
this.isActive = false;
}
/**
* Emitted when the checked property has changed.
*/
@Event() balChange!: EventEmitter<string>;
/**
* Emitted when the toggle loses focus.
*/
@Event() balBlur!: EventEmitter<void>;
/**
* Emitted when the toggle has focus..
*/
@Event() balFocus!: EventEmitter<void>;
/**
* Sets the given value to the input, closes the dropdown and triggers a change event.
*/
@Method()
async selectItem(newValue: string): Promise<void> {
this.inputElement.value = newValue;
this.isActive = false;
this.balChange.emit(newValue);
}
componentDidLoad() {
if (this.value) {
this.inputElement.value = this.value;
}
}
get children(): HTMLBalAutocompleteItemElement[] {
return Array.from(
this.element.querySelectorAll<HTMLBalAutocompleteItemElement>("bal-autocomplete-item"),
);
}
get childrenWithHiddenState(): Promise<boolean[]> {
return Promise.all(this.children.map(child => child.isHidden()));
}
async onKeyUp(event: KeyboardEvent) {
if (!this.disabled && ["Enter", "ArrowUp", "ArrowDown"].indexOf(event.key) < 0) {
const inputValue = (event.target as HTMLInputElement).value;
this.isActive = !!inputValue;
const children = this.children;
if (children && children.length > 0) {
children.forEach(child => child.highlightedValue = inputValue);
}
const areChildrenDisplayed = await Promise.all(children.map(child => child.isDisplayed()));
this.hasNoData = areChildrenDisplayed.every(displayed => displayed === false);
}
}
@Listen("click", {target: "document"})
clickOnOutside(event: UIEvent) {
if (!this.element.contains((event.target as any)) && this.isActive) {
this.isActive = false;
}
}
@Listen("keyup")
handleKeyUp(event: KeyboardEvent) {
if (event.key === "Escape") {
event.preventDefault();
this.isActive = false;
}
}
@Listen("keydown")
async handleKeyDown(event: KeyboardEvent) {
if (event.key === "ArrowUp" || event.key === "ArrowDown") {
event.preventDefault();
await this.focusNextItem(event.key === "ArrowDown");
}
if (event.key === "Enter") {
event.preventDefault();
const value = this.children[this.activeItemIndex].value;
this.selectItem(value);
}
}
async getNextItem(): Promise<number> {
let nextIndex;
(await this.childrenWithHiddenState).forEach((isHidden, index) => {
if (index > this.activeItemIndex && !isHidden && nextIndex === undefined) {
nextIndex = index;
}
});
return nextIndex || this.activeItemIndex;
}
async getPreviousItem(): Promise<number> {
let previousIndex = this.activeItemIndex;
(await this.childrenWithHiddenState).forEach((isHidden, index) => {
if (index < this.activeItemIndex && !isHidden) {
previousIndex = index;
}
});
return previousIndex;
}
async focusNextItem(isArrowDown: boolean) {
const children = this.children;
if (children && children.length > 0 && !this.disabled) {
if (isArrowDown) {
this.activeItemIndex = await this.getNextItem();
} else {
this.activeItemIndex = await this.getPreviousItem();
}
const scrollPuffer = 156;
const activeChild = children[this.activeItemIndex];
const visMin = this.dropdownContent.scrollTop + scrollPuffer;
const visMax = this.dropdownContent.scrollTop + scrollPuffer
+ this.dropdownContent.clientHeight - activeChild.clientHeight;
if (activeChild.offsetTop < visMin) {
this.dropdownContent.scrollTop = activeChild.offsetTop - scrollPuffer;
} else if (activeChild.offsetTop >= visMax) {
this.dropdownContent.scrollTop = (
activeChild.offsetTop -
this.dropdownContent.clientHeight +
activeChild.clientHeight
);
}
children
.forEach((child, index) =>
child.activated = index === this.activeItemIndex);
}
}
render() {
return (
<Host>
<div class={[
"dropdown",
this.expanded ? "is-fullwidth" : "",
this.isActive ? "is-active" : "",
].join(" ")}>
<div class="dropdown-trigger">
<div class="autocomplete control">
<input class="input"
placeholder="Placeholder Text"
disabled={this.disabled}
onKeyUp={this.onKeyUp.bind(this)}
onFocus={() => this.balFocus.emit()}
onBlur={() => this.balBlur.emit()}
ref={el => this.inputElement = el as HTMLInputElement}
/>
</div>
</div>
<div class="dropdown-menu" role="menu">
<div class="dropdown-content"
ref={el => this.dropdownContent = el as HTMLDivElement}>
<slot/>
<span class="autocomplete-no-data" style={!this.hasNoData && {display: "none"}}>
<slot name="no-data-content">No Data</slot>
</span>
</div>
</div>
</div>
</Host>
);
}
}
|
culmat/bal-ui-library
|
src/components/bal-datepicker/bal-datepicker.tsx
|
<reponame>culmat/bal-ui-library<filename>src/components/bal-datepicker/bal-datepicker.tsx
import { Component, Host, h, State, Prop, Watch, Event, EventEmitter, Method } from "@stencil/core";
import moment from "moment";
import {i18n} from "./i18n";
moment.defineLocale("it", i18n.it);
moment.defineLocale("fr", i18n.fr);
moment.defineLocale("en", i18n.en);
moment.defineLocale("de", i18n.de);
interface CalendarCell {
date: moment.Moment;
label: string;
dateString: string;
isToday: boolean;
isSelected: boolean;
isDisabled: boolean;
isOutdated: boolean;
}
export type DateCallback = (date: string) => boolean;
@Component({
tag: "bal-datepicker",
styleUrl: "bal-datepicker.scss",
})
export class BalDatepicker {
static FORMAT = "DD.MM.YYYY";
inputElement!: HTMLInputElement;
dropDownElement!: HTMLBalDropdownElement;
now: moment.Moment = moment().startOf("day");
@State() isPristine = true;
@State() selectedDate: moment.Moment = moment().startOf("day");
@State() pointerDate: moment.Moment = moment().startOf("day");
/**
* Language of the datepicker. Possible values are `de`, `fr`,`it` or `en`.
*/
@Prop() language: string = "de";
/**
* Placeholder text to render if no date has been selected.
*/
@Prop() placeholder: string = "Click to select...";
/**
* Disable the input
*/
@Prop() disabled: boolean = false;
/**
* Latest date available for selection
*/
@Prop() maxDate: string = "";
/**
* Earliest date available for selection
*/
@Prop() minDate: string = "";
/**
* Latest year available for selection
*/
@Prop() maxYear: string = "";
/**
* Earliest year available for selection
*/
@Prop() minYear: string = "";
/**
* The value of the datepicker with the format `dd.MM.yyyy`.
*/
@Prop() value: string = "";
@Watch("value")
valueWatcher(newValue: string) {
this.isPristine = false;
this.inputElement.value = newValue;
this.selectedDate = moment(newValue, BalDatepicker.FORMAT);
this.pointerDate = moment(newValue, BalDatepicker.FORMAT);
}
/**
* Callback to determine which date in the datepicker should be selectable.
*/
@Prop() filter: DateCallback = (_) => true;
/**
* Triggers when the value of the datepicker is changed
*/
@Event({
eventName: "input",
composed: true,
cancelable: true,
bubbles: true,
}) inputEventEmitter!: EventEmitter<string>;
componentWillLoad() {
moment.locale(this.language);
if (this.value) {
this.isPristine = false;
this.selectedDate = moment(this.value, BalDatepicker.FORMAT);
this.pointerDate = moment(this.value, BalDatepicker.FORMAT);
}
if (!this.minYear) {
this.minYear = moment(this.now).subtract(100, "years").year().toString();
}
if (!this.maxYear) {
this.maxYear = moment(this.now).add(100, "years").year().toString();
}
}
/**
* Open the datepicker dropdown
*/
@Method()
async open() {
await this.dropDownElement.open();
}
/**
* Close the datepicker dropdown
*/
@Method()
async close() {
await this.dropDownElement.close();
}
get weekdays(): string[] {
const arr: string[] = moment.weekdaysMin();
arr.push(arr.shift() as any);
return arr;
}
get years(): number[] {
const years = [];
for (let year = parseInt(this.minYear, 10); year <= parseInt(this.maxYear, 10); year++) {
years.push(year);
}
return years;
}
get parsedMaxDate(): moment.Moment {
return moment(this.maxDate, BalDatepicker.FORMAT).startOf("day");
}
get parsedMinDate(): moment.Moment {
return moment(this.minDate, BalDatepicker.FORMAT).startOf("day");
}
get firstDateOfBox(): moment.Moment {
return moment(this.pointerDate).startOf("month").startOf("isoWeek");
}
get calendarGrid(): CalendarCell[][] {
let weekDatePointer = this.firstDateOfBox;
let dayDatePointer = this.firstDateOfBox;
let calendar = [];
do {
let row = [];
do {
row = [...row, {
date: moment(dayDatePointer),
dateString: dayDatePointer.format(BalDatepicker.FORMAT),
label: dayDatePointer.date().toString(),
isToday: this.now.isSame(dayDatePointer),
isSelected: !this.isPristine && this.selectedDate.isSame(dayDatePointer),
isDisabled: !this.filter(dayDatePointer.format(BalDatepicker.FORMAT)),
isOutdated: !this.pointerDate.isSame(dayDatePointer, "month")
|| (this.minDate && dayDatePointer < this.parsedMinDate)
|| (this.maxDate && dayDatePointer > this.parsedMaxDate),
} as CalendarCell];
dayDatePointer = moment(dayDatePointer.add(1, "days"));
} while (weekDatePointer.isSame(dayDatePointer, "week"));
calendar = [...calendar, row];
weekDatePointer = moment(weekDatePointer.add(1, "weeks"));
} while (this.pointerDate.isSame(dayDatePointer, "month"));
return calendar;
}
private previousMonth() {
this.pointerDate = moment(this.pointerDate.subtract(1, "months"));
}
private nextMonth() {
this.pointerDate = moment(this.pointerDate.add(1, "months"));
}
private handleYearSelect(event: any) {
this.pointerDate = moment(this.pointerDate.year(event.target.value));
}
private handleMonthSelect(event: any) {
this.pointerDate = moment(this.pointerDate.month(parseInt(event.target.value, 10)));
}
private async selectDate(cell: CalendarCell) {
if (!cell.isDisabled && !cell.isOutdated) {
this.isPristine = false;
this.selectedDate = moment(cell.date);
this.pointerDate = moment(cell.date);
this.inputEventEmitter.emit(this.selectedDate.format(BalDatepicker.FORMAT));
this.inputElement.value = this.selectedDate.format(BalDatepicker.FORMAT);
await this.close();
}
}
render() {
return (
<Host>
<div class="datepicker control">
<bal-dropdown expanded ref={el => this.dropDownElement = el as HTMLBalDropdownElement}>
<div slot="trigger" class="control has-icons-right is-clearfix clickable">
<input type="text"
value={this.value}
disabled={this.disabled}
autocomplete="off"
placeholder={this.placeholder}
readonly="readonly"
ref={el => this.inputElement = el as HTMLInputElement}
class="input" />
<span class="icon is-right">
<i class="bal-icon-date"></i>
</span>
</div>
<div class="datepicker-popup">
<header class="datepicker-header">
<div class="pagination field is-centered">
<a role="button"
onClick={() => this.previousMonth()}
class="pagination-previous">
<span class="icon has-text-primary is-large">
<i class="bal-icon-nav-go-left"></i>
</span>
</a>
<a role="button"
onClick={() => this.nextMonth()}
class="pagination-next">
<span class="icon has-text-primary is-large">
<i class="bal-icon-nav-go-right"></i>
</span>
</a>
<div class="pagination-list">
<div class="field has-addons">
<div class="control month-select"><span class="select">
<select onInput={(event) => this.handleMonthSelect(event)}>
{moment.months().map((month, index) =>
<option value={index}
selected={this.pointerDate.month() === index}>
{month}
</option>,
)}
</select>
</span></div>
<div class="control year-select"><span class="select">
<select onInput={(event) => this.handleYearSelect(event)}>
{this.years.map((year) =>
<option value={year}
selected={this.pointerDate.year() === year}>
{year}
</option>,
)}
</select>
</span></div>
</div>
</div>
</div>
</header>
<div class="datepicker-content">
<section class="datepicker-table">
<header class="datepicker-header">
{this.weekdays.map((weekday) => <div
class="datepicker-cell">{weekday}</div>)}
</header>
<div class="datepicker-body">
{this.calendarGrid.map(row =>
<div class="datepicker-row">
{row.map(cell =>
<div onClick={() => this.selectDate(cell)} data-date={cell.dateString} class={[
"datepicker-cell",
cell.isToday ? "is-today" : "",
cell.isSelected ? "is-selected" : "",
cell.isOutdated ? "is-outdated" : "",
cell.isDisabled ? "is-disabled" : "",
].join(" ")}>
{cell.label}
</div>,
)}
</div>,
)}
</div>
</section>
</div>
</div>
</bal-dropdown>
</div>
</Host>
);
}
}
|
culmat/bal-ui-library
|
src/components/tabs/tabs.tsx
|
import {Component, Host, h, Element, State, Event, EventEmitter, Method, Prop} from "@stencil/core";
import {TabItemOptions} from "../tab-item/tab-item";
@Component({
tag: "bal-tabs",
styleUrl: "tabs.scss",
shadow: true,
})
export class Tabs {
@Element() element!: HTMLElement;
@State() tabsOptions: TabItemOptions[] = [];
/**
* If `true` the field expands over the whole width.
*/
@Prop() expanded = false;
/**
* Emitted when the changes has finished.
*/
@Event({eventName: "balTabsDidChange"}) tabsDidChange: EventEmitter<TabItemOptions>;
/**
* Select a tab by the value of the tab item.
*/
@Method()
async select(value: string) {
this.tabs.forEach(t => t.setActive(t.value === value));
this.readTabItems();
}
componentWillLoad() {
this.readTabItems();
}
private readTabItems() {
Promise.all(this.tabs.map(value => value.getOptions()))
.then(tabsOptions => {
this.tabsOptions = tabsOptions;
});
}
private get tabs() {
return Array.from(this.element.querySelectorAll("bal-tab-item"));
}
private async onSelectTab(tab: TabItemOptions) {
await this.select(tab.value);
this.tabsDidChange.emit(tab);
}
render() {
return (
<Host>
<div class={[
"tabs",
this.expanded ? "is-fullwidth" : "",
].join(" ")}>
<ul>
{this.tabsOptions.map((tab) =>
<li class={tab.active ? "is-active" : ""}>
<a onClick={() => this.onSelectTab(tab)}>{tab.label}</a>
</li>,
)}
</ul>
</div>
<slot/>
</Host>
);
}
}
|
culmat/bal-ui-library
|
src/components/bal-dropdown-item/bal-dropdown-item.tsx
|
import {Component, Host, h, Prop, Element, Event, EventEmitter, State, Listen} from "@stencil/core";
import {Components} from "../../components";
import {DropDownOption} from "../bal-dropdown/bal-dropdown";
@Component({
tag: "bal-dropdown-item",
styleUrl: "bal-dropdown-item.scss",
shadow: true,
})
export class BalDropdownItem {
@Element() element!: HTMLElement;
@State() isActive = false;
/**
* The value of the dropdown item. This value will be returned by the parent <bal-dropdown> element.
*/
@Prop() value: string | boolean | number | object = false;
/**
* Click event of the dropdown item.
*/
@Event() clickEvent: EventEmitter;
componentDidLoad() {
this.checkActiveState();
}
@Listen("dropdownSelected", {target: "document"})
async isActiveHandler(event: CustomEvent) {
if ((event.target as Node).isEqualNode(this.parent as any)) {
this.checkActiveState();
}
}
@Listen("selectDropdownItem", {target: "document"})
async isSelectedHandler(event: CustomEvent) {
if ((event.target as Node).isEqualNode(this.parent as any)) {
this.checkSelection(event.detail);
}
}
get parent(): Components.BalDropdown {
return this.element.parentNode as any;
}
async checkSelection(value: any) {
if (this.value === value) {
this.selectItem();
}
}
async checkActiveState() {
const selectedValue = await this.parent.getSelectedValue();
if (selectedValue === null) {
this.isActive = false;
} else {
this.isActive = this.value === selectedValue;
}
}
selectItem() {
const slotted = this.element.shadowRoot.querySelector("slot") as HTMLSlotElement;
const label = slotted.assignedNodes()
.map((node: any) => (node.nodeValue) ? node.nodeValue : node.outerHTML)
.join("");
const dropdownEventDetails: DropDownOption = {
label,
value: this.value,
};
this.parent.selectItem(dropdownEventDetails);
this.clickEvent.emit(dropdownEventDetails);
}
render() {
return (
<Host>
<button class={this.isActive ? "dropdown-item is-active" : "dropdown-item"}
onClick={() => this.selectItem()}>
<slot/>
</button>
</Host>
);
}
}
|
culmat/bal-ui-library
|
src/index.ts
|
<reponame>culmat/bal-ui-library
export * from "./components";
export {balToastController} from "./components/bal-toast/bal-toast.controller";
|
Thalassa-Ta/github-profile-trophy
|
src/user_info.ts
|
type Language = { name: string };
type Stargazers = { totalCount: number };
type Repository = {
languages: { nodes: Language[] };
stargazers: Stargazers;
};
export type GitHubUserData = {
createdAt: string;
contributionsCollection: {
totalCommitContributions: number;
restrictedContributionsCount: number;
};
pullRequests: {
totalCount: number;
};
issues: {
totalCount: number;
};
organizations: {
totalCount: number;
};
followers: {
totalCount: number;
};
repositories: {
totalCount: number;
nodes: Repository[];
};
};
export class UserInfo {
public readonly totalCommits: number;
public readonly totalFollowers: number;
public readonly totalIssues: number;
public readonly totalOrganizations: number;
public readonly totalPullRequests: number;
public readonly totalStargazers: number;
public readonly totalRepositories: number;
public readonly languageCount: number;
public readonly durationYear: number;
public readonly ancientAccount: number;
public readonly joined2020: number;
constructor(
userData: GitHubUserData,
) {
const totalCommits =
userData.contributionsCollection.restrictedContributionsCount +
userData.contributionsCollection.totalCommitContributions;
const totalStargazers = userData.repositories.nodes.reduce(
(prev: number, node: Repository) => {
return prev + node.stargazers.totalCount;
},
0,
);
const languages = new Set<string>();
userData.repositories.nodes.forEach((node: Repository) => {
if (node.languages.nodes != undefined) {
node.languages.nodes.forEach((node: Language) => {
if (node != undefined) {
languages.add(node.name);
}
});
}
});
const durationTime = new Date().getTime() -
new Date(userData.createdAt).getTime();
const durationYear = new Date(durationTime).getUTCFullYear() - 1970;
const ancientAccount = new Date(userData.createdAt).getFullYear() <= 2010
? 1
: 0;
const joined2020 = new Date(userData.createdAt).getFullYear() == 2020
? 1
: 0;
this.totalCommits = totalCommits;
this.totalFollowers = userData.followers.totalCount;
this.totalIssues = userData.issues.totalCount;
this.totalOrganizations = userData.organizations.totalCount;
this.totalPullRequests = userData.pullRequests.totalCount;
this.totalStargazers = totalStargazers;
this.totalRepositories = userData.repositories.totalCount;
this.languageCount = languages.size;
this.durationYear = durationYear;
this.ancientAccount = ancientAccount;
this.joined2020 = joined2020;
}
}
|
Thalassa-Ta/github-profile-trophy
|
src/github_api_client.ts
|
import { soxa } from "../deps.ts";
import { UserInfo } from "./user_info.ts"
import type { GitHubUserData } from "./user_info.ts";
export class GithubAPIClient {
constructor() {
}
async requestUserInfo(username: string): Promise<UserInfo | null> {
const token = Deno.env.get("GITHUB_TOKEN");
const variables = { username: username };
const query = `
query userInfo($username: String!) {
user(login: $username) {
createdAt
contributionsCollection {
totalCommitContributions
restrictedContributionsCount
}
pullRequests(first: 1) {
totalCount
}
issues(first: 1) {
totalCount
}
organizations(first: 1) {
totalCount
}
followers(first: 1) {
totalCount
}
repositories(first: 100, ownerAffiliations: OWNER, isFork: false, orderBy: {direction: DESC, field: STARGAZERS}) {
totalCount
nodes {
languages(first: 3, orderBy: {direction:DESC, field: SIZE}) {
nodes {
name
}
}
stargazers {
totalCount
}
}
}
}
}
`;
const response = await soxa.post(
"https://api.github.com/graphql",
{},
{
data: { query: query, variables },
headers: { Authorization: `bearer ${token}` },
},
);
if (response.status != 200) {
throw new Error(response)
}
const userData: GitHubUserData = response.data.data.user;
return new UserInfo(userData);
}
}
|
likuilin/muse
|
src/commands/nowplaying.ts
|
<filename>src/commands/nowplaying.ts
import {Message, MessageEmbed} from 'discord.js';
import {TYPES} from '../types';
import {inject, injectable} from 'inversify';
import PlayerManager from '../managers/player';
import Player, {STATUS} from '../services/player';
import Command from '.';
import getProgressBar from '../utils/get-progress-bar';
import {prettyTime} from '../utils/time';
import getYouTubeID from 'get-youtube-id';
@injectable()
export default class NowPlaying implements Command {
public name = 'nowplaying';
public aliases = ['np'];
public examples = [
['np', 'shows current song']
];
private readonly playerManager: PlayerManager;
constructor(@inject(TYPES.Managers.Player) playerManager: PlayerManager) {
this.playerManager = playerManager;
}
public static buildRadio(player: Player) {
const currentlyPlaying = player.getCurrent();
if (currentlyPlaying) {
const embed = new MessageEmbed();
embed.setTitle(currentlyPlaying.title);
embed.setURL(`https://www.youtube.com/watch?v=${currentlyPlaying.url.length === 11 ? currentlyPlaying.url : getYouTubeID(currentlyPlaying.url) ?? ''}`);
let description = player.status === STATUS.PLAYING ? '⏹️' : '▶️';
description += ' ';
description += getProgressBar(20, player.getPosition() / currentlyPlaying.length);
description += ' ';
description += `\`[${prettyTime(player.getPosition())}/${currentlyPlaying.isLive ? 'live' : prettyTime(currentlyPlaying.length)}]\``;
description += ' 🔉';
if (player.songLoop) {
description += ' 🔂';
}
if (player.queueLoop) {
description += ' 🔁';
}
embed.setDescription(description);
let footer = `Source: ${currentlyPlaying.artist}`;
embed.setFooter(footer);
return embed;
}
return 'no thoughts, queue empty';
}
public async execute(msg: Message): Promise<void> {
const player = this.playerManager.get(msg.guild!.id);
await msg.channel.send(NowPlaying.buildRadio(player));
}
}
|
likuilin/muse
|
src/commands/reset.ts
|
import {Message} from 'discord.js';
import {TYPES} from '../types';
import {inject, injectable} from 'inversify';
import PlayerManager from '../managers/player';
import errorMsg from '../utils/error-msg';
import Command from '.';
@injectable()
export default class implements Command {
public name = 'reset';
public aliases = ['destroy', 'leave', 'terminate', 'stop'];
public examples = [
['reset', 'disconnects player and deletes entire queue and clears scrobble and loop flags']
];
public requiresVC = true;
private readonly playerManager: PlayerManager;
constructor(@inject(TYPES.Managers.Player) playerManager: PlayerManager) {
this.playerManager = playerManager;
}
public async execute(msg: Message, _: string []): Promise<void> {
const player = this.playerManager.get(msg.guild!.id);
if (!player.voiceConnection) {
await msg.channel.send(errorMsg('not connected'));
return;
}
player.reset();
await msg.channel.send('“I love to soar in the boundless sky. In the vast emptiness of the blue, my soul rejoices listening to the soundless music of the wind.”\n― <NAME>, World Peace: The Voice of a Mountain Bird');
}
}
|
likuilin/muse
|
src/commands/fshuffle.ts
|
import {Message} from 'discord.js';
import {TYPES} from '../types';
import {inject, injectable} from 'inversify';
import PlayerManager from '../managers/player';
import Command from '.';
@injectable()
export default class implements Command {
public name = 'fullshuffle';
public aliases = ['fshuffle'];
public examples = [
['fullshuffle', 'shuffles the entire queue, including already-played and current songs, and re-starts at top of queue']
];
public requiresVC = true;
private readonly playerManager: PlayerManager;
constructor(@inject(TYPES.Managers.Player) playerManager: PlayerManager) {
this.playerManager = playerManager;
}
public async execute(msg: Message, _: string []): Promise<void> {
const player = this.playerManager.get(msg.guild!.id);
await player.shuffle(true);
await msg.channel.send('full shuffled');
}
}
|
likuilin/muse
|
src/commands/loop.ts
|
<filename>src/commands/loop.ts<gh_stars>0
import {Message} from 'discord.js';
import {TYPES} from '../types';
import {inject, injectable} from 'inversify';
import PlayerManager from '../managers/player';
import Command from '.';
@injectable()
export default class implements Command {
public name = 'loop';
public aliases = [];
public examples = [
['loop', 'toggles looping one song']
];
public requiresVC = true;
private readonly playerManager: PlayerManager;
constructor(@inject(TYPES.Managers.Player) playerManager: PlayerManager) {
this.playerManager = playerManager;
}
public async execute(msg: Message, _: string []): Promise<void> {
const player = this.playerManager.get(msg.guild!.id);
player.songLoop = !player.songLoop;
player.queueLoop = false;
if (player.songLoop) {
await msg.channel.send('spin your pardner round n\' round');
} else {
await msg.channel.send('let \'er down loosely');
}
}
}
|
Moeriki/nova-eslint
|
src/getEslintPath.ts
|
async function npmBin(): Promise<string> {
return new Promise<string>((resolve, reject) => {
const process = new Process("/usr/bin/env", {
args: ["npm", "bin"],
cwd: nova.workspace.path || nova.extension.path,
stdio: ["ignore", "pipe", "pipe"],
env: {
NO_UPDATE_NOTIFIER: "true",
},
});
let result = "";
process.onStdout((o) => {
result += o;
});
process.onStderr((e) => console.warn("npm bin:", e.trimRight()));
process.onDidExit((status) => {
if (status === 0) {
resolve(result.trim());
} else {
reject(new Error("failed to npm bin"));
}
});
process.start();
});
}
// this determines where the eslint executable is
export async function getEslintPath(): Promise<string | null> {
const npmBinDir = await npmBin();
let execPath: string;
const configExecPath =
nova.workspace.config.get("apexskier.eslint.config.eslintPath", "string") ??
nova.config.get("apexskier.eslint.config.eslintPath", "string");
if (configExecPath) {
if (nova.path.isAbsolute(configExecPath)) {
execPath = configExecPath;
} else if (nova.workspace.path) {
execPath = nova.path.join(nova.workspace.path, configExecPath);
} else {
nova.workspace.showErrorMessage(
"Save your workspace before using a relative ESLint executable path."
);
return null;
}
} else {
execPath = nova.path.join(npmBinDir, "eslint");
}
if (!nova.fs.access(execPath, nova.fs.X_OK)) {
return null;
}
return execPath;
}
|
Moeriki/nova-eslint
|
src/eslintOutputToIssue.ts
|
import type { Linter } from "eslint";
function eslintSeverityToNovaSeverity(severity: Linter.Severity) {
switch (severity) {
case 0:
return IssueSeverity.Info;
case 1:
return IssueSeverity.Warning;
case 2:
return IssueSeverity.Error;
}
}
export function eslintOutputToIssue(attributes: Linter.LintMessage) {
const issue = new Issue();
issue.source = "ESLint";
if (attributes.ruleId) {
issue.code = attributes.ruleId;
}
issue.message = attributes.message;
issue.severity = eslintSeverityToNovaSeverity(attributes.severity);
issue.line = attributes.line;
issue.endLine = attributes.endLine;
issue.column = attributes.column;
issue.endColumn = attributes.endColumn;
return issue;
}
|
Moeriki/nova-eslint
|
src/process.ts
|
<filename>src/process.ts
import type { Linter } from "eslint";
import { getEslintPath } from "./getEslintPath";
let eslintPath: string | null = null;
nova.config.onDidChange("apexskier.eslint.config.eslintPath", async () => {
eslintPath = await getEslintPath();
console.log("Updating ESLint executable globally", eslintPath);
});
nova.workspace.config.onDidChange(
"apexskier.eslint.config.eslintPath",
async () => {
eslintPath = await getEslintPath();
console.log("Updating ESLint executable for workspace", eslintPath);
}
);
(async () => {
eslintPath = await getEslintPath();
})();
const filePrefixRegex = /^file:/;
const syntaxToRequiredPlugin: { [syntax: string]: string | undefined } = {
html: "html",
vue: "vue",
markdown: "markdown",
};
export function runEslint(
content: string,
uri: string,
syntax: string,
// eslint-disable-next-line no-unused-vars
callback: (issues: ReadonlyArray<Linter.LintMessage>) => void
): Disposable {
const disposable = new CompositeDisposable();
if (!nova.workspace.path || !eslintPath) {
return disposable;
}
const eslint = eslintPath;
const workspacePath = nova.workspace.path;
const cleanFileName = decodeURI(uri).replace(filePrefixRegex, "");
// one idea for a performance improvement here would be to cache the needed results
// on a file path basis.
// Risks
// - if the eslint config or installed packages change it'll be hard to invalidate the cache
// - handling file renaming?
function getConfig(
// eslint-disable-next-line no-unused-vars
callback: (config: Linter.Config) => void
): void {
const configProcess = new Process(eslint, {
args: ["--format=json", "--print-config", cleanFileName],
cwd: workspacePath,
stdio: "pipe",
});
disposable.add({
dispose() {
configProcess.terminate();
},
});
let configStr = "";
configProcess.onStdout((line) => (configStr += line));
configProcess.onStderr(console.warn.bind(console));
configProcess.onDidExit((status) => {
const configProcessWasTerminated = status === 15;
if (status !== 0 && !configProcessWasTerminated) {
throw new Error(
`failed to get eslint config for ${cleanFileName}: ${status}`
);
}
if (configProcessWasTerminated) {
return;
}
callback(JSON.parse(configStr));
});
configProcess.start();
}
function getLintMessages(
// eslint-disable-next-line no-unused-vars
callback: (issues: ReadonlyArray<Linter.LintMessage>) => void
): void {
const lintProcess = new Process(eslint, {
args: ["--format=json", "--stdin", "--stdin-filename", cleanFileName],
cwd: workspacePath,
stdio: "pipe",
});
disposable.add({
dispose() {
lintProcess.terminate();
},
});
let lintOutput = "";
lintProcess.onStdout((line) => (lintOutput += line));
lintProcess.onStderr(console.warn.bind(console));
lintProcess.onDidExit((status) => {
const lintProcessWasTerminated = status === 15;
// https://eslint.org/docs/user-guide/command-line-interface#exit-codes
const areLintErrors = status === 1;
const noLintErrors = status === 0;
if (!areLintErrors && !noLintErrors && !lintProcessWasTerminated) {
callback([]);
throw new Error(`failed to lint ${cleanFileName}: ${status}`);
}
if (lintProcessWasTerminated) {
return;
}
if (noLintErrors) {
callback([]);
}
const parsedOutput = JSON.parse(lintOutput);
const messages = parsedOutput[0]["messages"] as Array<Linter.LintMessage>;
callback(messages);
});
lintProcess.start();
// TODO: Improve readable stream types
const writer = (lintProcess.stdin as any).getWriter();
writer.ready.then(() => {
writer.write(content);
writer.close();
});
}
// if a plugin is required to parse this syntax we need to verify it's been found for this file
// check in the config for this file
const requiredPlugin = syntaxToRequiredPlugin[syntax];
if (requiredPlugin) {
getConfig((config) => {
if (!config.plugins?.includes(requiredPlugin)) {
callback([]);
} else {
getLintMessages(callback);
}
});
} else {
// if plugins aren't required, just lint right away
getLintMessages(callback);
}
return disposable;
}
export function fixEslint(path: string) {
if (!nova.workspace.path || !eslintPath) {
return;
}
const process = new Process(eslintPath, {
args: ["--fix", "--format=json", path],
cwd: nova.workspace.path,
stdio: "pipe",
});
process.onStderr(console.warn.bind(console));
process.start();
return process;
}
|
Moeriki/nova-eslint
|
src/main.ts
|
<filename>src/main.ts
import { Linter } from "./linter";
import { fixEslint } from "./process";
import { shouldFixOnSave } from "./shouldFixOnSave";
import { createSuggestionCommandHandler } from "./suggestionCommand";
const compositeDisposable = new CompositeDisposable();
// eslint-disable-next-line no-unused-vars
function fix(workspace: Workspace, editor: TextEditor): void;
// eslint-disable-next-line no-unused-vars
function fix(editor: TextEditor): void;
function fix(
workspaceOrEditor: Workspace | TextEditor,
maybeEditor?: TextEditor
): void {
const editor = TextEditor.isTextEditor(workspaceOrEditor)
? workspaceOrEditor
: maybeEditor!;
if (editor.document.isDirty) {
const listener = editor.onDidSave(() => {
listener.dispose();
innerFix();
});
editor.save();
} else {
innerFix();
}
function innerFix() {
if (!editor.document.path) {
nova.workspace.showErrorMessage("This document is missing a path.");
return;
}
console.log("Fixing", editor.document.path);
fixEslint(editor.document.path);
}
}
export function activate() {
console.log("activating...");
const linter = new Linter();
compositeDisposable.add(
nova.commands.register("apexskier.eslint.command.fix", fix)
);
compositeDisposable.add(
nova.commands.register(
"apexskier.eslint.command.suggestForCursor",
createSuggestionCommandHandler(linter)
)
);
compositeDisposable.add(nova.workspace.onDidAddTextEditor(watchEditor));
function watchEditor(editor: TextEditor) {
const document = editor.document;
if (
![
"javascript",
"typescript",
"tsx",
"jsx",
"vue",
"html",
"markdown",
].includes(document.syntax ?? "")
) {
return;
}
linter.lintDocument(document);
const editorDisposable = new CompositeDisposable();
editorDisposable.add(
editor.onWillSave((editor) => {
if (shouldFixOnSave()) {
const listener = editor.onDidSave((editor) => {
listener.dispose();
if (!editor.document.path) {
nova.workspace.showErrorMessage(
"This document is missing a path."
);
return;
}
nova.commands.invoke("apexskier.eslint.command.fix", editor);
});
}
linter.lintDocument(editor.document);
})
);
editorDisposable.add(
editor.onDidStopChanging((editor) => linter.lintDocument(editor.document))
);
editorDisposable.add(
editor.onDidDestroy((destroyedEditor) => {
const anotherEditor = nova.workspace.textEditors.find(
(editor) => editor.document.uri === destroyedEditor.document.uri
);
if (!anotherEditor) {
linter.removeIssues(destroyedEditor.document.uri);
}
editorDisposable.dispose();
})
);
compositeDisposable.add(editorDisposable);
compositeDisposable.add(
document.onDidChangeSyntax((document) => linter.lintDocument(document))
);
}
console.log("activated");
}
export function deactivate() {
compositeDisposable.dispose();
}
|
Moeriki/nova-eslint
|
src/linter.ts
|
<gh_stars>0
import type { Linter as EslintLinter } from "eslint";
import { eslintOutputToIssue } from "./eslintOutputToIssue";
import { runEslint } from "./process";
function positionToRange(
document: TextDocument,
position: {
line: number;
column: number;
endLine: number;
endColumn: number;
}
): Range {
const fullContents = document.getTextInRange(new Range(0, document.length));
let rangeStart = 0;
let rangeEnd = 0;
let chars = 0;
const lines = fullContents.split(document.eol);
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
const lineLength = lines[lineIndex].length + document.eol.length;
if (position.line - 1 === lineIndex) {
rangeStart = chars + position.column - 1;
}
if (position.endLine - 1 === lineIndex) {
rangeEnd = chars + position.endColumn - 1;
break;
}
chars += lineLength;
}
return new Range(rangeStart, rangeEnd);
}
export class Linter {
private _issues = new IssueCollection();
// note - the order of this should match that of _issues
private _messages = new Map<
string,
ReadonlyArray<EslintLinter.LintMessage>
>();
private _processesForPaths: { [path: string]: Disposable | undefined } = {};
lintDocument(document: TextDocument) {
if (!document.syntax) {
return;
}
const contentRange = new Range(0, document.length);
const content = document.getTextInRange(contentRange);
this.lintString(content, document.uri, document.syntax);
}
private lintString(string: string, uri: string, syntax: string) {
const path = nova.path.normalize(uri);
this._processesForPaths[path]?.dispose();
this._processesForPaths[path] = runEslint(
string,
path,
syntax,
(messages) => {
delete this._processesForPaths[path];
this._messages.set(path, messages);
this._issues.set(path, messages.map(eslintOutputToIssue));
}
);
}
removeIssues(uri: string) {
const path = nova.path.normalize(uri);
this._messages.delete(path);
this._issues.remove(path);
}
getAllMessages(editor: TextEditor) {
const path = nova.path.normalize(editor.document.uri);
return this._messages.get(path) ?? [];
}
getMessageAtSelection(editor: TextEditor) {
const path = nova.path.normalize(editor.document.uri);
const messages = this._messages.get(path) ?? [];
const issues = this._issues.get(path);
if (messages.length != issues.length) {
throw new Error("inconsistent data in Linter");
}
const message = messages.find((_, i) => {
// annoyingly, nova doesn't provide a getter for this if col/line is set
// const issueRange = issues[i].textRange!;
const issue = issues[i];
const position = {
line: issue.line!,
column: issue.column!,
endLine: issue.endLine!,
endColumn: issue.endColumn!,
};
const issueRange = positionToRange(editor.document, position);
return (
editor.selectedRange.intersectsRange(issueRange) ||
(editor.selectedRange.empty &&
issueRange.containsIndex(editor.selectedRange.start))
);
});
return message;
}
}
|
Moeriki/nova-eslint
|
src/suggestionCommand.ts
|
import type { Linter } from "./linter";
import type { Rule } from "eslint";
export async function showChoicePalette<T>(
choices: T[],
// eslint-disable-next-line no-unused-vars
choiceToString: (choice: T) => string,
options?: { placeholder?: string }
) {
const index = await new Promise<number | null>((resolve) =>
nova.workspace.showChoicePalette(
choices.map(choiceToString),
options,
(_, index) => {
resolve(index);
}
)
);
if (index == null) {
return null;
}
return choices[index];
}
type FixChoiceType = { fix: Rule.Fix } | { fixAll: true };
function isFixAll(x: FixChoiceType): x is { fixAll: true } {
return !!(x as { fixAll: true }).fixAll;
}
export function createSuggestionCommandHandler(linter: Linter) {
return async (editor: TextEditor) => {
const choices: Array<
{ title: string } & ({ fix: Rule.Fix } | { fixAll: true })
> = [];
const message = linter.getMessageAtSelection(editor);
if (message) {
if (message.fix) {
choices.push({
title: `Fix this ${message.ruleId} problem`,
fix: message.fix,
});
}
if (message.suggestions) {
choices.push(
...message.suggestions.map((suggestion) => ({
title: suggestion.desc,
fix: suggestion.fix,
}))
);
}
}
choices.push({ title: "Fix all auto-fixable problems", fixAll: true });
const choice = await showChoicePalette(choices, ({ title }) => title, {
placeholder: message?.message,
});
if (!choice) {
return;
}
if (isFixAll(choice)) {
nova.commands.invoke("apexskier.eslint.command.fix", editor);
} else {
const { fix } = choice;
editor.edit((edit) => {
edit.replace(new Range(fix.range[0], fix.range[1]), fix.text);
});
}
};
}
|
Moeriki/nova-eslint
|
src/shouldFixOnSave.ts
|
<reponame>Moeriki/nova-eslint
function getWorkspaceSetting(): boolean | null {
const str = nova.workspace.config.get(
"apexskier.eslint.config.fixOnSave",
"string"
);
switch (str) {
case "Disable":
return false;
case "Enable":
return true;
default:
return null;
}
}
export function shouldFixOnSave(): boolean {
return (
getWorkspaceSetting() ??
nova.config.get("apexskier.eslint.config.fixOnSave", "boolean") ??
false
);
}
|
avidianity/react-modal-image
|
types/index.d.ts
|
import { Component, FC } from 'react';
export default class extends Component<{
className?: string;
alt?: string;
small: string;
smallSrcSet?: string;
medium?: string;
large?: string;
hideDownload?: boolean;
hideZoom?: boolean;
showRotate?: boolean;
imageBackgroundColor?: string;
}> {}
export const Lightbox: FC<{
className?: string;
alt?: string;
small: string;
smallSrcSet?: string;
medium?: string;
large?: string;
hideDownload?: boolean;
hideZoom?: boolean;
showRotate?: boolean;
imageBackgroundColor?: string;
onClose?: () => void;
}>;
|
leighmacdonald/uncletopia-web
|
frontend/src/component/Flashes.tsx
|
<reponame>leighmacdonald/uncletopia-web
import React from 'react';
import Alert from '@material-ui/lab/Alert';
import { Color } from '@material-ui/lab/Alert/Alert';
export interface Flash {
level: Color;
heading: string;
message: string;
closable?: boolean;
link_to?: string;
}
export interface FlashesProps {
flashes: Flash[];
}
export const Flashes = ({ flashes }: FlashesProps): JSX.Element => (
<>
{flashes.map((f, i) => {
return (
<Alert key={`alert-${i}`} severity={f.level}>
{f.message}
</Alert>
);
})}
</>
);
|
leighmacdonald/uncletopia-web
|
frontend/src/component/Demos.tsx
|
import React, { useEffect, useState } from 'react';
import Grid from '@material-ui/core/Grid';
import { DemoArchive, getDemos } from '../api';
import Typography from '@material-ui/core/Typography';
export const Demos = () => {
// const [servers, setServers] = useState<string[]>([]);
const [demos, setDemos] = useState<DemoArchive[]>([]);
useEffect(() => {
const fn = async () => {
const fetchedDemos = await getDemos();
setDemos(fetchedDemos as DemoArchive[]);
};
fn();
}, []
);
return <Grid container justifyContent={'center'}>
<Grid item xs={12} lg={8} style={{minHeight: "600px"}}>
<img src={"https://www.meme-arsenal.com/memes/7acea578d83d5900ac41663392fdf7df.jpg"}/>
{(demos ?? []).map((_e) => {
return <Typography variant={'h1'}>~~Demos~~</Typography>;
})}
</Grid>
</Grid>;
};
|
leighmacdonald/uncletopia-web
|
frontend/src/component/Logout.tsx
|
<reponame>leighmacdonald/uncletopia-web<gh_stars>1-10
import { PermissionLevel } from '../api';
import { Navigate } from 'react-router-dom';
import React from 'react';
import { GuestProfile, useCurrentUserCtx } from '../ctx/CurrentUserCtx';
export const Logout = (): JSX.Element => {
const {setCurrentUser} = useCurrentUserCtx();
localStorage.setItem('token', '');
localStorage.setItem('permission_level', `${PermissionLevel.Guest}`);
setCurrentUser(GuestProfile);
return <Navigate to={'/'} />;
};
|
leighmacdonald/uncletopia-web
|
frontend/src/component/Donate.tsx
|
<filename>frontend/src/component/Donate.tsx<gh_stars>1-10
import React, { useEffect, useState } from 'react';
import Typography from '@material-ui/core/Typography';
import Grid from '@material-ui/core/Grid';
import AcUnitIcon from '@material-ui/icons/AcUnit';
import { fetchServers, Person } from '../api';
import Button from '@material-ui/core/Button';
import FormControl from '@material-ui/core/FormControl';
import FormHelperText from '@material-ui/core/FormHelperText';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import MenuItem from '@material-ui/core/MenuItem';
import Paper from '@material-ui/core/Paper';
import Select from '@material-ui/core/Select';
import { createStyles, Theme } from '@material-ui/core';
import { Link } from 'react-router-dom';
import { useCurrentUserCtx } from '../ctx/CurrentUserCtx';
import makeStyles from '@material-ui/core/styles/makeStyles';
import sortedUniq from 'lodash-es/sortedUniq';
export interface Donation {
player: Person;
amount: number;
server_location: string;
}
const useStyles = makeStyles((theme: Theme) =>
createStyles({
paper: {
padding: theme.spacing(2)
},
formControl: {
margin: theme.spacing(1),
minWidth: 120,
width: '100%',
flexWrap: 'nowrap',
align: 'center',
justifyContent: 'center'
},
selectEmpty: {
marginTop: theme.spacing(2)
},
button: {
width: '100%',
flexWrap: 'nowrap',
align: 'center',
justifyContent: 'center',
backgroundColor: theme.palette.background.default
// '&:hover': {
// backgroundColor: theme.palette.text.primary
// }
},
tierRow: {
marginBottom: theme.spacing(6),
padding: theme.spacing(2)
},
rowBody: {
width: '100%',
flexWrap: 'nowrap',
alignItems: 'center',
justifyContent: 'center'
},
donation_container: {
padding: theme.spacing(3)
},
donation_selector: {
marginTop: theme.spacing(2),
marginBottom: theme.spacing(6),
padding: theme.spacing(3)
},
donation_body: {
padding: theme.spacing(3),
textAlign: 'justify',
marginTop: theme.spacing(2),
marginBottom: theme.spacing(2),
fontFamily: [
'"Helvetica Neue"',
'Helvetica',
'Roboto',
'Arial',
'sans-serif'
].join(',')
}
})
);
export const DonationPanel = () => {
const { currentUser } = useCurrentUserCtx();
const [servers, setServers] = useState<string[]>(['no-preference']);
const classes = useStyles();
const [selectedServer, setSelectedServer] = useState<string>('no-preference');
const clientId = '<KEY>';
const redirUrl = `${window.location.protocol}//${window.location.hostname}/patreon/callback`;
const state = `${localStorage.getItem('token')}----${selectedServer}`;
const link = `https://www.patreon.com/oauth2/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirUrl}&state=${state}`;
const handleChange = (event: React.ChangeEvent<{ value: unknown }>) => {
setSelectedServer(event.target.value as string);
};
useEffect(() => {
const fn = async () => {
try {
const s = await fetchServers();
setServers(sortedUniq(s.map(value => {
const va = value.name_short.split('-');
if (va.length > 0) {
return va[0] as string;
}
return '';
}).filter(value => value != '')));
} catch (e) {
}
};
// noinspection JSIgnoredPromiseFromCall
fn();
}, []);
return <Paper className={classes.donation_selector}>
<Grid container className={classes.rowBody} spacing={6}>
<Grid item xs={6}>
<Typography variant={'h3'} color={'secondary'}>Donate ❤️</Typography>
</Grid>
<Grid item xs={6}>
<Grid container className={classes.rowBody} spacing={3}>
{currentUser.steam_id === '' &&
<Grid item xs>
<Typography variant={'h6'} align={'right'}>Please login before linking your patreon
account</Typography>
</Grid>}
{currentUser.steam_id !== '' && <Grid item xs>
<Grid item xs>
<FormControl className={classes.formControl}>
<Select
labelId='donor-selected-server-label'
id='donor-selected-server'
value={selectedServer}
onChange={handleChange}
>
{['no-preference', ...servers].map((v) => <MenuItem value={v} key={v}>
<em>{v}</em>
</MenuItem>)}
</Select>
<FormHelperText>Select your home server</FormHelperText>
</FormControl>
</Grid>
<Grid item xs>
<Button className={classes.button} component={Link} color={'secondary'}
to={{ pathname: link }}
target={'_parent'}
>Link your
Patreon
account</Button>
</Grid>
</Grid>
}
</Grid></Grid>
</Grid>
</Paper>;
};
interface DonationTier {
title: string;
img: string;
sub_title: string;
price: string;
url: string;
body: string;
benefits: string[];
}
interface DonationTierProps {
tier: DonationTier;
}
export const DonationTier = ({ tier }: DonationTierProps) => {
const classes = useStyles();
return (
<Paper>
<Grid container className={classes.donation_container}>
<Grid item xs={12}>
<Typography variant={'h3'} style={{ marginBottom: '1rem' }}>{tier.title}</Typography>
<Typography variant={'h6'} style={{ marginBottom: '1rem' }}>{tier.sub_title}</Typography>
<img src={tier.img} style={{ width: '100%' }} />
<Typography variant={'body2'} className={classes.donation_body}>{tier.body}</Typography>
<List component='nav' aria-label='main mailbox folders'>
{tier.benefits.map(value =>
<ListItem>
<ListItemIcon>
<AcUnitIcon color={'secondary'}/>
</ListItemIcon>
<ListItemText primary={value} />
</ListItem>
)}
</List>
<Button className={classes.button} onClick={() => {
window.location.replace(tier.url);
}}>{tier.price}</Button>
</Grid>
</Grid>
</Paper>
);
};
export const Donate = () => {
const classes = useStyles();
const benefits = ['Includes Discord benefits', 'Support Uncletopia!', 'Exclusive Discord Role!'];
const tiers: DonationTier[] = [
{
title: 'Level 1 Supporter',
img: 'https://c10.patreonusercontent.com/3/eyJ3Ijo0MDB9/patreon-media/p/reward/7602063/94d9796cd6744e61935c2976cd9a3c11/1.jpg?token-time=21<PASSWORD>6800&token-hash=<PASSWORD>%3D',
benefits: benefits,
price: '5.00$ USD',
body: 'If you link your Patreon and Discord accounts, you will be given an exclusive australium-colored role in the official Uncletopia Discord server... which will let everyone else know how cool you are.',
sub_title: 'Thanks for keeping the lights on in Uncletopia!',
url: 'https://www.patreon.com/join/uncletopia/checkout?rid=7602063'
},
{
title: 'Level 2 Supporter',
img: 'https://c10.patreonusercontent.com/3/eyJ3Ijo0MDB9/patreon-media/p/reward/7602084/3691b4822232477a924770cbe4941529/1.jpg?token-time=2145916800&token-hash=-8RuQmCNsYC0yeQ4agfSODtOYBNmD2wA-oyYJGp84XQ%3D',
benefits: benefits,
price: '10.00$ USD',
body: 'If you link your Patreon and Discord accounts, you will be given an exclusive australium-colored role in the official Uncletopia Discord server... which will let everyone else know how awesome you are.',
sub_title: 'Thanks for keeping the lights on in Uncletopia!',
url: 'https://www.patreon.com/join/uncletopia/checkout?rid=7602084'
},
{
title: 'Level 3 Supporter',
img: 'https://c10.patreonusercontent.com/3/eyJ3Ijo0MDB9/patreon-media/p/reward/7602086/6607c3a50c3142bfa326d244bf2e459c/1.jpg?token-time=2145916800&token-hash=ilk450JzE53RS7DzyQlQNjHoOzaYdfTcShiSDyOHaRQ%3D',
benefits: benefits,
price: '20.00$ USD',
body: 'If you link your Patreon and Discord accounts, you will be given an exclusive australium-colored role in the official Uncletopia Discord server... which will let everyone else know how flipping epic you are.',
sub_title: 'Thanks for keeping the lights on in Uncletopia!',
url: 'https://www.patreon.com/join/uncletopia/checkout?rid=7602086'
}
];
return <>
<DonationPanel />
<Grid container spacing={3} className={classes.tierRow}>
{tiers.map(tier => <Grid item lg={4} sm={12} md={6} key={tier.title}><DonationTier tier={tier} /></Grid>)}
</Grid>
<Paper>
<Grid container>
<Grid item xs>
<Typography variant={'body1'} align={'center'} className={classes.donation_body}>
Please note that our donation system is created in a manner that offers zero in-game benefits.
We
feel that such offerings detract from the overall experience for everyone.
</Typography>
</Grid>
</Grid>
</Paper>
</>;
};
|
leighmacdonald/uncletopia-web
|
frontend/src/component/Home.tsx
|
import React, { useEffect, useState } from 'react';
import parseISO from 'date-fns/esm/parseISO';
import { eureka } from '../misc';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import makeStyles from '@material-ui/core/styles/makeStyles';
import { getNews, News } from '../api';
import format from 'date-fns/esm/format';
interface BlogEntryProps {
entry: News;
}
const useStyles = makeStyles((theme) => ({
body1: {
fontFamily: [
'"Helvetica Neue"',
'Helvetica',
'Roboto',
'Arial',
'sans-serif'
].join(','),
fontSize: '14px'
},
paper: {
padding: theme.spacing(2),
marginBottom: theme.spacing(2)
}
}));
export const BlogEntry = ({ entry }: BlogEntryProps) => {
const classes = useStyles();
const d = parseISO(entry.created_on);
return <Paper className={classes.paper}>
<Grid container>
<Grid item>
<Grid container>
<Grid item>
<Typography variant={'h2'}>{entry.title}</Typography>
<Typography variant={'subtitle1'}>{format(d, 'yyyy-MM-dd')}</Typography>
</Grid>
</Grid>
<Grid container>
<Grid item>
<div className={classes.body1} dangerouslySetInnerHTML={{ __html: entry.body_html }} />
</Grid>
</Grid>
</Grid>
</Grid>
</Paper>;
};
export const Home = () => {
const [news, setNews] = useState<News[]>([]);
useEffect(() => {
eureka();
}, []);
useEffect(() => {
const fn = async () => {
const fetchedNews = await getNews();
setNews(fetchedNews as News[]);
};
fn();
}, []
);
return <Grid container justifyContent={'center'}>
<Grid item xs={12} lg={8}>
{(news ?? []).map((e) => {
return <BlogEntry entry={e} key={`entry-${e.news_id}`} />;
})}
</Grid>
</Grid>;
};
|
leighmacdonald/uncletopia-web
|
frontend/src/component/Discord.tsx
|
import React from "react"
export const DiscordLink = () => {
window.open("/discord")
return <></>
}
|
leighmacdonald/uncletopia-web
|
frontend/src/component/Footer.tsx
|
import React from 'react';
import Container from '@material-ui/core/Container';
import Typography from '@material-ui/core/Typography';
import Link from '@material-ui/core/Link';
import makeStyles from '@material-ui/core/styles/makeStyles';
function Copyright() {
return (
<Typography variant='body2' color='textSecondary' align='center'>
<Link color='inherit' href='https://uncletopia.com/'>
© Copyright Uncletopia
</Link>{' '}
{new Date().getFullYear()}
</Typography>
);
}
const useStyles = makeStyles((theme) => ({
footer: {
marginTop: theme.spacing(3),
padding: theme.spacing(6, 0)
}
}));
export const Footer = () => {
const classes = useStyles();
return (
<footer className={classes.footer}>
<Container maxWidth='lg'>
<Copyright />
</Container>
</footer>
);
}
|
leighmacdonald/uncletopia-web
|
frontend/src/Theme.tsx
|
<filename>frontend/src/Theme.tsx<gh_stars>1-10
import createTheme from '@material-ui/core/styles/createTheme';
export const readableFonts = {fontFamily: [
'"Helvetica Neue"',
'Helvetica',
'Roboto',
'Arial',
'sans-serif'
].join(',')}
export const tf2theme = createTheme({
typography: {
fontFamily: [
'"TF2 Build"',
'"Helvetica Neue"',
'Helvetica',
'Roboto',
'Arial',
'sans-serif'
].join(','),
h1: { textAlign: 'center', fontSize: 48, marginBottom: 12 },
h2: { textAlign: 'center', fontSize: 36, marginBottom: 12 },
h3: { textAlign: 'center' },
h4: { textAlign: 'center'},
h5: { textAlign: 'center'},
h6: { textAlign: 'center' },
body1: {
...readableFonts,
fontWeight: 400,
fontSize: 20
}
},
spacing: 6,
palette: {
background: {
paper: 'rgb(20, 13, 10)',
default: 'rgb(38,24,18)'
},
primary: {
main: 'rgb(250,158,75)'
},
secondary: {
main: 'rgb(252, 198, 149)'
},
text: {
primary: 'rgb(246,231,222)',
secondary: 'rgb(218,189,171)'
}
}
});
|
leighmacdonald/uncletopia-web
|
frontend/src/index.tsx
|
import 'core-js/es/map';
import 'core-js/es/set';
import 'raf/polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import {App} from "./component/App";
ReactDOM.render(<App />, document.getElementById('root'));
|
leighmacdonald/uncletopia-web
|
frontend/src/component/AdminNews.tsx
|
<reponame>leighmacdonald/uncletopia-web<filename>frontend/src/component/AdminNews.tsx
import React, { useCallback, useMemo } from 'react';
import { useEffect, useState } from 'react';
import { createNews, deleteNews, getNews, NewsUpdatePayload, News, updateNews } from '../api';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import Paper from '@material-ui/core/Paper';
import Tab from '@material-ui/core/Tab';
import Tabs from '@material-ui/core/Tabs';
import TextField from '@material-ui/core/TextField';
import List from '@material-ui/core/List';
import Button from '@material-ui/core/Button';
import ButtonGroup from '@material-ui/core/ButtonGroup';
import Box from '@material-ui/core/Box';
import { marked } from 'marked';
import { readableFonts } from '../Theme';
import IconButton from '@material-ui/core/IconButton';
import PublicIcon from '@material-ui/icons/Public';
import EditIcon from '@material-ui/icons/Edit';
import DeleteForeverIcon from '@material-ui/icons/DeleteForever';
import AddCircleIcon from '@material-ui/icons/AddCircle';
import { Checkbox, FormControlLabel } from '@material-ui/core';
// import { DateTimePicker } from '@material-ui/pickers/DateTimePicker';
interface TabPanelProps {
value: number;
index: number;
children?: React.ReactNode;
}
const TabPanel = ({ value, index, children }: TabPanelProps) => {
return (
<div role={'tabpanel'}
hidden={value !== index}
id={`tab-panel-${index}`}
>
{value === index && (
<Box p={3}>
{children}
</Box>
)}
</div>
);
};
const emptyNews = {
news_id: 0, body_md: '', updated_on: '', published: false,
body_html: '', title: '', created_on: '', steam_id: 0
};
export const AdminNews = () => {
const [articles, setArticles] = useState<News[]>([]);
const [current, setCurrent] = useState<News>(emptyNews);
const [title, setTitle] = useState<string>('');
const [publish, setPublish] = useState<boolean>(false);
const [body, setBody] = useState<string>('');
const [len, setLen] = useState<number>(0);
const rendered = useMemo(() => {
return marked(body);
}, [body]);
const [tab, setTab] = useState(0);
const onDelete = useCallback(async (newsId?: number) => {
const i = newsId ?? current.news_id;
if (i > 0 && confirm('sure?')) {
if (await deleteNews(i)) {
setArticles(articles.filter(value => value.news_id !== i));
setCurrent(emptyNews);
}
}
}, []);
const updateArticles = async () => {
try {
const news = (await getNews() || []);
setArticles(news as News[]);
} catch (_e) {
setArticles([]);
}
};
useEffect(() => {
updateArticles();
}, []);
const updateLen = () => {
setLen(`${title}\n\n${body}`.length);
};
const onTitleChange = (e: any) => {
setTitle(e.target.value);
updateLen();
};
const onBodyChange = (e: any) => {
setBody(e.target.value);
updateLen();
};
const onSave = async () => {
const updated: NewsUpdatePayload = {
title: title,
body_md: body,
published: publish
};
if (current.news_id > 0) {
if (await updateNews(current.news_id, updated)) {
alert(`Updated ${current.news_id}`);
}
} else {
const created = await createNews(updated);
if (created.news_id > 0) {
alert(`Created ${created.news_id}`);
}
}
await updateArticles()
};
const loadArticle = (n: News) => {
setCurrent(n);
setTitle(n.title);
setBody(n.body_md);
setPublish(n.published);
};
const onChangePublished = (event: React.ChangeEvent<HTMLInputElement>) => {
setPublish(event.target.checked);
};
return <Grid container spacing={3}>
<Grid item xs={8}>
<Grid container spacing={2}>
<Grid item xs={12}>
<Paper>
<Tabs centered value={tab} onChange={(_e, value) => {
setTab(value);
}} aria-label='Raw / Preview toggle'>
<Tab label='Markdown' />
<Tab label='Preview' />
</Tabs>
</Paper>
</Grid>
<Grid item xs={12}>
<Paper>
<ButtonGroup>
<Button style={{ color: 'green' }} onClick={onSave}>Save</Button>
<Button style={{ color: 'orange' }} onClick={() => {
for (let i = 0; i < articles.length; i++) {
if (articles[i]?.news_id === current.news_id) {
loadArticle(articles[i] as News);
}
}
}}>Reset</Button>
<Button style={{ color: 'red' }} onClick={async () => {
await onDelete(current.news_id);
}}>Delete</Button>
</ButtonGroup>
</Paper>
</Grid>
<Grid item xs={12}>
<Paper>
<Typography variant={'h6'}>Len: {len}/2000</Typography>
<Typography variant={'body1'} align={'center' }>Messages longer than 2000 cannot be posted to
discord because: "fuck you" - Discord.</Typography>
</Paper></Grid>
<Grid item xs={12}>
<Paper>
<TabPanel index={0} value={tab}>
<Grid container>
<Grid item xs={12}>
<FormControlLabel
control={
<Checkbox
checked={publish}
onChange={onChangePublished}
name='Published'
color='primary'
/>
}
label='Published?'
/>
</Grid>
<Grid item xs={12}>
<TextField label='Title' placeholder={'Dane got a pan!'}
variant='filled' fullWidth
onChange={onTitleChange}
value={title} />
</Grid>
<Grid item xs={12}>
<TextField
id='standard-textarea'
label='Article Body (Markdown)'
placeholder='Placeholder'
variant={'filled'}
value={body}
minRows={25}
multiline
onChange={onBodyChange}
fullWidth
/>
</Grid>
</Grid>
</TabPanel>
<TabPanel index={1} value={tab}>
<Grid container>
<Grid item xs={12}>
<div style={{ ...readableFonts }} dangerouslySetInnerHTML={{ __html: rendered }} />
</Grid>
</Grid>
</TabPanel>
</Paper>
</Grid>
</Grid>
</Grid>
<Grid item xs={4}>
<Paper style={{ padding: '1rem' }}>
<Typography variant={'h4'}>Articles</Typography>
<ButtonGroup fullWidth>
<Button color={'primary'}
onClick={() => {
loadArticle(emptyNews);
}}>
<AddCircleIcon />Create New
</Button>
</ButtonGroup>
</Paper>
<Paper style={{ marginTop: '1rem' }}>
<List>
{articles.map((a) =>
<ListItem key={`news-${a.news_id}`}>
<ListItemText>{a.title}<ButtonGroup fullWidth>
<IconButton color={'primary'}><PublicIcon /></IconButton>
<IconButton color={'primary'} onClick={() => {
loadArticle(a);
}}><EditIcon /></IconButton>
<IconButton color={'primary'} onClick={async () => {
await onDelete(a.news_id);
}}><DeleteForeverIcon /></IconButton>
</ButtonGroup>
</ListItemText>
</ListItem>
)}
</List>
</Paper>
</Grid>
</Grid>;
};
|
leighmacdonald/uncletopia-web
|
frontend/src/component/Servers.tsx
|
import React, { useCallback, useEffect, useState } from 'react';
import Button from '@material-ui/core/Button';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import makeStyles from '@material-ui/core/styles/makeStyles';
import { fetchServers, Server } from '../api';
// @ts-ignore
//import * as x from 'leaflet/dist/leaflet.css';
import { ServerMap } from './ServerMap';
import { LatLngLiteral } from 'leaflet';
import { MapStateCtx, useMapStateCtx } from '../ctx/MapStateCtx';
import { ServerQueue } from './ServerQueue';
import { ServerFilters } from './ServerFilters';
import Link from '@material-ui/core/Link';
import CheckIcon from '@material-ui/icons/Check';
import { Flag } from './Flag';
import { ButtonGroup, Card, CardContent, LinearProgress, LinearProgressProps } from '@material-ui/core';
import sum from 'lodash-es/sum';
import Box from '@material-ui/core/Box';
import { getDistance } from '../geo';
interface ServerRowProps {
server: Server;
onClick: () => void;
showDetails: boolean;
}
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
padding: theme.spacing(1),
marginBottom: theme.spacing(1),
paddingBottom: theme.spacing(1),
paddingRight: theme.spacing(0)
},
item: {
// paddingBottom: 0
},
h1: { textAlign: 'left', fontSize: 20, marginBottom: 0 },
h2: { textAlign: 'center', fontSize: 16, marginBottom: 0 },
flag: {
maxHeight: '20px',
width: '40px',
verticalAlign: 'middle',
paddingRight: theme.spacing(0),
display: 'inline-block'
},
rowBody: {
width: '100%',
height: '24px',
flexWrap: 'nowrap',
alignItems: 'center'
// justifyContent: 'center'
},
stats: {
width: '100%',
flexWrap: 'nowrap',
alignItems: 'center'
// justifyContent: 'center'
},
statsText: {
textAlign: 'center', fontSize: 20, marginBottom: 0
},
button: {
backgroundColor: 'rgb(44,91,17)',
width: '100%',
height: '100%',
'&:hover': {
backgroundColor: 'rgb(74,154,28)'
}
}
}));
const ServerRow = ({ server }: ServerRowProps) => {
const classes = useStyles();
const [copied, setCopied] = useState<boolean>(false);
const players = server?.a2s?.Players || 0;
const maxPlayers = server?.a2s?.MaxPlayers || 32;
const [showPlayers, setShowPlayers ] = useState<boolean>(false);
return <Paper className={classes.root} style={{ borderTopLeftRadius: 0, borderTopRightRadius: 0 }} onClick={() => {
setShowPlayers(!showPlayers)
}}>
<Grid container className={classes.rowBody}>
{/*<Grid item md={1} sm={false} className={classes.item}>*/}
{/* <Flag countryCode={server.cc} />*/}
{/*</Grid>*/}
<Grid item md={5} sm={12} className={classes.item}>
<Flag countryCode={server.cc} />
<Typography variant={'h1'} className={classes.h1} gutterBottom={false} style={
{display: 'inline-block', paddingLeft: "10px"}}>
{server.name_long}
</Typography>
{/*<Button onClick={onClick}>Players</Button>*/}
</Grid>
<Grid item md={2} className={classes.item}>
<Typography variant={'h2'} className={classes.h2}
gutterBottom={false}>{server.a2s?.Map || ''}</Typography>
</Grid>
<Grid item md={2} className={classes.item}>
<Typography variant={'h2'}
className={classes.h2}
gutterBottom={false}>{Math.min(players, maxPlayers)} / {maxPlayers}</Typography>
</Grid>
<Grid item md={3} className={classes.item}>
<ButtonGroup fullWidth>
<Button className={classes.button} onClick={() => {
navigator.clipboard.writeText(`connect ${server.host}:${server.port}`).then(() => {
setCopied(true), () => setCopied(false);
}
);
}
}>Copy {copied && <CheckIcon />}</Button>
<Link component={Button} href={`steam://connect/${server.host}:${server.port}`} color={'inherit'}
style={{ textDecoration: 'none' }}
className={classes.button}>Connect</Link>
</ButtonGroup>
</Grid>
{/*{showDetails && <Grid item xs={12}>*/}
{/* <Typography variant={'h2'}>Selected</Typography>*/}
{/*</Grid>}*/}
</Grid>
</Paper>;
};
function LinearProgressWithLabel(props: LinearProgressProps & { value: number }) {
return (
<Box display='flex' alignItems='center'>
<Box width='100%' mr={1}>
<LinearProgress variant='determinate' {...props} />
</Box>
<Box minWidth={35}>
<Typography variant='body2' color='textSecondary'>{`${Math.round(props.value)}%`}</Typography>
</Box>
</Box>
);
}
export const ServerStats = () => {
const classes = useStyles();
const { servers } = useMapStateCtx();
const cap = servers.length * 24;
const use = sum(servers.map(value => value?.a2s?.Players || 0));
const regions = servers.reduce((acc, cv) => {
if (!acc.hasOwnProperty(cv.region)) {
acc[cv.region] = [];
}
// @ts-ignore
acc[cv.region].push(cv);
return acc;
}, {} as Record<string, Server[]>);
const keys = Object.keys(regions)
keys.sort()
return <Paper style={{ marginBottom: '1rem', marginTop: "1rem" }}>
<Grid container justifyContent='center' spacing={3}>
<Grid item xs>
<Grid container spacing={3} style={{paddingLeft: "10px"}}>
<Grid item xs={3}>
<Typography className={classes.statsText} style={{ display: 'inline' }}
variant={'subtitle1'}
align={'center'}>Global: {use} / {cap}</Typography>
<LinearProgressWithLabel value={Math.round((use / cap) * 100)} />
</Grid>
{keys.map((v) => {
const pSum = sum((regions.hasOwnProperty(v) && regions[v] || []).map((value => value?.a2s?.Players || 0)));
const pMax = sum((regions.hasOwnProperty(v) && regions[v] || []).map((value => value?.a2s?.MaxPlayers || 24)));
return <Grid item xs={3} key={`stat-${v}`}>
<Typography className={classes.statsText} style={{ display: 'inline' }}
variant={'subtitle1'}
align={'center'}>{v}: {pSum} / {pMax}</Typography>
<LinearProgressWithLabel value={Math.round((pSum / pMax) * 100)} />
</Grid>;
})}
</Grid>
</Grid>
</Grid>
</Paper>;
};
export const ServerList = () => {
const { selectedServers, pos } = useMapStateCtx();
const [selectedRow, setSelectedRow] = useState<string>("")
if (selectedServers.length === 0) {
return <Grid container>
<Grid item xs={12}>
<Typography variant={'h1'}>No servers :'(</Typography>
</Grid>
</Grid>;
}
return <Grid container>
<Grid item xs={12}>
{(selectedServers || []).
map(srv => {
return {...srv, "distance": getDistance(pos, { lat: srv.latitude, lng: srv.longitude })}
}).
sort((a, b) => {
// Sort by position if we have a non-default position.
// otherwise sort by server name
if (pos.lat !== 42.434719) {
if (a.distance > b.distance) { return 1; }
if (a.distance < b.distance) { return -1; }
return 0;
}
return ('' + a.name_short).localeCompare(b.name_short)
}).
map(server => <ServerRow showDetails={selectedRow == server.name_short} onClick={() => {
setSelectedRow(server.name_short)
}} key={`server-${server.host}-${server.port}`}
server={server} />)}
</Grid>
</Grid>;
};
export default function ServerNotice() {
return (
<Card style={{marginBottom: "0.5rem"}}>
<CardContent>
<Typography color="textSecondary" variant={'h6'}>Singapore Notice</Typography>
<Typography color="textSecondary" variant={'body1'}>
Singapore servers are currently experiencing on-going issues with upstream filtering. The servers
are in fact alive, but some users may have trouble connecting using the website or server browser.
You can still connect manually via console by using the copy button and pasting it into your TF2 console.
</Typography>
</CardContent>
</Card>
)
}
export const Servers = () => {
const [servers, setServers] = useState<Server[]>([]);
const [pos, setPos] = useState<LatLngLiteral>({ lat: 42.434719, lng: 42.434719 });
const [customRange, setCustomRange] = useState<number>(500);
const [selectedServers, setSelectedServers] = useState<Server[]>([]);
const [filterByRegion, setFilterByRegion] = useState<boolean>(false);
const [showOpenOnly, setShowOpenOnly] = useState<boolean>(false);
const [selectedRegion, setSelectedRegion] = useState<string[]>(['any']);
const loadServers = useCallback(async () => {
try {
const s = (await fetchServers() || [])
setServers(s);
setSelectedServers(s);
} catch (e) {
console.log(`Failed to load servers: ${e}`)
}
}, [pos, setServers, setSelectedServers]);
// Sort by distance once we get a position
useEffect(() => {
setServers(servers)
}, [pos])
useEffect(() => {
// noinspection JSIgnoredPromiseFromCall
loadServers();
setInterval(loadServers, 10000);
}, []);
return <>
<MapStateCtx.Provider value={{
servers, setServers, customRange, setCustomRange,
pos, setPos, selectedServers, setSelectedServers,
filterByRegion, setFilterByRegion, showOpenOnly,
setShowOpenOnly, selectedRegion, setSelectedRegion
}}>
<ServerMap />
<ServerFilters />
<ServerQueue />
<ServerStats />
<ServerList />
<ServerNotice />
</MapStateCtx.Provider>
</>;
};
|
leighmacdonald/uncletopia-web
|
frontend/src/component/ServerMap.tsx
|
import { Grid } from '@material-ui/core';
import React, { useEffect, useMemo } from 'react';
import { MapContainer, useMap } from 'react-leaflet';
import { Marker } from 'react-leaflet';
import { Circle } from 'react-leaflet';
import { TileLayer } from 'react-leaflet';
import { useMapStateCtx } from '../ctx/MapStateCtx';
import { getDistance } from '../geo';
const UserPosition = () => {
const map = useMap();
const { setPos } = useMapStateCtx();
useEffect(() => {
const defPos = { lat: 42.434719, lng: -83.985001 }
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(pos => {
const userPos = { lat: pos.coords.latitude, lng: pos.coords.longitude };
map.setView(userPos);
setPos(userPos);
}, _err => {
map.setView(defPos);
setPos(defPos);
});
} else {
map.setView(defPos);
setPos(defPos);
}
}, []);
return null;
};
const UserPositionMarker = () => {
const { pos } = useMapStateCtx();
return <>
{pos.lat != 0 && <Marker autoPan={true} title={'You'} position={pos} />}
</>;
};
export const UserPingRadius = () => {
const { pos, customRange, filterByRegion, selectedServers, setCustomRange } = useMapStateCtx();
const baseOpts = { color: 'green', opacity: 0.1, interactive: true };
const markers = [
{ ...baseOpts, radius: 3000000, color: 'red' },
{ ...baseOpts, radius: 1500000, color: 'yellow' },
{ ...baseOpts, radius: 500000, color: 'green' }
];
const c = useMemo(() => {
return filterByRegion && <Circle center={pos} radius={customRange * 1000} color={'green'} />;
}, [customRange, pos, filterByRegion, selectedServers, setCustomRange]);
return <>
{c}
{pos.lat != 0 && markers.map(m => <Circle center={pos} key={m.radius} {...m} fillOpacity={0.1} />)}
</>;
};
export const ServerMarkers = () => {
const { pos, servers, customRange, selectedServers } = useMapStateCtx();
const d = useMemo(() => servers.map((s) => {
//const dis = getDistance(pos, { lat: s.latitude, lng: s.longitude }) / 1000;
return <Circle center={[s.latitude, s.longitude]} radius={50000}
color={getDistance(pos, {
lat: s.latitude,
lng: s.longitude
}) < customRange * 1000 ? 'green' : 'red'}
key={s.server_id} />;
}), [selectedServers, customRange, pos, servers]);
return <>
{servers && d}
</>;
};
export const ServerMap = () =>
<Grid container>
<Grid item xs={12}>
<MapContainer zoom={4} scrollWheelZoom={true} id={'map'} style={{ height: '500px', width: '100%' }}
attributionControl={false} minZoom={3} worldCopyJump={true}>
<TileLayer url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' />
<UserPosition />
<ServerMarkers />
<UserPingRadius />
<UserPositionMarker />
</MapContainer>
</Grid>
</Grid>;
|
leighmacdonald/uncletopia-web
|
frontend/src/component/LoginSuccess.tsx
|
import { PermissionLevel } from '../api';
import React from 'react';
import { Navigate } from 'react-router-dom';
/**
* This is what the user gets redirected to after a successful steam openid redirect.
*/
export const LoginSuccess = (): JSX.Element => {
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get('token');
if (token != null && token.length > 0) {
localStorage.setItem('token', token);
localStorage.setItem(
'permission_level',
`${
urlParams.get('permission_level') ??
PermissionLevel.Authenticated
}`
);
}
let next_url = urlParams.get('next_url');
if (next_url == null || next_url == '') {
next_url = '/';
}
return <Navigate to={next_url} />;
};
|
leighmacdonald/uncletopia-web
|
frontend/src/component/Header.tsx
|
<reponame>leighmacdonald/uncletopia-web
// How to alias this?
import { Link as LinkMUI } from '@material-ui/core';
import Avatar from '@material-ui/core/Avatar';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Toolbar from '@material-ui/core/Toolbar';
import AppBar from '@material-ui/core/AppBar';
import IconButton from '@material-ui/core/IconButton';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import Button from '@material-ui/core/Button';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Badge from '@material-ui/core/Badge';
import Divider from '@material-ui/core/Divider';
import Typography from '@material-ui/core/Typography';
import makeStyles from '@material-ui/core/styles/makeStyles';
import React, { forwardRef, useMemo, useState } from 'react';
import NotificationsIcon from '@material-ui/icons/Notifications';
import ExitToAppIcon from '@material-ui/icons/ExitToApp';
import AccountCircleIcon from '@material-ui/icons/AccountCircle';
import AnnouncementIcon from '@material-ui/icons/Announcement';
import SettingsIcon from '@material-ui/icons/Settings';
import MoreIcon from '@material-ui/icons/More';
import { Link } from 'react-router-dom';
import { useCurrentUserCtx } from '../ctx/CurrentUserCtx';
// @ts-ignore
import SteamLogo from '../images/steam_login_sm.png';
import { PermissionLevel } from '../api';
export interface HeaderLink {
title: string;
url: string;
submenu?: HeaderLink[];
}
const links: HeaderLink[] = [
{ title: 'Home', url: '/' },
{ title: 'Servers', url: '/servers' },
{ title: 'Demos', url: '/demos' },
{ title: 'Maps', url: '/maps' },
{ title: 'Rules', url: '/rules' },
{ title: 'Donate', url: '/donate' },
{ title: 'Discord', url: '/discord' }
];
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex'
},
offset: theme.mixins.toolbar,
grow: {
flexGrow: 1
},
sectionDesktop: {
display: 'none',
[theme.breakpoints.up('md')]: {
display: 'flex'
}
},
sectionMobile: {
display: 'flex',
[theme.breakpoints.up('md')]: {
display: 'none'
}
},
toolbar: {
flexGrow: 1,
backgroundColor: theme.palette.background.paper
},
buttons: {
// fontFamily: theme.typography.fontFamily,
color: '#fde1c7'
}
}));
//
// export const withRouter = (Component: any) => {
// const Wrapper = (props: any) => {
// const history = useHistory();
//
// return (
// <Component
// history={history}
// {...props}
// />
// );
// };
//
// return Wrapper;
// };
export const steamOIDUrl = (): string => {
// noinspection HttpUrlsUsage
return `https://steamcommunity.com/openid/login?openid.ns=` + encodeURIComponent('http://specs.openid.net/auth/2.0') +
'&openid.mode=checkid_setup' +
'&openid.return_to=' + encodeURIComponent(`${window.location.protocol}//${window.location.hostname}/auth/callback?return_url=${window.location.pathname}`) +
`&openid.realm=` + encodeURIComponent(`${window.location.protocol}//${window.location.hostname}`) +
'&openid.ns.sreg=' + encodeURIComponent('http://openid.net/extensions/sreg/1.1') +
'&openid.claimed_id=' + encodeURIComponent('http://specs.openid.net/auth/2.0/identifier_select') +
'&openid.identity=' + encodeURIComponent('http://specs.openid.net/auth/2.0/identifier_select');
};
interface GLinkProps {
icon?: string | JSX.Element;
primary: string;
to: string;
}
export const GLink = ({ primary, to }: GLinkProps): JSX.Element => {
const classes = useStyles();
const CustomLink = useMemo(() => {
const f = forwardRef<HTMLAnchorElement>((linkProps, ref) => (
<Link ref={ref} to={to} {...linkProps} />
));
f.displayName = 'GLink';
return f;
}, [to]);
return (
<Button component={CustomLink} className={classes.buttons}>
{primary}
</Button>
);
};
export function RenderMenuButton(link: HeaderLink) {
return <GLink primary={link.title} to={link.url} />;
}
const TopBar = ({ history }: any): JSX.Element => {
const classes = useStyles();
const [anchorEl, setAnchorEl] = React.useState(null);
const [anchorProfileMenuEl, setAnchorProfileMenuEl] =
useState<Element | null>(null);
const [mobileMoreAnchorEl, setMobileMoreAnchorEl] =
useState<Element | null>(null);
const isProfileMenuOpen = Boolean(anchorProfileMenuEl);
const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);
const { currentUser } = useCurrentUserCtx();
const handleProfileMenuOpen = (event: React.MouseEvent) => {
setAnchorProfileMenuEl(event.currentTarget);
};
const handleMobileMenuClose = () => {
setMobileMoreAnchorEl(null);
};
const handleProfileMenuClose = () => {
setAnchorProfileMenuEl(null);
handleMobileMenuClose();
};
const handleMobileMenuOpen = (event: React.MouseEvent) => {
setMobileMoreAnchorEl(event.currentTarget);
};
const open = Boolean(anchorEl);
const loadRoute = (route: string) => {
history.push(route);
handleProfileMenuClose();
handleMobileMenuClose();
};
const renderLinkedMenuItem = (
text: string,
route: string,
icon: JSX.Element
) => (
<MenuItem onClick={() => loadRoute(route)}>
<ListItemIcon>{icon}</ListItemIcon>
<ListItemText primary={text} />
</MenuItem>
);
const handleUserMenu = (event: any) => {
setAnchorEl(event.currentTarget);
};
const handleUserMenuClose = () => {
setAnchorEl(null);
};
const menuId = 'primary-menu';
const renderProfileMenu = (
<Menu
anchorEl={anchorProfileMenuEl}
anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
id={menuId}
keepMounted
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
open={isProfileMenuOpen}
onClose={handleProfileMenuClose}
>
{renderLinkedMenuItem('Profile', '/profile', <AccountCircleIcon />)}
{renderLinkedMenuItem('Settings', '/settings', <SettingsIcon />)}
<Divider light />
{renderLinkedMenuItem('Logout', '/logout', <ExitToAppIcon />)}
</Menu>
);
//const perms = parseInt(localStorage.getItem('permission_level') || '1');
const mobileMenuId = 'primary-menu-mobile';
const renderMobileMenu = (
<Menu
anchorEl={mobileMoreAnchorEl}
anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
id={mobileMenuId}
keepMounted
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
open={isMobileMenuOpen}
onClose={handleMobileMenuClose}
>
<MenuItem>
<IconButton
aria-label='show 0 new notifications'
color='inherit'
>
<Badge badgeContent={0} color='secondary'>
<NotificationsIcon />
</Badge>
</IconButton>
<p>Notifications</p>
</MenuItem>
<MenuItem onClick={handleProfileMenuOpen}>
<IconButton
aria-label='account of current user'
aria-controls='primary-menu'
aria-haspopup='true'
color='inherit'
>
<AccountCircleIcon />
</IconButton>
<p>Profile</p>
</MenuItem>
</Menu>
);
return (
<>
<AppBar position='fixed'>
<Toolbar variant={'regular'} className={classes.toolbar} disableGutters={false}>
<Typography variant='h3' color={'primary'} style={{ marginRight: '1rem' }}>
Uncletopia
</Typography>
{links.map(props => <RenderMenuButton key={`m-${props.title}`} {...props} />)}
<div className={classes.grow} />
{currentUser.steam_id && currentUser?.steam_profile &&
<Button
aria-label='account of current user'
aria-controls='menu-appbar'
aria-haspopup='true'
onClick={handleUserMenu}
className={classes.buttons}
>
<Avatar alt={currentUser?.steam_profile?.personaname} src={currentUser?.steam_profile.avatar} />
</Button>
}
<div className={classes.sectionDesktop}>
{currentUser.steam_id == '' &&
<LinkMUI component={Button} href={steamOIDUrl()}>
<img
src={SteamLogo}
alt={'Steam Login'}
/>
</LinkMUI>
}
{currentUser.steam_id !== '' && (
<Menu
id='menu-appbar'
anchorEl={anchorEl}
anchorOrigin={{
vertical: 'top',
horizontal: 'right'
}}
keepMounted
transformOrigin={{
vertical: 'top',
horizontal: 'right'
}}
open={open}
onClose={handleUserMenuClose}
title={currentUser?.steam_profile?.personaname || 'Guest'}
>
{renderLinkedMenuItem('Profile', '/profile', <AccountCircleIcon color={'secondary'} />)}
{currentUser?.steam_profile?.steamid != '' &&
currentUser.permission_level >= PermissionLevel.Admin &&
renderLinkedMenuItem('News', '/admin/news',
<AnnouncementIcon color={'secondary'} />)}
{renderLinkedMenuItem('Logout', '/logout', <ExitToAppIcon color={'secondary'} />)}
</Menu>)}
</div>
<div className={classes.sectionMobile}>
<IconButton
aria-label='show more'
aria-controls={mobileMenuId}
aria-haspopup='true'
onClick={handleMobileMenuOpen}
color='inherit'
>
<MoreIcon />
</IconButton>
</div>
</Toolbar>
</AppBar>
<div className={classes.offset} />
{renderMobileMenu}
{renderProfileMenu}
</>
);
};
export const Header = () => {
return (
<Paper style={{ marginBottom: '2rem' }}>
<Grid container>
<Grid item md={12}>
<TopBar />
</Grid>
</Grid>
</Paper>
);
};
|
leighmacdonald/uncletopia-web
|
frontend/src/component/Maps.tsx
|
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import Paper from '@material-ui/core/Paper';
import React from 'react';
import { Link } from '@material-ui/core';
import FiberNewIcon from '@material-ui/icons/FiberNew';
import ACUnitIcon from '@material-ui/icons/AcUnit';
interface Map {
name: string;
link: string;
icon: 'none' | 'new' | 'smissmas';
}
interface MapSet {
name: string;
maps: Map[];
}
export const Maps = () => {
const mapList: MapSet[] = [
{
name: 'Payload', maps: [
{ name: 'Badwater', link: 'https://wiki.teamfortress.com/wiki/Badwater_Basin', icon: 'none' },
{ name: 'Barnblitz', link: 'https://wiki.teamfortress.com/wiki/Barnblitz', icon: 'none' },
{ name: 'Breadspace', link: 'https://wiki.teamfortress.com/wiki/Breadspace', icon: 'smissmas' },
{ name: 'Borneo', link: 'https://wiki.teamfortress.com/wiki/Borneo', icon: 'none' },
{ name: 'Chilly', link: 'https://wiki.teamfortress.com/wiki/Chilly', icon: 'smissmas' },
{ name: 'Frontier', link: 'https://wiki.teamfortress.com/wiki/Frontier', icon: 'none' },
{ name: 'Gold Rush', link: 'https://wiki.teamfortress.com/wiki/Gold_Rush', icon: 'new' },
{ name: 'Pier', link: 'https://wiki.teamfortress.com/wiki/Pier', icon: 'none' },
{ name: 'Polar', link: 'https://wiki.teamfortress.com/wiki/Polar', icon: 'smissmas' },
{ name: 'Snowycoast', link: 'https://wiki.teamfortress.com/wiki/Snowycoast', icon: 'none' },
{ name: 'SnowVille', link: 'https://wiki.teamfortress.com/wiki/SnowVille', icon: 'smissmas' },
{ name: 'Swiftwater', link: 'https://wiki.teamfortress.com/wiki/Swiftwater', icon: 'none' },
{ name: 'Thunder Mountain', link: 'https://wiki.teamfortress.com/wiki/Thunder_Mountain', icon: 'none' },
{ name: 'Upward', link: 'https://wiki.teamfortress.com/wiki/Upward', icon: 'none' },
{ name: 'Wutville', link: 'https://wiki.teamfortress.com/wiki/Wutville', icon: 'smissmas' }
]
},
{
name: 'Control Point', maps: [
{ name: 'Foundry', link: 'https://wiki.teamfortress.com/wiki/Foundry_(Control_Point)', icon: 'new' },
{ name: 'Granary', link: 'https://wiki.teamfortress.com/wiki/Granary_(Control_Point)', icon: 'new' },
{ name: 'Gullywash', link: 'https://wiki.teamfortress.com/wiki/Gullywash', icon: 'new' },
{ name: 'Metalworks', link: 'https://wiki.teamfortress.com/wiki/Metalworks', icon: 'none' },
{ name: 'Powerhouse', link: 'https://wiki.teamfortress.com/wiki/Powerhouse', icon: 'new' },
{ name: 'Process', link: 'https://wiki.teamfortress.com/wiki/Process', icon: 'none' },
{ name: 'Snakewater', link: 'https://wiki.teamfortress.com/wiki/Snakewater', icon: 'none' },
{ name: 'Sunshine', link: 'https://wiki.teamfortress.com/wiki/Sunshine', icon: 'none' }
]
},
{
name: 'KOTH', maps: [
{ name: 'Badlands', link: 'https://wiki.teamfortress.com/wiki/Badlands_(King_of_the_Hill)', icon: 'none' },
{ name: 'Brazil', link: 'https://wiki.teamfortress.com/wiki/Brazil', icon: 'new' },
{ name: 'Cascade', link: 'https://wiki.teamfortress.com/wiki/Cascade', icon: 'smissmas' },
{ name: 'Highpass', link: 'https://wiki.teamfortress.com/wiki/Highpass', icon: 'none' },
{ name: 'Kong King', link: 'https://wiki.teamfortress.com/wiki/Kong_King', icon: 'none' },
{ name: 'Lakeside', link: 'https://wiki.teamfortress.com/wiki/Lakeside', icon: 'none' },
{ name: 'Lazarus', link: 'https://wiki.teamfortress.com/wiki/Lazarus', icon: 'new' },
{ name: 'Sawmill', link: 'https://wiki.teamfortress.com/wiki/Sawmill', icon: 'none' },
{ name: 'Suijin', link: 'https://wiki.teamfortress.com/wiki/Suijin', icon: 'none' },
{ name: 'Viaduct', link: 'https://wiki.teamfortress.com/wiki/Viaduct', icon: 'none' }
]
},
{
name: 'Attack/Defend', maps: [
{ name: 'Altitude', link: 'https://wiki.teamfortress.com/wiki/Altitude', icon: 'smissmas' },
{ name: 'Dustbowl', link: 'https://wiki.teamfortress.com/wiki/Dustbowl', icon: 'none' },
{ name: 'Gorge', link: 'https://wiki.teamfortress.com/wiki/Gorge', icon: 'none' },
{ name: 'Gravel Pit', link: 'https://wiki.teamfortress.com/wiki/Gravel_Pit', icon: 'new' },
{ name: 'Mossrock', link: 'https://wiki.teamfortress.com/wiki/Mossrock', icon: 'none' },
{ name: 'Mountain Lab', link: 'https://wiki.teamfortress.com/wiki/Mountain_Lab', icon: 'none' },
{ name: 'Steel', link: 'https://wiki.teamfortress.com/wiki/Steel', icon: 'none' },
{ name: 'Mercenary Park', link: 'https://wiki.teamfortress.com/wiki/Mercenary_Park', icon: 'new' }
]
},
{
name: 'CTF', maps: [
{ name: 'Doublefrost', link: 'https://wiki.teamfortress.com/wiki/Doublefrost', icon: "smissmas" },
{ name: 'Landfall', link: 'https://wiki.teamfortress.com/wiki/Landfall',icon: "new" },
{ name: 'Snowfall', link: 'https://wiki.teamfortress.com/wiki/Snowfall', icon: "smissmas" }
]
}
];
return <>
<Grid container spacing={3}>
{mapList.map(m =>
<Grid item xs={6} lg={3} key={m.name}>
<Paper style={{ paddingTop: '1rem' }}>
<Typography variant={'h6'}>{m.name}</Typography>
<List>
{m.maps.map((map_info) =>
<ListItem key={map_info.name}>
<Link component={Button} fullWidth href={map_info.link}
style={{ textDecoration: 'none' }}>
{map_info.name}
{map_info.icon == "new" &&
<FiberNewIcon style={{ color: 'orange', paddingLeft: '4px' }} />}
{map_info.icon == "smissmas" &&
<ACUnitIcon style={{ color: 'rgba(127,195,255,0.66)', paddingLeft: '4px' }} />}
</Link>
</ListItem>
)}
</List>
</Paper>
</Grid>
)}
</Grid>
</>;
};
|
leighmacdonald/uncletopia-web
|
frontend/src/component/ServerQueue.tsx
|
// import useWebSocket, { ReadyState } from 'react-use-websocket';
import React from 'react';
import Button from '@material-ui/core/Button';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import makeStyles from '@material-ui/core/styles/makeStyles';
import { useCurrentUserCtx } from '../ctx/CurrentUserCtx';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
padding: theme.spacing(2),
marginBottom: theme.spacing(2)
},
button: {
backgroundColor: 'rgb(44,91,17)',
width: '100%',
height: '100%',
'&:hover': {
backgroundColor: 'rgb(74,154,28)'
}
}
}));
export const ServerQueue = () => {
const classes = useStyles();
const { currentUser } = useCurrentUserCtx();
// const { sendJsonMessage, lastJsonMessage, readyState } = useWebSocket();
if (!["76561198084134025", "76561198057999536"].includes(currentUser.steam_id)) {
return <></>;
}
return <Paper className={classes.root}>
<Grid container>
<Grid item xs={10}>
<Typography variant={'h4'} align={'left'}>Queue</Typography>
</Grid>
<Grid item xs={2}>
<Button className={classes.button} variant={'contained'}>Start Queue</Button>
</Grid>
</Grid>
</Paper>;
};
|
leighmacdonald/uncletopia-web
|
frontend/src/component/App.tsx
|
<reponame>leighmacdonald/uncletopia-web
import CssBaseline from '@material-ui/core/CssBaseline';
import Container from '@material-ui/core/Container';
import ThemeProvider from '@material-ui/styles/ThemeProvider';
import { Header } from './Header';
import { Footer } from './Footer';
import {
BrowserRouter as Router,
Routes,
Route
} from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import { Home } from './Home';
import { Servers } from './Servers';
import { Donate } from './Donate';
import { tf2theme } from '../Theme';
import { CurrentUserCtx, GuestProfile } from '../ctx/CurrentUserCtx';
import { UserFlashCtx } from '../ctx/UserFlashCtx';
import { Flash, Flashes } from './Flashes';
import { LoginSuccess } from './LoginSuccess';
import { getCurrentProfile, Person } from '../api';
import { UserProfile } from './Profile';
import { Logout } from './Logout';
import { Maps } from './Maps';
import { Rules } from './Rules';
import { DiscordLink } from './Discord';
import { AdminNews } from './AdminNews';
import MuiPickersUtilsProvider from '@material-ui/pickers/MuiPickersUtilsProvider';
import DateFnsUtils from '@date-io/date-fns';
import { Demos } from './Demos';
export const App = () => {
const [currentUser, setCurrentUser] = useState<NonNullable<Person>>(GuestProfile);
const [flashes, setFlashes] = useState<Flash[]>([]);
useEffect(() => {
const fetchProfile = async () => {
const token = localStorage.getItem('token');
if (token != null && token != '') {
const profile =
(await getCurrentProfile()) as NonNullable<Person>;
setCurrentUser(profile);
}
};
// noinspection JSIgnoredPromiseFromCall
fetchProfile();
}, []);
return (
<CurrentUserCtx.Provider value={{ currentUser, setCurrentUser }}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Router>
<React.Fragment>
<ThemeProvider theme={tf2theme}>
<Container>
<CssBaseline />
<Header />
<UserFlashCtx.Provider value={{ flashes, setFlashes }}>
<Flashes flashes={flashes} />
</UserFlashCtx.Provider>
<Container maxWidth='lg'>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/servers' element={<Servers />} />
<Route path='/maps' element={<Maps />} />
<Route path='/demos' element={<Demos />} />
<Route path='/rules' element={<Rules />} />
<Route path='/donate' element={<Donate />} />
<Route path='/discord' element={<DiscordLink />} />
<Route path='/profile' element={<UserProfile />} />
<Route
path={'/login/success'}
element={<LoginSuccess />}
/>
<Route
path={'/logout'}
element={<Logout />}
/>
<Route
path={'/admin/news'}
element={<AdminNews />}
/>
</Routes>
<Footer />
</Container>
</Container>
</ThemeProvider>
</React.Fragment>
</Router>
</MuiPickersUtilsProvider>
</CurrentUserCtx.Provider>
);
};
|
leighmacdonald/uncletopia-web
|
frontend/src/component/ServerFilters.tsx
|
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import FormControl from '@material-ui/core/FormControl';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import Paper from '@material-ui/core/Paper';
import Select from '@material-ui/core/Select';
import Slider from '@material-ui/core/Slider';
import Switch from '@material-ui/core/Switch';
import React, { useEffect } from 'react';
import makeStyles from '@material-ui/core/styles/makeStyles';
import uniq from 'lodash-es/uniq';
import { useMapStateCtx } from '../ctx/MapStateCtx';
import { getDistance } from '../geo';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
padding: theme.spacing(2),
marginBottom: theme.spacing(2)
},
item: {
paddingBottom: 0
},
h1: { textAlign: 'left', fontSize: 20, marginBottom: 0 },
h2: { textAlign: 'center', fontSize: 16, marginBottom: 0 },
formControl: {
margin: theme.spacing(1),
minWidth: 120
}
}));
export const ServerFilters = () => {
const classes = useStyles();
const {
setCustomRange, servers, customRange, pos, setSelectedServers,
setFilterByRegion, setServers, filterByRegion, selectedRegion, setSelectedRegion,
setShowOpenOnly, showOpenOnly
} = useMapStateCtx();
const regions = uniq(['any', ...(servers || []).map(value => value.region)]);
const onRegionsChange = (event: React.ChangeEvent<{ value: unknown }>) => {
const el = event.target as any;
setSelectedRegion(el.value);
};
const onShowOpenOnlyChanged = (_event: any, checked: boolean) => {
setShowOpenOnly(checked);
};
const onRegionsToggleEnabledChanged = (_event: any, checked: boolean) => {
setFilterByRegion(checked);
};
const defaultState = {
'showOpenOnly': false,
'selectedRegion': ['any'],
'filterByRegion': false,
'customRange': 1500
};
useEffect(() => {
let state = defaultState;
try {
const val = localStorage.getItem('filters');
if (val) {
state = JSON.parse(val);
}
} catch (e) {
console.log(`Tried to load invalid filter state`);
return;
}
setShowOpenOnly(state?.showOpenOnly || defaultState.showOpenOnly);
setSelectedRegion((state?.selectedRegion && state.selectedRegion.length > 1)
? state.selectedRegion : defaultState.selectedRegion);
setFilterByRegion(state?.filterByRegion || defaultState.filterByRegion);
setCustomRange(state?.customRange || defaultState.customRange);
}, []);
const saveFilterState = () => {
localStorage.setItem('filters', JSON.stringify({
'showOpenOnly': showOpenOnly,
'selectedRegion': selectedRegion,
'filterByRegion': filterByRegion,
'customRange': customRange
}));
};
useEffect(() => {
let s = servers;
if (!filterByRegion && !selectedRegion.includes('any')) {
s = s.filter(srv => selectedRegion.includes(srv.region));
}
if (showOpenOnly) {
s = s.filter(srv => (srv?.a2s?.Players || 0) < (srv?.a2s?.MaxPlayers || 32));
}
if (filterByRegion && customRange) {
s = s.filter(srv =>
getDistance(pos, { lat: srv.latitude, lng: srv.longitude }) < customRange * 1000
);
}
setSelectedServers(s);
saveFilterState();
}, [selectedRegion, showOpenOnly, filterByRegion, customRange, setServers, servers]);
const marks = [
{
value: 500,
label: '500 km'
},
{
value: 1500,
label: '1500 km'
},
{
value: 3000,
label: '3000 km'
},
{
value: 5000,
label: '5000 km'
}
];
return <Paper className={classes.root}>
<Grid container style={{
width: '100%',
flexWrap: 'nowrap',
alignItems: 'center',
// justifyContent: 'center'
}}>
<Grid item xs={2}>
<Typography variant={'h4'} align={'center'}>Filters</Typography>
</Grid>
<Grid item xs>
<FormControlLabel
control={<Switch checked={showOpenOnly} onChange={onShowOpenOnlyChanged} name='checkedA' />}
label='Open Slots'
/>
</Grid>
<Grid item xs>
<FormControl className={classes.formControl}>
<InputLabel id='region-selector-label'>Region</InputLabel>
<Select
disabled={filterByRegion}
labelId='region-selector-label'
id='region-selector'
value={selectedRegion}
onChange={onRegionsChange}
>
{regions.map(r => {
return <MenuItem key={`region-${r}`} value={r}>{r}</MenuItem>;
})}
</Select>
</FormControl>
</Grid>
<Grid item xs>
<FormControlLabel
control={<Switch checked={filterByRegion}
onChange={onRegionsToggleEnabledChanged}
name='regionsEnabled' />}
label='By Range'
/>
</Grid>
<Grid item xs style={{ paddingRight: '2rem' }}>
<Slider
style={{ zIndex: 1000 }}
disabled={!filterByRegion}
defaultValue={1000}
aria-labelledby='custom-range'
step={100}
max={5000}
valueLabelDisplay='auto'
value={customRange}
marks={marks}
onChange={(_event, value) => {
setCustomRange(value as number);
}}
/>
</Grid>
</Grid>
</Paper>;
};
|
ljybill/rax-components
|
packages/rax-slider/src/wechat-miniprogram/index.ts
|
<filename>packages/rax-slider/src/wechat-miniprogram/index.ts
import fmtEvent from './fmtEvent';
Component({
data: {
current: 0,
children: []
},
properties: {
className: {
type: String,
},
styleSheet: {
type: String,
},
width: {
type: String,
},
height: {
type: String,
},
autoPlay: {
type: Boolean,
value: false,
},
showsPagination: {
type: Boolean,
value: true,
},
loop: {
type: Boolean,
value: false,
},
direaction: {
type: String,
value: 'horizontal',
},
index: {
type: Number,
value: 0,
},
autoPlayInterval: {
type: Number,
value: 1000,
},
paginationStyle: {
type: Object,
value: {
itemColor: 'rgba(255, 255, 255, 0.5)',
itemSelectedColor: 'rgb(255, 80, 0)',
},
},
__length: {
type: Number,
observer(newLength) {
if (this.data.children.length !== newLength) {
this.data.children.length = newLength;
this.setData({
children: this.data.children
})
}
}
}
},
options: {
multipleSlots: true
},
attached() {
this.setData({
current: this.properties.index,
});
},
observers: {
'index': function(nextIndex) {
if (this.properties.index !== nextIndex) {
this.setData({
index: nextIndex
});
}
}
},
methods: {
onChange(e) {
const event = fmtEvent(this.properties, e);
this.triggerEvent('onChange', {
index: event.detail.current
});
},
slideTo(index) {
if (index !== undefined) {
this.setData({
current: index,
});
}
},
},
});
|
ljybill/rax-components
|
packages/rax-image/src/index.tsx
|
import { createElement, useState, useCallback } from 'rax';
import { isWeex } from 'universal-env';
import { ImageProps, Source, ImageLoadEvent, ImageNativeProps } from './types';
const EMPTY_SOURCE = {} as any as Source;
interface ErrorState {
uri?: string;
}
function Image({
source,
fallbackSource,
onLoad,
onError,
style,
resizeMode,
...otherProps
}: ImageProps) {
source = source || EMPTY_SOURCE;
fallbackSource = fallbackSource || EMPTY_SOURCE;
const nativeProps: ImageNativeProps = otherProps as any;
const [errorState, setErrorState] = useState<ErrorState>({});
nativeProps.onError = useCallback(
(e: ImageLoadEvent) => {
if (errorState.uri === undefined) {
setErrorState({
uri: source.uri,
});
}
onError && onError(e);
},
[source.uri, onError, errorState]
);
nativeProps.onLoad = useCallback(
(e: ImageLoadEvent) => {
if (e.success !== null && e.success !== undefined) {
if (e.success) {
onLoad && onLoad(e);
} else {
onError && onError(e);
}
} else if (e.currentTarget != null) {
if (
e.currentTarget.naturalWidth > 1 &&
e.currentTarget.naturalHeight > 1
) {
onLoad && onLoad(e);
} else {
onError && onError(e);
}
}
},
[onLoad, onError]
);
if (errorState.uri !== undefined) {
if (errorState.uri !== source.uri) {
errorState.uri = undefined;
} else if (fallbackSource.uri != null) {
source = fallbackSource;
}
}
const { width, height, uri } = source;
nativeProps.src = uri;
nativeProps.style = {
width,
height,
...style,
};
// for cover and contain
resizeMode = resizeMode || nativeProps.style.resizeMode;
if (resizeMode) {
if (isWeex) {
nativeProps.resize = resizeMode;
nativeProps.style.resizeMode = resizeMode;
} else {
nativeProps.style.objectFit = resizeMode as any;
}
}
// Set default quality to "original" in weex avoid image be optimized unexpect
return isWeex ? (
<image quality="original" {...nativeProps} />
) : (
<img {...nativeProps} />
);
}
export default Image;
|
unicorn-talent/Podcastr
|
podcastr_next/src/components/Header/index.tsx
|
import Switch from 'react-switch';
import {IoSunnyOutline, IoMoon} from 'react-icons/io5';
import { IconContext } from "react-icons";
import format from 'date-fns/format';
import ptBR from 'date-fns/locale/pt-BR';
import { useTheme } from '../../contexts/ThemeContext';
import styles from './styles.module.scss';
export function Header(){
const currentDate = format(new Date(), 'EEEEEE, d MMMM', {
locale: ptBR,
});
const { isDark, toggleTheme } = useTheme();
return (
<header className={styles.headerContainer}>
<img src="/logo.svg" alt="Podcastr" />
<p>O melhor para você ouvir sempre</p>
<span>{currentDate}</span>
<Switch
onChange={toggleTheme}
checked={isDark}
checkedIcon={false}
uncheckedIcon={false}
checkedHandleIcon={
<div style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100%"
}}>
<IconContext.Provider value={{size: "1.5rem"}}>
<div>
<IoMoon />
</div>
</IconContext.Provider>
</div>
}
uncheckedHandleIcon={
<div style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100%"
}}>
<IconContext.Provider value={{size: "1.5rem"}}>
<div>
<IoSunnyOutline />
</div>
</IconContext.Provider>
</div>
}
offColor="#e8e5f0"
onColor="#312f3b"
handleDiameter={22}
height={10}
width={32}
/>
</header>
);
}
|
unicorn-talent/Podcastr
|
podcastr_next/src/contexts/ThemeContext.tsx
|
import { createContext, ReactNode, useContext, useState } from 'react';
type ThemeContextData = {
isDark: boolean;
toggleTheme: () => void;
}
export const ThemeContext = createContext( {} as ThemeContextData );
type ThemeContextProviderProps ={
children: ReactNode;
}
export function ThemeContextProvider({ children }: ThemeContextProviderProps){
const [isDark, setIsDark] = useState(false);
function toggleTheme(){
setIsDark(!isDark);
}
return (
<ThemeContext.Provider value={{isDark, toggleTheme}}>
{children}
</ThemeContext.Provider>
);
}
export const useTheme = () => {
return useContext(ThemeContext);
}
|
mnecchi/eufy-robovac
|
src/RoboVac.ts
|
import TuyAPI from 'tuyapi';
import { STATUS_DPS } from './types';
export default async (deviceId: string, localKey: string) => {
let isConnected = false;
const api = new TuyAPI({ id: deviceId, key: localKey });
api.on('connected', () => { isConnected = true });
api.on('disconnected', () => { isConnected = false });
const connect = async () => {
if (!api.device.id || !api.device.ip) {
await api.find();
}
if (!isConnected) {
await api.connect();
}
}
const disconnect = () => api.disconnect();
const get = async () => {
await connect();
return api.get({ schema: true });
};
return {
get,
disconnect
};
};
|
mnecchi/eufy-robovac
|
src/types.ts
|
export enum STATUS_DPS {
DEFAULT = '1',
PLAY_PAUSE = '2',
DIRECTION = '3',
WORK_MODE = '5',
WORK_STATUS = '15',
GO_HOME = '101',
CLEAN_SPEED = '102',
FIND_ROBOT = '103',
BATTERY_LEVEL = '104',
ERROR_CODE = '106'
}
export enum WorkStatus {
// Cleaning
RUNNING = 'Running',
// In the dock, charging
CHARGING = 'Charging',
// Not in the dock, paused
STAND_BY = 'standby',
// Not in the dock - goes into this state after being paused for a while
SLEEPING = 'Sleeping',
// Going home because battery is depleted
RECHARGE_NEEDED = 'Recharge',
// In the dock, full charged
COMPLETED = 'completed'
}
export enum WorkMode {
AUTO = 'auto',
NO_SWEEP = 'Nosweep',
SMALL_ROOM = 'SmallRoom',
EDGE = 'Edge',
SPOT = 'Spot'
}
export interface StatusResponse {
devId: string;
dps: {
[STATUS_DPS.DEFAULT]: boolean;
[STATUS_DPS.PLAY_PAUSE]: boolean;
[STATUS_DPS.DIRECTION]: string;
[STATUS_DPS.WORK_MODE]: WorkMode;
[STATUS_DPS.WORK_STATUS]: WorkStatus;
[STATUS_DPS.GO_HOME]: boolean;
[STATUS_DPS.CLEAN_SPEED]: string;
[STATUS_DPS.FIND_ROBOT]: boolean;
[STATUS_DPS.BATTERY_LEVEL]: number;
[STATUS_DPS.ERROR_CODE]: string;
}
}
|
mnecchi/eufy-robovac
|
src/index.ts
|
import dotenv from 'dotenv';
import RoboVac from './RoboVac';
import { WorkMode } from './types';
import { RSA_NO_PADDING } from 'constants';
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
dotenv.config();
const { deviceId, localKey } = process.env;
(async () => {
const robovac = await RoboVac(deviceId, localKey);
const status = await robovac.get();
console.log(status);
robovac.disconnect();
// await robovac.find();
// await robovac.connect();
// const status = await robovac.get();
// console.log(status);
// robovac.disconnect();
})();
// (async () => {
// const robovac = new RoboVac({ deviceId, localKey });
// await robovac.startCleaning(true);
// await sleep(5000);
// await robovac.goHome();
// robovac.disconnect();
// })();
|
Keeper-Security/secrets-manager
|
sdk/javascript/packages/core/src/keeper.ts
|
<gh_stars>1-10
import {KeeperHttpResponse, KeyValueStorage, TransmissionKey, EncryptedPayload, platform} from './platform'
import {webSafe64FromBytes, webSafe64ToBytes} from './utils'
export {KeyValueStorage} from './platform'
let packageVersion = '[VI]{version}[/VI]'
const KEY_HOSTNAME = 'hostname' // base url for the Secrets Manager service
const KEY_SERVER_PUBIC_KEY_ID = 'serverPublicKeyId'
const KEY_CLIENT_ID = 'clientId'
const KEY_CLIENT_KEY = 'clientKey' // The key that is used to identify the client before public key
const KEY_APP_KEY = 'appKey' // The application key with which all secrets are encrypted
const KEY_OWNER_PUBLIC_KEY = 'appOwnerPublicKey' // The application owner public key, to create records
const KEY_PRIVATE_KEY = 'privateKey' // The client's private key
const CLIENT_ID_HASH_TAG = 'KEEPER_SECRETS_MANAGER_CLIENT_ID' // Tag for hashing the client key to client id
let keeperPublicKeys: Record<number, Uint8Array>
export const initialize = (pkgVersion?: string) => {
if (pkgVersion) {
packageVersion = pkgVersion
}
let keyNumber = 7
keeperPublicKeys = [
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>'
].reduce((keys, key) => {
keys[keyNumber++] = webSafe64ToBytes(key)
return keys
}, {})
}
export type SecretManagerOptions = {
storage: KeyValueStorage
queryFunction?: (url: string, transmissionKey: TransmissionKey, payload: EncryptedPayload, allowUnverifiedCertificate?: boolean) => Promise<KeeperHttpResponse>
allowUnverifiedCertificate?: boolean;
}
type GetPayload = {
clientVersion: string
clientId: string
publicKey?: string // passed once when binding
requestedRecords?: string[] // only return these records
}
type UpdatePayload = {
clientVersion: string
clientId: string
recordUid: string
data: string
revision?: number
}
type CreatePayload = {
clientVersion: string
clientId: string
recordUid: string
recordKey: string
folderUid: string
folderKey: string
data: string
}
type FileUploadPayload = {
clientVersion: string
clientId: string
fileRecordUid: string
fileRecordKey: string
fileRecordData: string
ownerRecordUid: string
ownerRecordData: string
linkKey: string
fileSize: number
}
type SecretsManagerResponseFolder = {
folderUid: string
folderKey: string
records: SecretsManagerResponseRecord[]
}
type SecretsManagerResponseRecord = {
recordUid: string
recordKey: string
data: string
revision: number
files: SecretsManagerResponseFile[]
}
type SecretsManagerResponseFile = {
fileUid: string
fileKey: string
data: string
url: string
thumbnailUrl: string
}
type SecretsManagerResponse = {
appData: string
encryptedAppKey?: string // received only on the first response
appOwnerPublicKey?: string // received only on the first response
folders: SecretsManagerResponseFolder[]
records: SecretsManagerResponseRecord[]
expiresOn: number
warnings: string[]
}
type SecretsManagerAddFileResponse = {
url: string
parameters: string
successStatusCode: number
}
export type KeeperSecrets = {
appData: {
title: string
type: string
}
expiresOn?: Date
records: KeeperRecord[]
warnings?: string[]
}
export type KeeperRecord = {
recordUid: string
folderUid?: string
data: any
revision?: number
files?: KeeperFile[]
}
export type KeeperFile = {
fileUid: string
data: any
url?: string
thumbnailUrl?: string
}
export type KeeperFileUpload = {
name: string
title: string
type?: string
data: Uint8Array
}
type KeeperError = {
error?: string
key_id?: number
}
const prepareGetPayload = async (storage: KeyValueStorage, recordsFilter?: string[]): Promise<GetPayload> => {
const clientId = await storage.getString(KEY_CLIENT_ID)
if (!clientId) {
throw new Error('Client Id is missing from the configuration')
}
const payload: GetPayload = {
clientVersion: 'ms' + packageVersion,
clientId: clientId
}
const appKey = await storage.getBytes(KEY_APP_KEY)
if (!appKey) {
const publicKey = await platform.exportPublicKey(KEY_PRIVATE_KEY, storage)
payload.publicKey = platform.bytesToBase64(publicKey)
}
if (recordsFilter) {
payload.requestedRecords = recordsFilter
}
return payload
}
const prepareUpdatePayload = async (storage: KeyValueStorage, record: KeeperRecord): Promise<UpdatePayload> => {
const clientId = await storage.getString(KEY_CLIENT_ID)
if (!clientId) {
throw new Error('Client Id is missing from the configuration')
}
const recordBytes = platform.stringToBytes(JSON.stringify(record.data))
const encryptedRecord = await platform.encrypt(recordBytes, record.recordUid)
return {
clientVersion: 'ms' + packageVersion,
clientId: clientId,
recordUid: record.recordUid,
data: webSafe64FromBytes(encryptedRecord),
revision: record.revision
}
}
const prepareCreatePayload = async (storage: KeyValueStorage, folderUid: string, recordData: any): Promise<CreatePayload> => {
const clientId = await storage.getString(KEY_CLIENT_ID)
if (!clientId) {
throw new Error('Client Id is missing from the configuration')
}
const ownerPublicKey = await storage.getBytes(KEY_OWNER_PUBLIC_KEY)
if (!ownerPublicKey) {
throw new Error('Application owner public key is missing from the configuration')
}
const recordBytes = platform.stringToBytes(JSON.stringify(recordData))
const recordKey = platform.getRandomBytes(32)
const recordUid = platform.getRandomBytes(16)
const encryptedRecord = await platform.encryptWithKey(recordBytes, recordKey)
const encryptedRecordKey = await platform.publicEncrypt(recordKey, ownerPublicKey)
const encryptedFolderKey = await platform.encrypt(recordKey, folderUid)
return {
clientVersion: 'ms' + packageVersion,
clientId: clientId,
recordUid: webSafe64FromBytes(recordUid),
recordKey: platform.bytesToBase64(encryptedRecordKey),
folderUid: folderUid,
folderKey: platform.bytesToBase64(encryptedFolderKey),
data: webSafe64FromBytes(encryptedRecord)
}
}
const prepareFileUploadPayload = async (storage: KeyValueStorage, ownerRecord: KeeperRecord, file: KeeperFileUpload): Promise<{
payload: FileUploadPayload,
encryptedFileData: Uint8Array
}> => {
const clientId = await storage.getString(KEY_CLIENT_ID)
if (!clientId) {
throw new Error('Client Id is missing from the configuration')
}
const ownerPublicKey = await storage.getBytes(KEY_OWNER_PUBLIC_KEY)
if (!ownerPublicKey) {
throw new Error('Application owner public key is missing from the configuration')
}
const fileData = {
name: file.name,
size: file.data.length,
title: file.title,
lastModified: new Date().getTime(),
type: file.type
}
const fileRecordBytes = platform.stringToBytes(JSON.stringify(fileData))
const fileRecordKey = platform.getRandomBytes(32)
const fileRecordUid = webSafe64FromBytes(platform.getRandomBytes(16))
const encryptedFileRecord = await platform.encryptWithKey(fileRecordBytes, fileRecordKey)
const encryptedFileRecordKey = await platform.publicEncrypt(fileRecordKey, ownerPublicKey)
const encryptedLinkKey = await platform.encrypt(fileRecordKey, ownerRecord.recordUid)
const encryptedFileData = await platform.encryptWithKey(file.data, fileRecordKey)
let fileRef = ownerRecord.data.fields.find(x => x.type == 'fileRef')
if (fileRef) {
fileRef.value.push(fileRecordUid)
} else {
fileRef = {type: 'fileRef', value: [fileRecordUid]}
ownerRecord.data.fields.push(fileRef)
}
const ownerRecordBytes = platform.stringToBytes(JSON.stringify(ownerRecord.data))
const encryptedOwnerRecord = await platform.encrypt(ownerRecordBytes, ownerRecord.recordUid)
return {
payload: {
clientVersion: 'ms' + packageVersion,
clientId: clientId,
fileRecordUid: fileRecordUid,
fileRecordKey: platform.bytesToBase64(encryptedFileRecordKey),
fileRecordData: webSafe64FromBytes(encryptedFileRecord),
ownerRecordUid: ownerRecord.recordUid,
ownerRecordData: webSafe64FromBytes(encryptedOwnerRecord),
linkKey: platform.bytesToBase64(encryptedLinkKey),
fileSize: encryptedFileData.length
},
encryptedFileData
}
}
const postFunction = async (url: string, transmissionKey: TransmissionKey, payload: EncryptedPayload, allowUnverifiedCertificate?: boolean): Promise<KeeperHttpResponse> => {
return platform.post(url, payload.payload,
{
PublicKeyId: transmissionKey.publicKeyId.toString(),
TransmissionKey: platform.bytesToBase64(transmissionKey.encryptedKey),
Authorization: `Signature ${platform.bytesToBase64(payload.signature)}`
}, allowUnverifiedCertificate)
}
export const generateTransmissionKey = async (storage: KeyValueStorage): Promise<TransmissionKey> => {
const transmissionKey = platform.getRandomBytes(32)
const keyNumberString = await storage.getString(KEY_SERVER_PUBIC_KEY_ID)
const keyNumber = keyNumberString ? Number(keyNumberString) : 7
const keeperPublicKey = keeperPublicKeys[keyNumber]
if (!keeperPublicKey) {
throw new Error(`Key number ${keyNumber} is not supported`)
}
const encryptedKey = await platform.publicEncrypt(transmissionKey, keeperPublicKeys[keyNumber])
return {
publicKeyId: keyNumber,
key: transmissionKey,
encryptedKey: encryptedKey
}
}
const encryptAndSignPayload = async (storage: KeyValueStorage, transmissionKey: TransmissionKey, payload: GetPayload | UpdatePayload | FileUploadPayload): Promise<EncryptedPayload> => {
const payloadBytes = platform.stringToBytes(JSON.stringify(payload))
const encryptedPayload = await platform.encryptWithKey(payloadBytes, transmissionKey.key)
const signatureBase = Uint8Array.of(...transmissionKey.encryptedKey, ...encryptedPayload)
const signature = await platform.sign(signatureBase, KEY_PRIVATE_KEY, storage)
return {payload: encryptedPayload, signature}
}
const postQuery = async (options: SecretManagerOptions, path: string, payload: GetPayload | UpdatePayload | FileUploadPayload): Promise<Uint8Array> => {
const hostName = await options.storage.getString(KEY_HOSTNAME)
if (!hostName) {
throw new Error('hostname is missing from the configuration')
}
const url = `https://${hostName}/api/rest/sm/v1/${path}`
while (true) {
const transmissionKey = await generateTransmissionKey(options.storage)
const encryptedPayload = await encryptAndSignPayload(options.storage, transmissionKey, payload)
const response = await (options.queryFunction || postFunction)(url, transmissionKey, encryptedPayload, options.allowUnverifiedCertificate)
if (response.statusCode !== 200) {
let errorMessage
if (response.data) {
errorMessage = platform.bytesToString(response.data.slice(0, 1000))
try {
const errorObj: KeeperError = JSON.parse(errorMessage)
if (errorObj.error === 'key') {
await options.storage.saveString(KEY_SERVER_PUBIC_KEY_ID, errorObj.key_id!.toString())
continue
}
} catch {
}
} else {
errorMessage = `unknown ksm error, code ${response.statusCode}`
}
throw new Error(errorMessage)
}
return response.data
? platform.decryptWithKey(response.data, transmissionKey.key)
: new Uint8Array()
}
}
const decryptRecord = async (record: SecretsManagerResponseRecord, storage?: KeyValueStorage): Promise<KeeperRecord> => {
const decryptedRecord = await platform.decrypt(platform.base64ToBytes(record.data), record.recordUid || KEY_APP_KEY, storage)
const keeperRecord: KeeperRecord = {
recordUid: record.recordUid,
data: JSON.parse(platform.bytesToString(decryptedRecord)),
revision: record.revision
}
if (record.files) {
keeperRecord.files = []
for (const file of record.files) {
await platform.unwrap(platform.base64ToBytes(file.fileKey), file.fileUid, record.recordUid || KEY_APP_KEY)
const decryptedFile = await platform.decrypt(platform.base64ToBytes(file.data), file.fileUid)
keeperRecord.files.push({
fileUid: file.fileUid,
data: JSON.parse(platform.bytesToString(decryptedFile)),
url: file.url,
thumbnailUrl: file.thumbnailUrl
})
}
}
return keeperRecord
}
const fetchAndDecryptSecrets = async (options: SecretManagerOptions, recordsFilter?: string[]): Promise<{ secrets: KeeperSecrets, justBound: boolean }> => {
const storage = options.storage
const payload = await prepareGetPayload(storage, recordsFilter)
const responseData = await postQuery(options, 'get_secret', payload)
const response = JSON.parse(platform.bytesToString(responseData)) as SecretsManagerResponse
const records: KeeperRecord[] = []
let justBound = false
if (response.encryptedAppKey) {
justBound = true
await platform.unwrap(platform.base64ToBytes(response.encryptedAppKey), KEY_APP_KEY, KEY_CLIENT_KEY, storage)
await storage.delete(KEY_CLIENT_KEY)
await storage.saveString(KEY_OWNER_PUBLIC_KEY, response.appOwnerPublicKey!)
}
if (response.records) {
for (const record of response.records) {
if (record.recordKey) {
await platform.unwrap(platform.base64ToBytes(record.recordKey), record.recordUid, KEY_APP_KEY, storage, true)
}
const decryptedRecord = await decryptRecord(record, storage)
records.push(decryptedRecord)
}
}
if (response.folders) {
for (const folder of response.folders) {
await platform.unwrap(platform.base64ToBytes(folder.folderKey), folder.folderUid, KEY_APP_KEY, storage, true)
for (const record of folder.records) {
await platform.unwrap(platform.base64ToBytes(record.recordKey), record.recordUid, folder.folderUid)
const decryptedRecord = await decryptRecord(record)
decryptedRecord.folderUid = folder.folderUid
records.push(decryptedRecord)
}
}
}
let appData
if (response.appData) {
appData = JSON.parse(platform.bytesToString(await platform.decrypt(webSafe64ToBytes(response.appData), KEY_APP_KEY)))
}
const secrets: KeeperSecrets = {
appData: appData,
expiresOn: response.expiresOn > 0 ? new Date(response.expiresOn) : undefined,
records: records
}
if (response.warnings && response.warnings.length > 0) {
secrets.warnings = response.warnings
}
return {secrets, justBound}
}
export const getClientId = async (clientKey: string): Promise<string> => {
const clientKeyHash = await platform.hash(webSafe64ToBytes(clientKey), CLIENT_ID_HASH_TAG)
return platform.bytesToBase64(clientKeyHash)
}
export const initializeStorage = async (storage: KeyValueStorage, oneTimeToken: string, hostName?: string | 'keepersecurity.com' | 'keepersecurity.eu' | 'keepersecurity.au') => {
const tokenParts = oneTimeToken.split(':')
let host, clientKey
if (tokenParts.length === 1) {
if (!hostName) {
throw new Error('The hostname must be present in the token or as a parameter')
}
host = hostName
clientKey = oneTimeToken
} else {
host = {
US: 'keepersecurity.com',
EU: 'keepersecurity.eu',
AU: 'keepersecurity.com.au',
GOV: 'govcloud.keepersecurity.us'
}[tokenParts[0].toUpperCase()]
if (!host) {
host = tokenParts[0]
}
clientKey = tokenParts[1]
}
const clientKeyBytes = webSafe64ToBytes(clientKey)
const clientKeyHash = await platform.hash(clientKeyBytes, CLIENT_ID_HASH_TAG)
const clientId = platform.bytesToBase64(clientKeyHash)
const existingClientId = await storage.getString(KEY_CLIENT_ID)
if (existingClientId) {
if (existingClientId === clientId) {
return // the storage is already initialized
}
throw new Error(`The storage is already initialized with a different client Id (${existingClientId})`)
}
await storage.saveString(KEY_HOSTNAME, host)
await storage.saveString(KEY_CLIENT_ID, clientId)
await platform.importKey(KEY_CLIENT_KEY, clientKeyBytes, storage)
await platform.generatePrivateKey(KEY_PRIVATE_KEY, storage)
}
export const getSecrets = async (options: SecretManagerOptions, recordsFilter?: string[]): Promise<KeeperSecrets> => {
platform.cleanKeyCache()
const {secrets, justBound} = await fetchAndDecryptSecrets(options, recordsFilter)
if (justBound) {
try {
await fetchAndDecryptSecrets(options, recordsFilter)
} catch (e) {
console.error(e)
}
}
return secrets
}
export const findSecretsByTitle = async (records: KeeperRecord[], recordTitle: string): Promise<KeeperRecord[]> => {
return records.filter(record => record.data.title === recordTitle)
}
export const findSecretByTitle = async (records: KeeperRecord[], recordTitle: string): Promise<KeeperRecord | undefined> => {
return records.find(record => record.data.title === recordTitle)
}
export const getSecretsByTitle = async (options: SecretManagerOptions, recordTitle: string): Promise<KeeperRecord[]> => {
const secrets = await getSecrets(options)
return secrets.records.filter(record => record.data.title === recordTitle)
}
export const getSecretByTitle = async (options: SecretManagerOptions, recordTitle: string): Promise<KeeperRecord | undefined> => {
const secrets = await getSecrets(options)
return secrets.records.find(record => record.data.title === recordTitle)
}
export const updateSecret = async (options: SecretManagerOptions, record: KeeperRecord): Promise<void> => {
const payload = await prepareUpdatePayload(options.storage, record)
await postQuery(options, 'update_secret', payload)
}
export const createSecret = async (options: SecretManagerOptions, folderUid: string, recordData: any): Promise<string> => {
if (!platform.hasKeysCached()) {
await getSecrets(options) // need to warm up keys cache before posting a record
}
const payload = await prepareCreatePayload(options.storage, folderUid, recordData)
await postQuery(options, 'create_secret', payload)
return payload.recordUid
}
export const downloadFile = async (file: KeeperFile): Promise<Uint8Array> => {
const fileResponse = await platform.get(file.url!, {})
return platform.decrypt(fileResponse.data, file.fileUid)
}
export const downloadThumbnail = async (file: KeeperFile): Promise<Uint8Array> => {
const fileResponse = await platform.get(file.thumbnailUrl!, {})
return platform.decrypt(fileResponse.data, file.fileUid)
}
export const uploadFile = async (options: SecretManagerOptions, ownerRecord: KeeperRecord, file: KeeperFileUpload): Promise<string> => {
const { payload, encryptedFileData } = await prepareFileUploadPayload(options.storage, ownerRecord, file)
const responseData = await postQuery(options, 'add_file', payload)
const response = JSON.parse(platform.bytesToString(responseData)) as SecretsManagerAddFileResponse
const uploadResult = await platform.fileUpload(response.url, JSON.parse(response.parameters), encryptedFileData)
if (uploadResult.statusCode !== response.successStatusCode) {
throw new Error(`Upload failed (${uploadResult.statusMessage}), code ${uploadResult.statusCode}`)
}
return payload.fileRecordUid
}
|
Keeper-Security/secrets-manager
|
sdk/javascript/packages/core/src/utils.ts
|
import {platform} from './platform'
export const webSafe64 = (source: string): string => source.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
export const webSafe64ToRegular = (source: string): string => source.replace(/-/g, '+').replace(/_/g, '/') + '=='.substring(0, (3 * source.length) % 4);
export const webSafe64ToBytes = (source: string): Uint8Array => platform.base64ToBytes(webSafe64ToRegular(source));
export const webSafe64FromBytes = (source: Uint8Array): string => webSafe64(platform.bytesToBase64(source));
// extracts public raw from private key for prime256v1 curve in der/pkcs8
// privateKey: key.slice(36, 68)
export const privateDerToPublicRaw = (key: Uint8Array): Uint8Array => key.slice(-65)
const b32encode = (base32Text: string): Uint8Array => {
/* encodes a string s to base32 and returns the encoded string */
const alphabet: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
// private static readonly Regex rxBase32Alphabet = new Regex($"", RegexOptions.Compiled);
// The padding specified in RFC 3548 section 2.2 is not required and should be omitted.
const base32: string = (base32Text || '').replace(/=+$/g, '').toUpperCase();
if (!base32 || !/^[A-Z2-7]+$/.test(base32))
return new Uint8Array();
const bytes = Array.from(base32)
let output = new Array()
for (let bitIndex = 0; bitIndex < base32.length * 5; bitIndex += 8) {
const idx = Math.floor(bitIndex / 5);
let dualByte = alphabet.indexOf(bytes[idx]) << 10;
if (idx + 1 < bytes.length)
dualByte |= alphabet.indexOf(bytes[idx + 1]) << 5;
if (idx + 2 < bytes.length)
dualByte |= alphabet.indexOf(bytes[idx + 2]);
dualByte = 0xff & (dualByte >> (15 - bitIndex % 5 - 8));
output.push(dualByte);
}
return new Uint8Array(output);
}
export const getTotpCode = async (url: string, unixTimeSeconds: number = 0) : Promise<{ code: string; timeLeft: number; period: number; } | null> => {
let totpUrl: URL;
try {
totpUrl = new URL(url);
} catch (e) {
return null;
}
if (totpUrl.protocol != 'otpauth:')
return null;
const secret: string = (totpUrl.searchParams.get('secret') || '').trim();
if (!secret)
return null;
let algorithm: string = (totpUrl.searchParams.get('algorithm') || '').trim();
if (!algorithm)
algorithm = 'SHA1'; // default algorithm
const strDigits: string = (totpUrl.searchParams.get('digits') || '').trim();
let digits: number = ((isNaN(+strDigits) || !Boolean(strDigits)) ? 6 : parseInt(strDigits));
digits = digits == 0 ? 6 : digits;
const strPeriod: string = (totpUrl.searchParams.get('period') || '').trim();
let period: number = ((isNaN(+strPeriod) || !Boolean(strPeriod)) ? 30 : parseInt(strPeriod));
period = period == 0 ? 30 : period;
const tmBase: number = unixTimeSeconds != 0 ? unixTimeSeconds : Math.floor(Date.now() / 1000);
const tm: bigint = BigInt(Math.floor(tmBase / period));
const buffer = new ArrayBuffer(8)
new DataView(buffer).setBigInt64(0, tm);
const msg = new Uint8Array(buffer)
const secretBytes = b32encode(secret.toUpperCase());
if (secretBytes == null || secretBytes.length < 1)
return null;
const digest = await platform.getHmacDigest(algorithm, secretBytes, msg);
if (digest.length < 1)
return null;
const offset = digest[digest.length - 1] & 0x0f;
const codeBytes = new Uint8Array(digest.slice(offset, offset+4));
codeBytes[0] &= 0x7f;
let codeInt = new DataView(codeBytes.buffer).getInt32(0);
codeInt %= Math.floor(Math.pow(10, digits));
codeInt = Math.floor(codeInt);
let codeStr = codeInt.toString(10);
while (codeStr.length < digits)
codeStr = "0" + codeStr;
const elapsed = Math.floor(tmBase % period); // time elapsed in current period in seconds
const ttl = period - elapsed; // time to live in seconds
return { code: codeStr, timeLeft: ttl, period: period };
}
export const generatePassword = async (length: number = 64, lowercase: number = 0, uppercase: number = 0, digits: number = 0, specialCharacters: number = 0) : Promise<string> => {
const asciiLowercase = 'abcdefghijklmnopqrstuvwxyz'
const asciiUppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
const asciiDigits = '0123456789'
const asciiSpecialCharacters = '"!@#$%()+;<>=?[]{}^.,'
length = (typeof length === 'number' && length > 0) ? length : 64
lowercase = (typeof lowercase === 'number' && lowercase > 0) ? lowercase : 0
uppercase = (typeof uppercase === 'number' && uppercase > 0) ? uppercase : 0
digits = (typeof digits === 'number' && digits > 0) ? digits : 0
specialCharacters = (typeof specialCharacters === 'number' && specialCharacters > 0) ? specialCharacters : 0
if (lowercase == 0 && uppercase == 0 && digits == 0 && specialCharacters == 0) {
const increment = length / 4
const lastIncrement = increment + length % 4
lowercase = uppercase = digits = increment
specialCharacters = lastIncrement
}
let result = ''
for (let i = 0; i < lowercase; i++)
result += await platform.getRandomCharacterInCharset(asciiLowercase)
for (let i = 0; i < uppercase; i++)
result += await platform.getRandomCharacterInCharset(asciiUppercase)
for (let i = 0; i < digits; i++)
result += await platform.getRandomCharacterInCharset(asciiDigits)
for (let i = 0; i < specialCharacters; i++)
result += await platform.getRandomCharacterInCharset(asciiSpecialCharacters)
// Fisher-Yates shuffle
if (result.length > 1) {
let a = result.split('')
for (let i = a.length - 1; i > 0; i--) {
const j = await platform.getRandomNumber(i+1) // 0 <= j <= i
if (i != j) {
const tmp = a[i]
a[i] = a[j]
a[j] = tmp
}
}
result = a.join('')
}
return result
}
|
Keeper-Security/secrets-manager
|
sdk/javascript/packages/core/test/keeper.test.ts
|
import {
KeeperHttpResponse,
getSecrets,
initializeStorage,
platform,
localConfigStorage, SecretManagerOptions, inMemoryStorage, loadJsonConfig, getTotpCode, generatePassword
} from '../'
import * as fs from 'fs'
test('Get secrets e2e', async () => {
const responses: { transmissionKey: string, data: string, statusCode: number } [] = JSON.parse(fs.readFileSync('../../../fake_data.json').toString())
let responseNo = 0
const getRandomBytesStub = (): Uint8Array => platform.base64ToBytes(responses[responseNo].transmissionKey)
const postStub = (): Promise<KeeperHttpResponse> => {
const response = responses[responseNo++]
return Promise.resolve({
data: platform.base64ToBytes(response.data),
statusCode: response.statusCode,
headers: []
})
}
platform.getRandomBytes = getRandomBytesStub
platform.post = postStub
const kvs = localConfigStorage()
const fakeOneTimeCode = 'VB3sGkzVyRB9Lup6WE7Rx-ETFZxyWR2zqY2b9f2zwBo'
await initializeStorage(kvs, fakeOneTimeCode, 'fake.keepersecurity.com')
const options: SecretManagerOptions = {
storage: kvs,
queryFunction: postStub
}
const secrets = await getSecrets(options)
expect(secrets.records[1].data.fields[1].value[0]).toBe('N$B!lkoOrVL1RUNDBvn2')
try {
await getSecrets(options)
fail('Did not throw')
} catch ({message}) {
expect(JSON.parse(message as string).message).toBe('Signature is invalid')
}
})
test('Storage prefixes', async () => {
let storage = inMemoryStorage({})
await initializeStorage(storage, 'US:ONE_TIME_TOKEN')
expect(await storage.getString('hostname')).toBe('keepersecurity.com')
storage = inMemoryStorage({})
await initializeStorage(storage, 'EU:ONE_TIME_TOKEN')
expect(await storage.getString('hostname')).toBe('keepersecurity.eu')
storage = inMemoryStorage({})
await initializeStorage(storage, 'AU:ONE_TIME_TOKEN')
expect(await storage.getString('hostname')).toBe('keepersecurity.com.au')
storage = inMemoryStorage({})
await initializeStorage(storage, 'eu:ONE_TIME_TOKEN')
expect(await storage.getString('hostname')).toBe('keepersecurity.eu')
storage = inMemoryStorage({})
await initializeStorage(storage, 'fake.keepersecurity.com:ONE_TIME_TOKEN')
expect(await storage.getString('hostname')).toBe('fake.keepersecurity.com')
})
test('Storage base64', async () => {
const base64Config = '<KEY>' +
<KEY>' +
<KEY>'
let storage = loadJsonConfig(base64Config)
expect(await storage.getString('hostname')).toBe('fake.keepersecurity.com')
const jsonConfig = '{"hostname": "fake.keepersecurity.com"}'
storage = loadJsonConfig(jsonConfig)
expect(await storage.getString('hostname')).toBe('fake.keepersecurity.com')
})
test('TOTP', async () => {
// test default algorithm
// {Algorithm: "", Period: 30, UnixTime: 20000000000, Secret: "12345678901234567890", Digits: 8}, Output: "65353130"}
let url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=ACME&algorithm=&digits=8&period=30'
let totp = await getTotpCode(url, 20000000000)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('65353130') // using default algorithm SHA1
// test default digits
// { Algorithm: "SHA1", Period: 30, UnixTime: 20000000000, Secret: "12345678901234567890", Digits: 0}, Output: "353130"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=ACME&algorithm=SHA1&digits=0&period=30'
totp = await getTotpCode(url, 20000000000)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('353130') // using default digits = 6
// test default period
// {Algorithm: "SHA1", Period: 0, UnixTime: 20000000000, Secret: "12345678901234567890", Digits: 8}, Output: "65353130"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=ACME&algorithm=SHA1&digits=8&period=0'
totp = await getTotpCode(url, 20000000000)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('65353130') // using default period = 30
// test empty secret
// {Algorithm: "SHA1", Period: 30, UnixTime: 0, Secret: "", Digits: 8}, Output: "no secret key provided"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=&issuer=ACME&algorithm=SHA1&digits=8&period=30'
totp = await getTotpCode(url)
expect(totp).toBeNull() // Empty secret shouldn't produce valid TOTP
// test invalid algorithm
// { Algorithm: "SHA1024", Period: 30, UnixTime: 0, Secret: "12345678901234567890", Digits: 8}, Output: "invalid algorithm - use one of SHA1/SHA256/SHA512"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=ACME&algorithm=SHA1024&digits=8&period=30'
totp = await getTotpCode(url)
expect(totp).toBeNull() // SHA1024 is unsupported algorithm for TOTP
// test invalid secret
// { Algorithm: "SHA1", Period: 30, UnixTime: 0, Secret: "1NVAL1D", Digits: 8}, Output: "bad secret key"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=1NVAL1D&issuer=ACME&algorithm=SHA1&digits=8&period=30'
totp = await getTotpCode(url)
expect(totp).toBeNull() // Invalid secret shouldn't produce valid TOTP
// Check seconds passed
// {Algorithm: "SHA1", Period: 30, UnixTime: 59, Secret: "12345678901234567890", Digits: 8}, Output: "94287082"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=ACME&algorithm=SHA1&digits=8&period=30'
totp = await getTotpCode(url, 59)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('94287082')
expect(totp!.timeLeft).toBe(1)
// {Algorithm: "SHA256", Period: 30, UnixTime: 59, Secret: "12345678901234567890123456789012", Digits: 8}, Output: "46119246"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA&issuer=ACME&algorithm=SHA256&digits=8&period=30'
totp = await getTotpCode(url, 59)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('46119246')
expect(totp!.timeLeft).toBe(1)
// {Algorithm: "SHA512", Period: 30, UnixTime: 59, Secret: "1234567890123456789012345678901234567890123456789012345678901234", Digits: 8}, Output: "90693936"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNA=&issuer=ACME&algorithm=SHA512&digits=8&period=30'
totp = await getTotpCode(url, 59)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('90693936')
expect(totp!.timeLeft).toBe(1)
// Check different periods - 1 sec. before split
// {Algorithm: "SHA1", Period: 30, UnixTime: 1111111109, Secret: "12345678901234567890", Digits: 8}, Output: "07081804"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=ACME&algorithm=SHA1&digits=8&period=30'
totp = await getTotpCode(url, 1111111109)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('07081804')
// {Algorithm: "SHA256", Period: 30, UnixTime: 1111111109, Secret: "12345678901234567890123456789012", Digits: 8}, Output: "68084774"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA&issuer=ACME&algorithm=SHA256&digits=8&period=30'
totp = await getTotpCode(url, 1111111109)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('68084774')
// {Algorithm: "SHA512", Period: 30, UnixTime: 1111111109, Secret: "1234567890123456789012345678901234567890123456789012345678901234", Digits: 8}, Output: "25091201"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNA=&issuer=ACME&algorithm=SHA512&digits=8&period=30'
totp = await getTotpCode(url, 1111111109)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('25091201')
// Check different periods - 1 sec. after split
// {Algorithm: "SHA1", Period: 30, UnixTime: 1111111111, Secret: "12345678901234567890", Digits: 8}, Output: "14050471"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=ACME&algorithm=SHA1&digits=8&period=30'
totp = await getTotpCode(url, 1111111111)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('14050471')
// {Algorithm: "SHA256", Period: 30, UnixTime: 1111111111, Secret: "12345678901234567890123456789012", Digits: 8}, Output: "67062674"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA&issuer=ACME&algorithm=SHA256&digits=8&period=30'
totp = await getTotpCode(url, 1111111111)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('67062674')
// {Algorithm: "SHA512", Period: 30, UnixTime: 1111111111, Secret: "1234567890123456789012345678901234567890123456789012345678901234", Digits: 8}, Output: "99943326"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNA=&issuer=ACME&algorithm=SHA512&digits=8&period=30'
totp = await getTotpCode(url, 1111111111)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('99943326')
// Check different time periods
// {Algorithm: "SHA1", Period: 30, UnixTime: 1234567890, Secret: "12345678901234567890", Digits: 8}, Output: "89005924"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=ACME&algorithm=SHA1&digits=8&period=30'
totp = await getTotpCode(url, 1234567890)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('89005924')
// {Algorithm: "SHA256", Period: 30, UnixTime: 1234567890, Secret: "12345678901234567890123456789012", Digits: 8}, Output: "91819424"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA&issuer=ACME&algorithm=SHA256&digits=8&period=30'
totp = await getTotpCode(url, 1234567890)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('91819424')
// {Algorithm: "SHA512", Period: 30, UnixTime: 1234567890, Secret: "1234567890123456789012345678901234567890123456789012345678901234", Digits: 8}, Output: "93441116"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNA=&issuer=ACME&algorithm=SHA512&digits=8&period=30'
totp = await getTotpCode(url, 1234567890)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('93441116')
// {Algorithm: "SHA1", Period: 30, UnixTime: 2000000000, Secret: "12345678901234567890", Digits: 8}, Output: "69279037"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=ACME&algorithm=SHA1&digits=8&period=30'
totp = await getTotpCode(url, 2000000000)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('69279037')
// {Algorithm: "SHA256", Period: 30, UnixTime: 2000000000, Secret: "12345678901234567890123456789012", Digits: 8}, Output: "90698825"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA&issuer=ACME&algorithm=SHA256&digits=8&period=30'
totp = await getTotpCode(url, 2000000000)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('90698825')
// {Algorithm: "SHA512", Period: 30, UnixTime: 2000000000, Secret: "1234567890123456789012345678901234567890123456789012345678901234", Digits: 8}, Output: "38618901"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNA=&issuer=ACME&algorithm=SHA512&digits=8&period=30'
totp = await getTotpCode(url, 2000000000)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('38618901')
// {Algorithm: "SHA1", Period: 30, UnixTime: 20000000000, Secret: "12345678901234567890", Digits: 8}, Output: "65353130"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=ACME&algorithm=SHA1&digits=8&period=30'
totp = await getTotpCode(url, 20000000000)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('65353130')
// {Algorithm: "SHA256", Period: 30, UnixTime: 20000000000, Secret: "12345678901234567890123456789012", Digits: 8}, Output: "77737706"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA&issuer=ACME&algorithm=SHA256&digits=8&period=30'
totp = await getTotpCode(url, 20000000000)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('77737706')
// {Algorithm: "SHA512", Period: 30, UnixTime: 20000000000, Secret: "1234567890123456789012345678901234567890123456789012345678901234", Digits: 8}, Output: "47863826"}
url = 'otpauth://totp/ACME:<EMAIL>?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNA=&issuer=ACME&algorithm=SHA512&digits=8&period=30'
totp = await getTotpCode(url, 20000000000)
expect(totp).not.toBeNull()
expect(totp!.code).toBe('47863826')
})
test('GeneratePassword', async () => {
let password = await generatePassword()
expect(password).not.toBeNull()
expect(password.length).toBe(64)
password = await generatePassword(32, 32)
expect(/^[a-z]{32}$/.test(password)).toBe(true)
password = await generatePassword(32, 0, 32)
expect(/^[A-Z]{32}$/.test(password)).toBe(true)
password = await generatePassword(32, 0, 0, 32)
expect(/^[0-9]{32}$/.test(password)).toBe(true)
password = await generatePassword(32, 0, 0, 0, 32)
expect(password).not.toBeNull()
expect(password.length).toBe(32)
expect(/^["!@#$%()+;<>=?[\]{}^.,]{32}$/.test(password)).toBe(true)
})
|
Keeper-Security/secrets-manager
|
sdk/javascript/packages/core/internal/test-generator.ts
|
<filename>sdk/javascript/packages/core/internal/test-generator.ts
import {
getSecrets,
initialize,
initializeStorage
} from '../src/keeper';
import {nodePlatform} from '../src/node/nodePlatform';
import {localConfigStorage} from '../src/node/localConfigStorage';
import {connectPlatform, KeeperHttpResponse, platform} from '../src/platform';
import {inspect} from 'util';
import * as fs from 'fs';
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
connectPlatform(nodePlatform)
initialize()
const platformPost = platform.post;
const platformRandomBytes = platform.getRandomBytes
const responses: { transmissionKey: string; data: string, statusCode: number } [] = []
const oneTimeToken = '<PASSWORD>' // TODO: Add user prompt for this variables
const ksmServer = 'fake.keepersecurity.com' // TODO: Add user prompt for this variable
async function generateTests() {
platform.post = postProxy
platform.getRandomBytes = getRandomBytesProxy
try {
const kvs = localConfigStorage()
await initializeStorage(kvs, oneTimeToken, ksmServer)
const response = await getSecrets({
storage: kvs
})
console.log(inspect(response, false, 6))
const kvs1 = localConfigStorage()
await initializeStorage(kvs1, oneTimeToken, ksmServer) // expect failure on invalid signature
await getSecrets({
storage: kvs1
})
} catch (e) {
console.error(e)
}
console.log(responses)
fs.writeFileSync('../../../fake_data.json', JSON.stringify(responses, null, 2))
}
generateTests().finally()
let currentTransmissionKey: string
function getRandomBytesProxy(length: number): Uint8Array {
const bytes = platformRandomBytes(length)
currentTransmissionKey = platform.bytesToBase64(bytes)
return bytes
}
async function postProxy(
url: string,
payload: Uint8Array,
headers?: { [key: string]: string }
): Promise<KeeperHttpResponse> {
const response = await platformPost(url, payload, headers)
responses.push({
transmissionKey: currentTransmissionKey,
data: platform.bytesToBase64(response.data),
statusCode: response.statusCode
})
return Promise.resolve(response)
}
|
Keeper-Security/secrets-manager
|
sdk/javascript/packages/core/test/notation.test.ts
|
<reponame>Keeper-Security/secrets-manager
import {
KeeperSecrets,
getValue
} from '../'
const recordUID = 'k9qMpcO0aszz9w3li5XbaQ'
const secrets: KeeperSecrets = {
appData: {
title: "",
type: ""
},
records: [
{
recordUid: recordUID,
data: {
title: 'My Record 1',
type: 'login',
fields: [
{type: 'login', value: ['My Login 1']},
{type: 'password', value: ['<PASSWORD>']}
],
custom: [
{type: 'text', label: 'My Custom 1', value: ['custom1']},
{type: 'text', label: 'My Custom 1', value: ['custom1']},
{type: 'text', label: 'My Custom 2', value: ['one', 'two', 'three']},
{
type: 'phone', label: 'phone', value: [
{number: '555-5555555', ext: '55'},
{number: '777-7777777', ext: '77'},
{number: '888-8888888', ext: '', 'type': 'Home'},
{number: '999-9999999', type: 'Work'}
]
},
{
type: 'name', label: 'name', value: [{
first: 'Jenny',
middle: 'X',
last: 'Smith'
}]
},
]
},
files: [
{
fileUid: 'HKGdx7dSrtuTfA67wiEZkw',
data: {
name: 'qr.png',
size: 53926,
title: 'QR Code',
lastModified: 1629142801191,
type: 'image/png'
},
url: 'QR Code File Url'
}
]
}
]
}
test('Notations', () => {
let value
value = getValue(secrets, `keeper://${recordUID}/field/login`)
expect(value).toBe('My Login 1')
value = getValue(secrets, `${recordUID}/field/login`)
expect(value).toBe('My Login 1')
value = getValue(secrets, `keeper://${recordUID}/field/login[0]`)
expect(value).toBe('My Login 1')
try {
value = getValue(secrets, `keeper://${recordUID}/field/login[1]`)
fail('Getting wrong index did not throw')
} catch ({message}) {
expect(message).toContain(`The index 1 for field value of login in the record ${recordUID} is out of range`)
}
value = getValue(secrets, `keeper://${recordUID}/field/login[]`)
expect(value).toStrictEqual(['My Login 1'])
value = getValue(secrets, `keeper://${recordUID}/custom_field/My Custom 1`)
expect(value).toBe('custom1')
value = getValue(secrets, `keeper://${recordUID}/custom_field/My Custom 2`)
expect(value).toBe('one')
value = getValue(secrets, `keeper://${recordUID}/custom_field/My Custom 2[1]`)
expect(value).toBe('two')
value = getValue(secrets, `keeper://${recordUID}/custom_field/My Custom 2[]`)
expect(value).toStrictEqual(['one','two','three'])
value = getValue(secrets, `keeper://${recordUID}/custom_field/phone[0][number]`)
expect(value).toBe('555-5555555')
value = getValue(secrets, `keeper://${recordUID}/custom_field/phone[1][number]`)
expect(value).toBe('777-7777777')
value = getValue(secrets, `keeper://${recordUID}/custom_field/phone[2]`)
expect(value).toStrictEqual({number: "888-8888888", ext: "", type: "Home"})
value = getValue(secrets, `keeper://${recordUID}/custom_field/name[first]`)
expect(value).toBe('Jenny')
value = getValue(secrets, `keeper://${recordUID}/custom_field/name[last]`)
expect(value).toBe('Smith')
value = getValue(secrets, `keeper://${recordUID}/file/QR Code`)
expect(value.fileUid).toBe('HKGdx7dSrtuTfA67wiEZkw')
expect(value.url).toBe('QR Code File Url')
value = getValue(secrets, `keeper://${recordUID}/file/qr.png`)
expect(value.fileUid).toBe('HKGdx7dSrtuTfA67wiEZkw')
expect(value.url).toBe('QR Code File Url')
})
|
eduardozgz/member-counter-bot
|
src/commands/utils.ts
|
import Command from "../typings/Command";
import { GuildChannel, VoiceChannel } from "eris";
import botHasPermsToEdit from "../utils/botHasPermsToEdit";
import UserError from "../utils/UserError";
import CountService from "../services/CountService";
import getEnv from "../utils/getEnv";
import setStatus from "../others/setStatus";
import Eris from "eris";
import ClientStatsService from "../services/ClientStatsService";
import { CommandUsage } from "../models/ClientStats";
import commands from "./all";
import embedBase from "../utils/embedBase";
import Paginator from "../utils/paginator";
const { BOT_OWNERS } = getEnv();
const lockChannel: Command = {
aliases: ["lockChannel", "lock"],
denyDm: true,
onlyAdmin: true,
run: async ({ message, languagePack, client }) => {
const {
success,
errorInvalidChannel,
errorNoPerms,
errorNotFound
} = languagePack.commands.lockChannel;
const { channel, content } = message;
const [command, channelId] = content.split(/\s+/);
const { guild } = channel;
if (guild.channels.has(channelId)) {
const channelToEdit = guild.channels.get(channelId);
if (channelToEdit instanceof VoiceChannel) {
if (botHasPermsToEdit(channelToEdit)) {
await channelToEdit.editPermission(
client.user.id,
Eris.Constants.Permissions.voiceConnect |
Eris.Constants.Permissions.viewChannel,
0,
// TODO use constants when abalabahaha/eris#1271 is merged
1
);
await channelToEdit.editPermission(
guild.id,
0,
Eris.Constants.Permissions.voiceConnect,
// TODO use constants when abalabahaha/eris#1271 is merged
0
);
} else {
throw new UserError(errorNoPerms.replace(/\{CHANNEL\}/gi, channelId));
}
} else {
throw new UserError(errorInvalidChannel);
}
} else {
throw new UserError(errorNotFound);
}
await channel.createMessage(success);
}
};
const editChannel: Command = {
aliases: ["editChannel", "edit"],
denyDm: true,
onlyAdmin: true,
run: async ({ message, languagePack, guildService }) => {
const { channel, content } = message;
if (channel instanceof GuildChannel) {
const { guild } = channel;
let [command, channelId, ...newContent]: any = content.split(/ +/);
newContent = newContent.join(" ");
if (!newContent)
throw new UserError(languagePack.commands.editChannel.errorNoContent);
if (!guild.channels.has(channelId))
throw new UserError(languagePack.commands.editChannel.errorNotFound);
await guildService.setCounter(channelId, newContent);
await channel.createMessage(languagePack.commands.editChannel.success);
}
}
};
const preview: Command = {
aliases: ["test", "preview"],
denyDm: true,
onlyAdmin: false,
run: async ({ message, languagePack, guildService }) => {
const { channel, content } = message;
if (channel instanceof GuildChannel) {
const { guild } = channel;
let [command, ...contentToTest]: any = content.split(/ +/);
contentToTest = contentToTest.join(" ");
if (!contentToTest)
throw new UserError(languagePack.commands.editChannel.errorNoContent);
const counterService = await CountService.init(guild);
const { channelName, channelTopic } = languagePack.commands.preview;
const previewMessage = `${channelName}:\n${await counterService.processContent(
contentToTest,
false
)}\n\n${channelTopic}:\n${await counterService.processContent(
contentToTest,
true
)}`;
await channel.createMessage(previewMessage);
}
}
};
const base64: Command = {
aliases: ["base64"],
denyDm: false,
run: async ({ message, languagePack }) => {
const { channel, content } = message;
let action = "";
let string = "";
let parts = content.trimStart().split(" ");
parts.shift(); // remove command ("base64" or any alias)
for (const part of parts) {
// if action has been not found yet AND part is a whitespace
if (!action && !part) continue;
// else, if there is no action, set the current part to the action
else if (!action) action = part;
// else, if there is no part (but the action has been found before), recover a whitespace lost in the split
else if (!part) string += " ";
// else, concatenate the part to the string that will be encoded or decoded
else string += part;
}
switch (action) {
case "encode": {
await channel.createMessage(Buffer.from(string).toString("base64"));
break;
}
case "decode": {
await channel.createMessage(Buffer.from(string, "base64").toString());
break;
}
default: {
await channel.createMessage(languagePack.commands.base64.invalidAction);
break;
}
}
}
};
const setStatusCmd: Command = {
aliases: ["setStatus"],
denyDm: false,
run: async ({ client, message, languagePack }) => {
if (!BOT_OWNERS.includes(message.author.id)) return;
let [, ...content] = message.content.split(" ");
await message.channel.sendTyping();
const { text, type, status } = setStatus(client, content.join(" "));
await message.channel.createMessage(`Now _${type}_ **${text}**`);
}
};
const commandStats: Command = {
aliases: ["commandStats"],
denyDm: false,
run: async ({ client, message, languagePack }) => {
const clientStats = await ClientStatsService.init(client.user.id);
const commandStats: [string, CommandUsage][] = Array.from(
clientStats.commandUsageStats.entries()
).map(([key, entry]) => [JSON.parse(key), entry]);
const allTotalHourlyUsage = commandStats
.map(([, value]) => value.hourlyUsage)
.reduce((a, b) => a + b);
const allTotalDailyUsage = commandStats
.map(([, value]) => value.dailyUsage)
.reduce((a, b) => a + b);
const allTotalWeeklyUsage = commandStats
.map(([, value]) => value.weeklyUsage)
.reduce((a, b) => a + b);
const allTotalMonthlyUsage = commandStats
.map(([, value]) => value.monthlyUsage)
.reduce((a, b) => a + b);
const allTotalUsage = commandStats
.map(([, value]) => value.totalUsage)
.reduce((a, b) => a + b);
const description = languagePack.commands.commandStats.stats.usageText
.replace(/{totalHourlyUsage}/, String(allTotalHourlyUsage))
.replace(/{totalDailyUsage}/, String(allTotalDailyUsage))
.replace(/{totalWeeklyUsage}/, String(allTotalWeeklyUsage))
.replace(/{totalMonthlyUsage}/, String(allTotalMonthlyUsage))
.replace(/{totalUsage}/, String(allTotalUsage));
function chunkArray(array: Array<any>, arraySize: number): Array<any> {
let index: number;
const arrayLength = array.length;
const tempArray = [];
let splitArrays: Array<any>;
for (index = 0; index < arrayLength; index += arraySize) {
splitArrays = array.slice(index, index + arraySize);
tempArray.push(splitArrays);
}
return tempArray;
}
const fields = [];
commands.forEach((command) => {
const {
hourlyUsage,
dailyUsage,
weeklyUsage,
monthlyUsage,
totalUsage
} = clientStats.commandUsageStats.get(JSON.stringify(command.aliases));
const hourlyUsagePercent =
((hourlyUsage / allTotalHourlyUsage) * 100).toFixed(1) === "NaN"
? "0.0"
: ((hourlyUsage / allTotalHourlyUsage) * 100).toFixed(1) + "%";
const dailyUsagePercent =
((dailyUsage / allTotalDailyUsage) * 100).toFixed(1) === "NaN"
? "0.0"
: ((dailyUsage / allTotalDailyUsage) * 100).toFixed(1) + "%";
const weeklyUsagePercent =
((weeklyUsage / allTotalWeeklyUsage) * 100).toFixed(1) === "NaN"
? "0.0"
: ((weeklyUsage / allTotalWeeklyUsage) * 100).toFixed(1) + "%";
const monthlyUsagePercent =
((monthlyUsage / allTotalMonthlyUsage) * 100).toFixed(1) === "NaN"
? "0.0"
: ((monthlyUsage / allTotalMonthlyUsage) * 100).toFixed(1) + "%";
const totalUsagePercent =
((totalUsage / allTotalUsage) * 100).toFixed(1) === "NaN"
? "0.0"
: ((totalUsage / allTotalUsage) * 100).toFixed(1) + "%";
let field = Object.assign(
{},
languagePack.commands.commandStats.stats.commandUsageField
);
field = Object.assign(field, {
name: field.name.replace(/{commandName}/, command.aliases[0])
});
field = Object.assign(field, {
value: field.value
.replace(/{commandHourlyPercentageOfTotal}/, hourlyUsagePercent)
.replace(/{commandDailyPercentageOfTotal}/, dailyUsagePercent)
.replace(/{commandWeeklyPercentageOfTotal}/, weeklyUsagePercent)
.replace(/{commandMonthlyPercentageOfTotal}/, monthlyUsagePercent)
.replace(/{commandTotalPercentageOfTotal}/, totalUsagePercent)
.replace(/{commandHourlyUsage}/, String(hourlyUsage))
.replace(/{commandDailyUsage}/, String(dailyUsage))
.replace(/{commandWeeklyUsage}/, String(weeklyUsage))
.replace(/{commandMonthlyUsage}/, String(monthlyUsage))
.replace(/{commandUsageTotal}/, String(totalUsage))
});
fields.push(field);
});
const fieldsChunks = chunkArray(fields, 6);
const embeds = fieldsChunks.map((fields) => {
return embedBase({ description, fields, timestamp: new Date() });
});
new Paginator(
message.channel,
message.author.id,
embeds,
languagePack
).displayPage(0);
}
};
const utilCommands = [
lockChannel,
editChannel,
preview,
base64,
setStatusCmd,
commandStats
];
export default utilCommands;
|
eduardozgz/member-counter-bot
|
src/services/ClientStatsService.ts
|
import ClientStatsModel, {
CommandUsage,
CommandUsageStatsByDate,
ClientStatsDocument
} from "../models/ClientStats";
class ClientStatsService {
private constructor(
public command: string,
private doc: ClientStatsDocument
) {}
public static async init(id: string): Promise<ClientStatsService> {
const doc = await ClientStatsModel.findOneAndUpdate(
{ id: id },
{},
{ new: true, upsert: true }
);
return new ClientStatsService(id, doc);
}
public get commandsRun(): number {
return this.doc.commandsRun;
}
public async incrementCommandsRun(): Promise<number> {
this.doc.commandsRun++;
await this.doc.save();
return this.doc.commandsRun;
}
public get commandUsageStats(): Map<string, CommandUsage> {
return this.doc.commandUsageStats;
}
public async setCommandStats(
command: string,
usage: CommandUsage
): Promise<CommandUsage> {
this.doc.commandUsageStats.set(command, usage);
await this.doc.save();
return this.doc.commandUsageStats.get(command);
}
public get commandUsageStatsByDate(): Map<string, CommandUsageStatsByDate> {
return this.doc.commandUsageStatsByDate;
}
public async setCommandUsageByDate(
date: string,
usage: CommandUsageStatsByDate
): Promise<CommandUsageStatsByDate> {
this.doc.commandUsageStatsByDate.set(date, usage);
await this.doc.save();
return this.doc.commandUsageStatsByDate.get(date);
}
public async remove(): Promise<void> {
await this.doc.remove();
}
}
export default ClientStatsService;
|
eduardozgz/member-counter-bot
|
src/utils/initializeClientStats.ts
|
<gh_stars>100-1000
import { Client } from "eris";
import ClientStatsService from "../services/ClientStatsService";
import commands from "../commands/all";
async function initializeCommandStats(client: Client) {
const ClientStats = await ClientStatsService.init(client.user.id);
const delays: Array<number> = new Array(commands.length)
.fill(0)
.map((ele, index, array) => {
return array[index - 1] !== undefined || !isNaN(array[index - 1])
? (array[index] = array[index - 1] + 125)
: (array[index] = ele);
});
commands.forEach((command, index) => {
if (!ClientStats.commandUsageStats.has(JSON.stringify(command.aliases))) {
setTimeout(async () => {
await ClientStats.setCommandStats(JSON.stringify(command.aliases), {
hourlyUsage: 0,
hourlyUsageDate: new Date(),
dailyUsage: 0,
dailyUsageDate: new Date(),
weeklyUsage: 0,
weeklyUsageDate: new Date(),
monthlyUsage: 0,
monthlyUsageDate: new Date(),
totalUsage: 0,
stats: Object.fromEntries(new Map())
});
}, delays[index]);
}
});
}
export default initializeCommandStats;
|
eduardozgz/member-counter-bot
|
src/models/ClientStats.ts
|
import { Map } from "mongodb";
import { model, Schema, Document } from "mongoose";
interface CommandUsageStats {
engagedUsers: Array<string>;
uses: Map<string, number>;
}
export interface CommandUsage {
hourlyUsage: number;
hourlyUsageDate: Date;
dailyUsage: number;
dailyUsageDate: Date;
weeklyUsage: number;
weeklyUsageDate: Date;
monthlyUsage: number;
monthlyUsageDate: Date;
totalUsage: number;
stats: Map<string, CommandUsageStats>;
}
export interface CommandUsageStatsByDate {
engagedUsers: Array<string>;
uses: number;
}
interface ClientStatsDocument extends Document {
id: string;
commandsRun: number;
commandUsageStats: Map<string, CommandUsage>;
commandUsageStatsByDate: Map<string, CommandUsageStatsByDate>;
}
const ClientStatsSchema = new Schema({
id: { type: String, require: true },
commandsRun: { type: Number, default: 0 },
commandUsageStats: {
type: Map,
of: new Schema({
hourlyUsage: { type: Number, require: true, default: 0 },
hourlyUsageDate: { type: Date, require: true, default: new Date() },
dailyUsage: { type: Number, require: true, default: 0 },
dailyUsageDate: { type: Date, require: true, default: new Date() },
weeklyUsage: { type: Number, require: true, default: 0 },
weeklyUsageDate: { type: Date, require: true, default: new Date() },
monthlyUsage: { type: Number, require: true, default: 0 },
monthlyUsageDate: { type: Date, require: true, default: new Date() },
totalUsage: { type: Number, require: true, default: 0 },
stats: {
type: Map,
of: new Schema({
engagedUsers: {
type: Array,
of: String,
default: [],
require: false
},
uses: { type: Map, of: Number, require: false }
}),
default: new Map<string, CommandUsageStats>()
}
}),
default: new Map<string, CommandUsage>(),
require: false
},
commandUsageStatsByDate: {
type: Map,
of: new Schema({
engagedUsers: { type: Array, default: [] },
uses: { type: Number, default: 0 }
}),
default: new Map<string, CommandUsageStatsByDate>()
}
});
const ClientStatsModel = model<ClientStatsDocument>(
"client-stats",
ClientStatsSchema
);
export { ClientStatsModel, ClientStatsDocument };
export default ClientStatsModel;
|
eduardozgz/member-counter-bot
|
src/utils/commandHandler.ts
|
import getEnv from "./getEnv";
import Eris, { GuildTextableChannel, Message } from "eris";
import GuildService from "../services/GuildService";
import { loadLanguagePack } from "./languagePack";
import memberHasAdminPermission from "./memberHasAdminPermission";
import commandErrorHandler from "./commandErrorHandler";
import commands from "../commands/all";
import Bot from "../bot";
import LanguagePack from "../typings/LanguagePack";
import { GuildChannelCommand, AnyChannelCommand } from "../typings/Command";
import UserService from "../services/UserService";
import escapeRegex from "./escapeRegex";
import ClientStatsService from "../services/ClientStatsService";
import daysInCurrentMonth from "../utils/daysInCurrentMonth";
const {
PREMIUM_BOT,
DISCORD_PREFIX,
DISCORD_PREFIX_MENTION_DISABLE,
DISCORD_DEFAULT_LANG,
DISCORD_OFFICIAL_SERVER_ID,
GHOST_MODE,
BOT_OWNERS
} = getEnv();
export default async (message: Eris.Message) => {
if (GHOST_MODE && !BOT_OWNERS.includes(message.author?.id)) return;
const { author, content } = message;
let { channel } = message;
const { client } = Bot;
// Ignore requested commands in the official server since this server already has the premium bot
if (
channel instanceof Eris.GuildChannel &&
!PREMIUM_BOT &&
channel.guild.id === DISCORD_OFFICIAL_SERVER_ID
) {
return;
}
// Avoid responding to other bots
if (author && !author.bot) {
// fetch dm channel
if (!message.guildID) {
message.channel = await message.author.getDMChannel();
({ channel } = message);
}
let prefixToCheck: string;
let languagePack: LanguagePack;
let clientIntegrationRoleId: string;
let guildService: GuildService;
// upsert the message author in the db
await UserService.init(author.id);
if (channel instanceof Eris.GuildChannel) {
const { guild } = channel;
guildService = await GuildService.init(guild.id);
languagePack = loadLanguagePack(guildService.language);
prefixToCheck = guildService.prefix;
clientIntegrationRoleId = guild.members
.get(client.user.id)
?.roles.filter((roleID) =>
guild.roles.get(roleID)?.managed ? roleID : null
)[0];
} else {
languagePack = loadLanguagePack(DISCORD_DEFAULT_LANG);
prefixToCheck = DISCORD_PREFIX;
}
prefixToCheck = prefixToCheck.toLowerCase();
let prefixRegexStr = "^(";
if (!DISCORD_PREFIX_MENTION_DISABLE) {
// mention of integration role as prefix
if (clientIntegrationRoleId) {
prefixRegexStr += `<@&${clientIntegrationRoleId}>|`;
}
// mention as prefix
prefixRegexStr += `<@!?${client.user.id}>|`;
}
// normal prefix
prefixRegexStr += escapeRegex(prefixToCheck);
prefixRegexStr += `)\\s*`;
const prefixRegex = new RegExp(prefixRegexStr, "i");
const commandRequested = content.toLowerCase(); // Case insensitive match
const matchedPrefix = commandRequested.match(prefixRegex)?.[0];
if (matchedPrefix == null) return;
if (commandRequested.startsWith(matchedPrefix)) {
commandsLoop: for (const command of commands) {
for (const alias of command.aliases) {
let commandAliasToCheck = matchedPrefix + alias.toLowerCase();
if (commandRequested.startsWith(commandAliasToCheck)) {
const ClientStats = await ClientStatsService.init(client.user.id);
let commandStats = ClientStats.commandUsageStats.get(
JSON.stringify(command.aliases)
);
const date = new Date().toLocaleString("en-US", {
month: "numeric",
day: "numeric",
year: "numeric"
});
const time = new Date().toLocaleTimeString("en-US", {
hour: "2-digit",
minute: "2-digit"
});
let stats = commandStats.stats;
let hourlyUsage = commandStats.hourlyUsage;
let hourlyUsageIncrement = hourlyUsage + 1;
let hourlyUsageDate = commandStats.hourlyUsageDate;
let dailyUsage = commandStats.dailyUsage;
let dailyUsageIncrement = dailyUsage + 1;
let dailyUsageDate = commandStats.dailyUsageDate;
let weeklyUsage = commandStats.weeklyUsage;
let weeklyUsageIncrement = weeklyUsage + 1;
let weeklyUsageDate = commandStats.weeklyUsageDate;
let monthlyUsage = commandStats.monthlyUsage;
let monthlyUsageIncrement = monthlyUsage + 1;
let monthlyUsageDate = commandStats.monthlyUsageDate;
let totalUsage = commandStats.totalUsage;
let totalUsageIncrement = totalUsage + 1;
let engagedUsers =
Object.fromEntries(stats?.entries() ?? new Map())[date]
?.engagedUsers ?? [];
let statEntries = Object.entries(
Object.fromEntries(stats?.entries() ?? new Map())
);
let useEntries = Object.entries(
Object.fromEntries(
Object.fromEntries(stats?.entries() ?? new Map())[
date
]?.uses?.entries() ?? new Map()
) ?? new Map()
);
let uses =
Object.fromEntries(
Object.fromEntries(stats?.entries() ?? new Map())[
date
]?.uses?.entries() ?? new Map()
)[time] === undefined
? 0
: Object.fromEntries(
Object.fromEntries(stats?.entries() ?? new Map())[date]
?.uses
)[time];
let usageStatsForDate = Object.fromEntries(
ClientStats.commandUsageStatsByDate.entries()
)[date] ?? { engagedUsers: [], uses: 0 };
let engagedUsersForDate = usageStatsForDate?.engagedUsers;
let usesForDate = usageStatsForDate?.uses;
engagedUsersForDate = [...engagedUsersForDate, "userid"];
usesForDate = usesForDate + 1;
let hourlyUsageDifference =
new Date().getTime() - hourlyUsageDate.getTime();
let dailyUsageDifference =
new Date().getTime() - dailyUsageDate.getTime();
let weeklyUsageDifference =
new Date().getTime() - weeklyUsageDate.getTime();
let monthlyUsageDifference =
new Date().getTime() - monthlyUsageDate.getTime();
if (hourlyUsageDifference >= 3600000) {
commandStats = Object.assign(commandStats, {
hourlyUsage: 0,
hourlyUsageDate: new Date()
});
} else {
commandStats = Object.assign(commandStats, {
hourlyUsage: hourlyUsageIncrement
});
}
if (dailyUsageDifference >= 86400000) {
commandStats = Object.assign(commandStats, {
dailyUsage: 0,
dailyUsageDate: new Date()
});
} else {
commandStats = Object.assign(commandStats, {
dailyUsage: dailyUsageIncrement
});
}
if (weeklyUsageDifference >= 604800000) {
commandStats = Object.assign(commandStats, {
weeklyUsage: 0,
weeklyUsageDate: new Date()
});
} else {
commandStats = Object.assign(commandStats, {
weeklyUsage: weeklyUsageIncrement
});
}
if (daysInCurrentMonth === 30) {
if (monthlyUsageDifference >= 2592000000) {
commandStats = Object.assign(commandStats, {
monthlyUsage: 0,
monthlyUsageDate: new Date()
});
} else {
commandStats = Object.assign(commandStats, {
monthlyUsage: monthlyUsageIncrement
});
}
} else {
if (monthlyUsageDifference >= 2678400000) {
commandStats = Object.assign(commandStats, {
monthlyUsage: 0,
monthlyUsageDate: new Date()
});
} else {
commandStats = Object.assign(commandStats, {
monthlyUsage: monthlyUsageIncrement
});
}
}
commandStats = Object.assign(commandStats, {
totalUsage: totalUsageIncrement,
stats: Object.fromEntries(
new Map([
...statEntries,
[
date,
{
engagedUsers: [...engagedUsers, "userid"].filter(
(v: string, i: number, a: Array<string>) =>
a.findIndex((t) => t === v) === i
),
uses: Object.fromEntries(
new Map([...useEntries, [time, uses + 1]])
)
}
]
])
)
});
setTimeout(async () => {
await ClientStats.setCommandStats(
JSON.stringify(command.aliases),
commandStats
);
await ClientStats.incrementCommandsRun();
usageStatsForDate = Object.assign(usageStatsForDate, {
uses: usesForDate,
engagedUsers: engagedUsersForDate.filter(
(v: string, i: number, a: Array<string>) =>
a.findIndex((t) => t === v) === i
)
});
await ClientStats.setCommandUsageByDate(date, usageStatsForDate);
}, 100);
if (channel instanceof Eris.PrivateChannel && command.denyDm) {
channel
.createMessage(languagePack.functions.commandHandler.noDm)
.catch(console.error);
break commandsLoop;
}
if (
channel instanceof Eris.GuildChannel &&
(command as GuildChannelCommand).onlyAdmin &&
!(await memberHasAdminPermission(message.member))
) {
channel
.createMessage(languagePack.common.errorNoAdmin)
.catch(console.error);
break commandsLoop;
}
try {
const guild =
channel instanceof Eris.GuildChannel ? channel.guild : false;
console.log(
`${author.username}#${author.discriminator} (${author.id}) [${
guild ? `Server: ${guild.name} (${guild.id}), ` : ``
}Channel: ${channel.id}]: ${content}`
);
message.content = message.content.replace(prefixRegex, "");
if (matchedPrefix.startsWith("<@&")) {
message.roleMentions.shift();
} else if (matchedPrefix.startsWith("<@")) {
message.mentions.shift();
}
if (channel instanceof Eris.GuildChannel) {
await (command as GuildChannelCommand).run({
client,
message: message as Message<GuildTextableChannel>,
languagePack,
guildService
});
} else {
await (command as AnyChannelCommand).run({
client,
message,
languagePack
});
}
} catch (error) {
commandErrorHandler(channel, languagePack, prefixToCheck, error);
}
break commandsLoop;
}
}
}
}
}
};
|
eduardozgz/member-counter-bot
|
src/jobs/updateCommandStats.ts
|
<gh_stars>100-1000
import Job from "../typings/Job";
import ClientStatsService from "../services/ClientStatsService";
import commands from "../commands/all";
import daysInCurrentMonth from "../utils/daysInCurrentMonth";
const updateCommandStats: Job = {
time: "0 */30 * * * *",
runAtStartup: true,
runInOnlyFirstThread: false,
run: async ({ client }) => {
const delays: Array<number> = new Array(commands.length)
.fill(0)
.map((ele, index, array) => {
return array[index - 1] !== undefined || !isNaN(array[index - 1])
? (array[index] = array[index - 1] + 125)
: (array[index] = ele);
});
const ClientStats = await ClientStatsService.init(client.user.id);
commands.forEach((command, index) => {
let commandStats = ClientStats.commandUsageStats.get(
JSON.stringify(command.aliases)
);
let hourlyUsageDate = commandStats.hourlyUsageDate;
let dailyUsageDate = commandStats.dailyUsageDate;
let weeklyUsageDate = commandStats.weeklyUsageDate;
let monthlyUsageDate = commandStats.monthlyUsageDate;
let hourlyUsageDifference =
new Date().getTime() - hourlyUsageDate.getTime();
let dailyUsageDifference =
new Date().getTime() - dailyUsageDate.getTime();
let weeklyUsageDifference =
new Date().getTime() - weeklyUsageDate.getTime();
let monthlyUsageDifference =
new Date().getTime() - monthlyUsageDate.getTime();
if (hourlyUsageDifference >= 3600000) {
commandStats = Object.assign(commandStats, {
hourlyUsage: 0,
hourlyUsageDate: new Date()
});
}
if (dailyUsageDifference >= 86400000) {
commandStats = Object.assign(commandStats, {
dailyUsage: 0,
dailyUsageDate: new Date()
});
}
if (weeklyUsageDifference >= 604800000) {
commandStats = Object.assign(commandStats, {
weeklyUsage: 0,
weeklyUsageDate: new Date()
});
}
if (daysInCurrentMonth === 30) {
if (monthlyUsageDifference >= 2592000000) {
commandStats = Object.assign(commandStats, {
monthlyUsage: 0,
monthlyUsageDate: new Date()
});
}
} else {
if (monthlyUsageDifference >= 2678400000) {
commandStats = Object.assign(commandStats, {
monthlyUsage: 0,
monthlyUsageDate: new Date()
});
}
}
setTimeout(async () => {
await ClientStats.setCommandStats(
JSON.stringify(command.aliases),
commandStats
);
}, delays[index]);
});
}
};
export default updateCommandStats;
|
eduardozgz/member-counter-bot
|
src/utils/daysInCurrentMonth.ts
|
function daysInThisMonth(): number {
var now: Date = new Date();
return new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
}
const daysInCurrentMonth = daysInThisMonth();
export default daysInCurrentMonth;
|
sr3dna/xplat
|
packages/xplat/src/utils/xplat.ts
|
<filename>packages/xplat/src/utils/xplat.ts
import {
Tree,
noop,
branchAndMerge,
mergeWith,
apply,
url,
template,
move,
SchematicContext,
Rule,
externalSchematic,
SchematicsException
} from '@angular-devkit/schematics';
import { createSourceFile, ScriptTarget } from 'typescript';
import {
getDefaultTemplateOptions,
getPrefix,
updateJsonFile,
getJsonFromFile,
stringUtils,
PlatformTypes,
supportedSandboxPlatforms,
supportedPlatforms,
getGroupByName,
sanitizeCommaDelimitedArg,
updateFile,
updateTsConfig,
getNxWorkspaceConfig,
PlatformModes,
isTesting,
jsonParse,
FrameworkTypes,
getFrontendFramework,
IXplatSettings,
supportedFrameworks,
PlatformWithNxTypes,
supportedNxExtraPlatforms,
PlatformNxExtraTypes,
supportedPlatformsWithNx
} from './general';
import {
updateJsonInTree,
toFileName,
serializeJson,
readJsonInTree
} from '@nrwl/workspace';
import { insert, addGlobal } from './ast';
import {
platformAppPrefixError,
generatorError,
optionsMissingError,
noPlatformError,
unsupportedPlatformError,
noteAboutXplatSetupWithFramework,
unsupportedFrameworkError,
generateOptionError,
noXplatLayerNote
} from './errors';
import { join } from 'path';
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
import {
NodePackageInstallTask,
RunSchematicTask
} from '@angular-devkit/schematics/tasks';
import { xplatVersion, nxVersion } from './versions';
import { output } from './output';
export const packageInnerDependencies = {
'@nstudio/angular': ['@nrwl/angular'],
'@nstudio/electron-angular': [
'@nrwl/angular',
'@nstudio/electron',
'@nstudio/angular'
],
'@nstudio/ionic-angular': [
'@nrwl/angular',
'@nstudio/ionic',
'@nstudio/angular',
'@nstudio/web-angular'
],
'@nstudio/nativescript-angular': [
'@nrwl/angular',
'@nstudio/nativescript',
'@nstudio/angular'
],
'@nstudio/web-angular': ['@nrwl/angular', '@nstudio/web', '@nstudio/angular']
};
export namespace XplatHelpers {
export interface Schema {
/**
* Target platforms
*/
platforms?: string;
/**
* Target frameworks
*/
framework?: string;
/**
* npm scope - auto detected from nx.json but can specify your own name
*/
npmScope?: string;
/**
* The prefix to apply to generated selectors.
*/
prefix?: string;
/**
* Skip formatting
*/
skipFormat?: boolean;
/**
* Skip dependent platform files
*/
skipDependentPlatformFiles?: boolean;
useXplat?: boolean;
/**
* Skip install
*/
skipInstall?: boolean;
/**
* group by name
*/
groupByName?: boolean;
/**
* testing helper
*/
isTesting?: boolean;
}
export interface NgAddSchema {
/**
* Target platforms
*/
platforms?: string;
/**
* Target frameworks
*/
framework?: string;
/**
* The prefix to apply to generated selectors.
*/
prefix?: string;
}
export interface IXplatGeneratorOptions {
featureName?: string;
projectNames?: Array<string>;
platforms: Array<PlatformWithNxTypes>;
}
/**
* Calls ng-add _if_ the package does not already exist
* Otherwise calls that schematic if desired, otherwise noop
*/
export function addPackageWithNgAdd(
packageName: string,
options?: NgAddSchema,
callSchematicIfAdded?: string
): Rule {
return (host: Tree) => {
const { dependencies, devDependencies } = readJsonInTree(
host,
'package.json'
);
return dependencies[packageName] || devDependencies[packageName]
? callSchematicIfAdded
? externalSchematic(packageName, callSchematicIfAdded, options, {
interactive: false
})
: noop()
: externalSchematic(packageName, 'ng-add', options, {
interactive: false
});
};
}
export function getPlatformsFromOption(
platformArgument: string = '',
required: boolean = true
) {
let platforms = [];
if (platformArgument === 'all') {
// conveniently add support for all supported platforms
for (const platform of supportedPlatforms) {
platforms.push(platform);
}
} else {
const platformArgList = <Array<PlatformTypes>>(
(<unknown>sanitizeCommaDelimitedArg(platformArgument))
);
if (platformArgList.length === 0) {
if (required) {
throw new Error(noPlatformError());
}
} else {
for (const platform of platformArgList) {
if (supportedPlatforms.includes(platform)) {
platforms.push(platform);
} else {
throw new Error(unsupportedPlatformError(platform));
}
}
}
}
return platforms;
}
export function getFrameworksFromOptions(frameworkArgument: string) {
// will support comma delimited list of frameworks to generate support for
// most common to generate 1 at a time but we will allow multiple
// always default framework choice to first in list when multiple
return <Array<FrameworkTypes>>(
(<unknown>(
(frameworkArgument === 'all'
? supportedFrameworks
: sanitizeCommaDelimitedArg(frameworkArgument))
))
);
}
export function getFrameworkChoice(
frameworkArgument: string,
frameworks?: Array<FrameworkTypes>
) {
frameworks = frameworks || getFrameworksFromOptions(frameworkArgument);
return frameworks.length ? frameworks[0] : null;
}
export function getUpdatedXplatSettings(options: Schema) {
const frameworks = getFrameworksFromOptions(options.framework);
const frameworkChoice = XplatHelpers.getFrameworkChoice(
options.framework,
frameworks
);
const xplatSettings: IXplatSettings = {
prefix: getPrefix()
};
if (frameworkChoice && frameworks.length === 1) {
// when only 1 framework is specified, auto add as default
xplatSettings.framework = frameworkChoice;
}
if (options.groupByName) {
xplatSettings.groupByName = true;
}
return xplatSettings;
}
/**
* Returns a name with the platform.
*
* @example (app, web) => web-app or app-web
* @param name
* @param platform
*/
export function getPlatformName(name: string, platform: PlatformWithNxTypes) {
const nameSanitized = toFileName(name);
return getGroupByName()
? `${nameSanitized}-${platform}`
: `${platform}-${nameSanitized}`;
}
/**
* Returns xplat folder name dependent on settings.
*
* @example ('web', 'angular') => 'web-angular' if no default framework otherwise just 'web'
* @param platform
* @param framework
*/
export function getXplatFoldername(
platform: PlatformTypes,
framework?: FrameworkTypes
) {
const frontendFramework = getFrontendFramework();
// console.log('getXplatFoldername frontendFramework:', frontendFramework);
// console.log('framework:', framework);
let frameworkSuffix = '';
if (framework && frontendFramework !== framework) {
// user had a default framework set
// however an explicit framework is being requested
// if they differ, use suffix to distinguish
frameworkSuffix = `-${framework}`;
}
return `${platform}${frameworkSuffix}`;
}
export function getExternalChainsForGenerator(
options: Schema,
generator: string,
packagesToRunXplat: Array<string>
) {
let generatorSettings: IXplatGeneratorOptions;
let isApp = false;
switch (generator) {
case 'component':
generatorSettings = XplatComponentHelpers.prepare(<any>options);
break;
case 'feature':
generatorSettings = XplatFeatureHelpers.prepare(<any>options);
break;
default:
isApp = ['application', 'app'].includes(generator);
generatorSettings = {
platforms: <Array<PlatformWithNxTypes>>(
(<unknown>sanitizeCommaDelimitedArg(options.platforms))
)
};
break;
}
const platforms = generatorSettings.platforms;
const externalChains = [];
const devDependencies = {};
// frontend framework
const frameworks = getFrameworksFromOptions(options.framework);
const frameworkChoice = getFrameworkChoice(options.framework, frameworks);
// console.log('frameworks:', frameworks);
// console.log('frameworkChoice:', frameworkChoice);
// console.log('platforms:', platforms);
if (frameworks.length) {
for (const framework of frameworks) {
if (supportedFrameworks.includes(framework)) {
if (platforms.length) {
for (const platform of platforms) {
if (
framework === 'angular' &&
(!isApp || (isApp && platform === 'web'))
) {
// Angular generators start with @nstudio/angular and branch from there
// Exception: if app generator and with web platform, also use this configuration
const packageName = `@nstudio/angular`;
devDependencies[packageName] = xplatVersion;
// install platform dependencies
devDependencies[`@nstudio/${platform}-angular`] = xplatVersion;
devDependencies[`@nstudio/${platform}`] = xplatVersion;
if (!packagesToRunXplat.includes(packageName)) {
packagesToRunXplat.push(packageName);
}
} else if (
isApp &&
supportedNxExtraPlatforms.includes(<PlatformNxExtraTypes>(
platform
))
) {
// platforms that are supported directly via Nx only right now
// 'app'/'application' is only schematic supported via xplat proxy at moment
const packageName = `@nrwl/${platform}`;
devDependencies[packageName] = nxVersion;
packagesToRunXplat.push(packageName);
} else {
const packageName = `@nstudio/${platform}-${framework}`;
devDependencies[packageName] = xplatVersion;
// externalChains.push(externalSchematic(`@nstudio/${platform}-${framework}`, 'app', options));
packagesToRunXplat.push(packageName);
}
}
}
} else {
throw new SchematicsException(unsupportedFrameworkError(framework));
}
}
} else if (platforms.length) {
for (const platform of platforms) {
if (supportedPlatforms.includes(<PlatformTypes>platform)) {
const packageName = `@nstudio/${platform}`;
devDependencies[packageName] = xplatVersion;
// externalChains.push(externalSchematic(packageName, 'app', options));
packagesToRunXplat.push(packageName);
} else if (
isApp &&
supportedNxExtraPlatforms.includes(<PlatformNxExtraTypes>platform)
) {
// platforms supported directly via Nx only right now
// 'app'/'application' is only schematic supported via xplat proxy at moment
const packageName = `@nrwl/${platform}`;
devDependencies[packageName] = nxVersion;
packagesToRunXplat.push(packageName);
} else {
throw new SchematicsException(unsupportedPlatformError(platform));
}
}
}
if (Object.keys(devDependencies).length) {
externalChains.push((tree: Tree, context: SchematicContext) => {
// check if othet nstudio or nrwl dependencies are needed
// check user's package for current version
const packageJson = getJsonFromFile(tree, 'package.json');
if (packageJson) {
for (const packageName in devDependencies) {
if (packageInnerDependencies[packageName]) {
// inner dependencies are either nstudio or nrwl based packages
let version: string;
// ensure inner schematic dependencies are installed
for (const name of packageInnerDependencies[packageName]) {
if (name.indexOf('nrwl') > -1) {
// default to internally managed/supported nrwl version
version = nxVersion;
// look for existing nrwl versions if user already has them installed and use those
if (
packageJson.dependencies &&
packageJson.dependencies[name]
) {
version = packageJson.dependencies[name];
} else if (
packageJson.devDependencies &&
packageJson.devDependencies[name]
) {
version = packageJson.devDependencies[name];
}
devDependencies[name] = version;
} else {
devDependencies[name] = xplatVersion;
}
}
}
}
}
// console.log(devDependencies);
return XplatHelpers.updatePackageForXplat(options, {
devDependencies
})(tree, context);
});
if (options.isTesting) {
// necessary to unit test the appropriately
// console.log('packagesToRunXplat:', packagesToRunXplat)
if (packagesToRunXplat.length) {
for (const packageName of packagesToRunXplat) {
externalChains.push(
externalSchematic(packageName, generator, options, {
interactive: false
})
);
}
}
} else {
externalChains.push((tree: Tree, context: SchematicContext) => {
const installPackageTask = context.addTask(
new NodePackageInstallTask()
);
// console.log('devDependencies:', devDependencies);
// console.log('packagesToRunXplat:', packagesToRunXplat);
for (const packageName of packagesToRunXplat) {
context.addTask(
new RunSchematicTask(packageName, generator, options),
[installPackageTask]
);
}
});
}
}
return externalChains;
}
export function getExternalChainsForApplication(
options: Schema,
generator: string,
packagesToRun: Array<string>
) {
let generatorSettings: IXplatGeneratorOptions = {
platforms: <Array<PlatformWithNxTypes>>(
(<unknown>sanitizeCommaDelimitedArg(options.platforms))
)
};
const platforms = generatorSettings.platforms;
const externalChains = [];
const devDependencies = {};
let xplatPlatforms = 0;
// console.log('platforms:', platforms);
if (platforms.length) {
for (const platform of platforms) {
if (supportedPlatforms.includes(<PlatformTypes>platform)) {
xplatPlatforms++;
} else if (
supportedNxExtraPlatforms.includes(<PlatformNxExtraTypes>platform)
) {
// platforms supported directly via Nx only right now
// 'app'/'application' is only schematic supported via xplat proxy at moment
const packageName = `@nrwl/${platform}`;
devDependencies[packageName] = nxVersion;
packagesToRun.push(packageName);
} else {
throw new SchematicsException(unsupportedPlatformError(platform));
}
}
}
if (Object.keys(devDependencies).length) {
externalChains.push((tree: Tree, context: SchematicContext) => {
// check if othet nstudio or nrwl dependencies are needed
// check user's package for current version
const packageJson = getJsonFromFile(tree, 'package.json');
if (packageJson) {
for (const packageName in devDependencies) {
if (packageInnerDependencies[packageName]) {
// inner dependencies are either nstudio or nrwl based packages
let version: string;
// ensure inner schematic dependencies are installed
for (const name of packageInnerDependencies[packageName]) {
if (name.indexOf('nrwl') > -1) {
// default to internally managed/supported nrwl version
version = nxVersion;
// look for existing nrwl versions if user already has them installed and use those
if (
packageJson.dependencies &&
packageJson.dependencies[name]
) {
version = packageJson.dependencies[name];
} else if (
packageJson.devDependencies &&
packageJson.devDependencies[name]
) {
version = packageJson.devDependencies[name];
}
devDependencies[name] = version;
} else {
devDependencies[name] = xplatVersion;
}
}
}
}
}
// console.log(devDependencies);
return XplatHelpers.updatePackageForXplat(options, {
devDependencies
})(tree, context);
});
}
if (options.isTesting) {
// necessary to unit test the appropriately
if (xplatPlatforms) {
externalChains.push(
externalSchematic('@nstudio/xplat', 'app-generate', options, {
interactive: false
})
);
}
if (packagesToRun.length) {
for (const packageName of packagesToRun) {
const nxPlatform = <PlatformWithNxTypes>(
packageName.replace('@nrwl/', '')
);
const { name, directory } = getAppNamingConvention(
options,
nxPlatform
);
output.log({
title: 'Note:',
bodyLines: [noXplatLayerNote(nxPlatform)]
});
externalChains.push(
externalSchematic(
packageName,
generator,
{
...options,
name,
directory
},
{
interactive: false
}
)
);
}
}
} else {
if (xplatPlatforms) {
externalChains.push(
externalSchematic('@nstudio/xplat', 'app-generate', options)
);
}
if (packagesToRun.length) {
externalChains.push((tree: Tree, context: SchematicContext) => {
const installPackageTask = context.addTask(
new NodePackageInstallTask()
);
// console.log('devDependencies:', devDependencies);
// console.log('packagesToRunXplat:', packagesToRunXplat);
for (const packageName of packagesToRun) {
const nxPlatform = <PlatformWithNxTypes>(
packageName.replace('@nrwl/', '')
);
const { name, directory } = getAppNamingConvention(
options,
nxPlatform
);
output.log({
title: 'Note:',
bodyLines: [noXplatLayerNote(nxPlatform)]
});
context.addTask(
new RunSchematicTask(packageName, generator, {
...options,
name,
directory
}),
[installPackageTask]
);
}
});
}
}
return externalChains;
}
export function applyAppNamingConvention(
options: any,
platform: PlatformWithNxTypes
) {
return (tree: Tree, context: SchematicContext) => {
const { name, directory } = getAppNamingConvention(options, platform);
options.name = name;
options.directory = directory;
// console.log('applyAppNamingConvention:', options);
// adjusted name, nothing else to do
return noop()(tree, context);
};
}
export function getAppNamingConvention(
options: any,
platform: PlatformWithNxTypes
) {
let name = '';
let directory = '';
if (options.directory) {
directory = toFileName(options.directory);
if (
directory === platform &&
supportedPlatformsWithNx.includes(<PlatformWithNxTypes>directory)
) {
name = toFileName(options.name);
} else {
name = getPlatformName(options.name, platform);
}
} else {
name = getPlatformName(options.name, platform);
}
return {
name,
directory
};
}
export function addPlatformFiles(options: Schema, platform: string) {
return (tree: Tree, context: SchematicContext) => {
let frontendFramework: FrameworkTypes = getFrontendFramework();
if (tree.exists(`xplat/${platform}/index.ts`)) {
// check if framework had been set
frontendFramework = getFrontendFramework();
// console.log('addPlatformFiles frontendFramework:', frontendFramework)
// console.log('addPlatformFiles options.framework:', options.framework)
if (frontendFramework && !options.framework) {
// User is attempting to add xplat support for platform they added previously paired with a framework
// base platform support: platform without framework integrations
// ie: vanilla {N}, vanilla web, vanilla ionic, etc. (without angular, react, vue, etc.)
// if user had set a default framework and is now attempting to generate base platform support
// TODO: add schematic to reconfigure workspace to rename xplat folders to support full multi-framework setup
throw new SchematicsException(
noteAboutXplatSetupWithFramework(frontendFramework, platform)
);
}
// already added
return noop();
}
const xplatFolderName = XplatHelpers.getXplatFoldername(
<PlatformTypes>platform,
<FrameworkTypes>options.framework
);
return branchAndMerge(
mergeWith(
apply(url(`./_files`), [
template({
...(options as any),
...getDefaultTemplateOptions(),
xplatFolderName
}),
move(`xplat/${xplatFolderName}`)
])
)
);
};
}
export function updatePackageForXplat(
options: Schema,
updates: {
dependencies?: { [key: string]: string };
devDependencies?: { [key: string]: string };
}
) {
return (tree: Tree, context: SchematicContext) => {
const packagePath = 'package.json';
let packageJson = getJsonFromFile(tree, packagePath);
if (packageJson) {
// could introduce xplat.json but trying to avoid too much extra overhead so just store in package.json for now
// can migrate this later if decide enough settings for xplat.json
// prefix is important because shared code is setup with a prefix to begin with which should be known and used for all subsequent apps which are generated
const xplatSettings: IXplatSettings = getUpdatedXplatSettings(options);
if (!updates && xplatSettings) {
// just updating xplat internal settings
packageJson.xplat = {
...(packageJson.xplat || {}),
...xplatSettings
};
// just update xplat workspace settings
return updateJsonFile(tree, packagePath, packageJson);
} else if (updates) {
// update root dependencies for the generated xplat support
packageJson = {
...packageJson,
dependencies: {
...(packageJson.dependencies || {}),
...(updates.dependencies || {})
},
devDependencies: {
...(packageJson.devDependencies || {}),
...(updates.devDependencies || {})
},
xplat: {
...(packageJson.xplat || {}),
...xplatSettings
}
};
// console.log('updatePackageForXplat:', serializeJson(packageJson));
return updateJsonFile(tree, packagePath, packageJson);
}
}
return tree;
};
}
export function updateGitIgnore() {
return (tree: Tree) => {
const gitIgnorePath = '.gitignore';
let gitIgnore = tree.get(gitIgnorePath).content.toString();
if (gitIgnore) {
if (gitIgnore.indexOf('libs/**/*.js') === -1) {
gitIgnore += `
# libs
libs/**/*.js
libs/**/*.map
libs/**/*.d.ts
libs/**/*.metadata.json
libs/**/*.ngfactory.ts
libs/**/*.ngsummary.json
`;
}
if (gitIgnore.indexOf('xplat/**/*.js') === -1) {
gitIgnore += `
# xplat
xplat/**/*.js
xplat/**/*.map
xplat/**/*.d.ts
xplat/**/*.metadata.json
xplat/**/*.ngfactory.ts
xplat/**/*.ngsummary.json
`;
}
}
return updateFile(tree, gitIgnorePath, gitIgnore);
};
}
export function updateTsConfigPaths(
options: Schema,
settings?: {
framework?: FrameworkTypes;
dependentPlatforms?: Array<PlatformTypes>;
}
) {
return (tree: Tree) => {
const nxJson = getNxWorkspaceConfig(tree);
const npmScope = nxJson.npmScope;
const platformArg = options.platforms;
// sort for consistency
const platforms = (<Array<PlatformTypes>>(
(<unknown>sanitizeCommaDelimitedArg(platformArg))
)).sort(function(a, b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
const frontendFramework = getFrontendFramework();
let frameworkSuffix: string = '';
if (settings) {
if (settings.framework !== frontendFramework) {
// when users have a default framework set, generation allows name to not include the default framework of choice
frameworkSuffix = `-${settings.framework}`;
}
if (settings.dependentPlatforms) {
for (const dependentPlatform of settings.dependentPlatforms) {
if (!platforms.includes(dependentPlatform)) {
// ensure dependent platform is added since these platforms depend on it
platforms.push(dependentPlatform);
}
}
}
}
const updates: any = {};
// ensure default Nx libs path is in place
updates[`@${npmScope}/*`] = [`libs/*`];
for (const t of platforms) {
updates[`@${npmScope}/${t}${frameworkSuffix}`] = [
`xplat/${t}${frameworkSuffix}/index.ts`
];
updates[`@${npmScope}/${t}${frameworkSuffix}/*`] = [
`xplat/${t}${frameworkSuffix}/*`
];
}
return updateTsConfig(tree, (tsConfig: any) => {
if (tsConfig) {
if (!tsConfig.compilerOptions) {
tsConfig.compilerOptions = {};
}
tsConfig.compilerOptions.paths = {
...(tsConfig.compilerOptions.paths || {}),
...updates
};
}
});
};
}
export function updateIDESettings(
options: Schema,
devMode?: PlatformModes,
allApps?: string[],
focusOnApps?: string[]
) {
return (tree: Tree, context: SchematicContext) => {
if (isTesting()) {
// ignore node file modifications when just testing
return tree;
}
try {
// console.log('workspace dir:', process.cwd());
// const dirName = process.cwd().split('/').slice(-1);
const groupByName = getGroupByName();
const framework = getFrontendFramework();
let frameworkSuffix: string = framework ? `-${framework}` : '';
let isFullstack = false;
let isExcluding = false;
let appWildcards: Array<string> = [];
const userUpdates: any = {};
if (!devMode || devMode === 'fullstack') {
// show all
isFullstack = true;
for (const p of supportedPlatformsWithNx) {
const appFilter = groupByName ? `*-${p}` : `${p}*`;
userUpdates[`**/apps/${appFilter}`] = false;
userUpdates[`**/xplat/${p}`] = false;
if (frameworkSuffix) {
userUpdates[`**/xplat/${p}${frameworkSuffix}`] = false;
}
}
} else if (options.platforms) {
const platforms = sanitizeCommaDelimitedArg(options.platforms);
// switch on/off platforms
for (const p of supportedPlatformsWithNx) {
const excluded = platforms.includes(p) ? false : true;
const appFilter = groupByName ? `*-${p}` : `${p}*`;
if (focusOnApps.length) {
// focusing on apps
// fill up wildcards to use below (we will clear all app wildcards when focusing on apps)
appWildcards.push(`**/apps/${appFilter}`);
} else {
// use wildcards for apps only if no project names were specified
userUpdates[`**/apps/${appFilter}`] = excluded;
}
userUpdates[`**/xplat/${p}`] = excluded;
if (frameworkSuffix) {
userUpdates[`**/xplat/${p}${frameworkSuffix}`] = excluded;
}
if (excluded) {
// if excluding any platform at all, set the flag
// this is used for WebStorm support below
isExcluding = true;
}
}
}
// always ensure hidden xplat files are hidden from view
userUpdates['**/xplat/*/.xplatframework'] = true;
// VS Code
const isVsCode = updateVSCode({
userUpdates,
allApps,
focusOnApps,
appWildcards,
isFullstack
});
// WebStorm
let isWebStorm = updateWebStorem({
userUpdates,
allApps,
focusOnApps,
appWildcards,
isFullstack
});
if (!devMode) {
// only when not specifying a dev mode
const workspaceUpdates: any = {
'**/node_modules': true,
'**/hooks': true,
// '**/apps/nativescript-*/src/package.json': false,
'**/apps/nativescript-*/hooks': true,
'**/apps/nativescript-*/platforms': true,
'**/apps/nativescript-*/report': true,
'**/apps/nativescript-*/src/**/*.js': {
when: '$(basename).ts'
},
'**/apps/nativescript-*/src/**/*.d.ts': {
when: '$(basename).ts'
},
'**/apps/nativescript-*/src/**/*.css': {
when: '$(basename).scss'
},
// also add groupByName support
// '**/apps/*-nativescript/src/package.json': false,
'**/apps/*-nativescript/hooks': true,
'**/apps/*-nativescript/platforms': true,
'**/apps/*-nativescript/report': true,
'**/apps/*-nativescript/app/**/*.js': {
when: '$(basename).ts'
},
'**/apps/*-nativescript/src/**/*.d.ts': {
when: '$(basename).ts'
},
'**/apps/*-nativescript/src/**/*.css': {
when: '$(basename).scss'
},
// libs/xplat
'**/libs/**/*.js': {
when: '$(basename).ts'
},
'**/libs/**/*.d.ts': {
when: '$(basename).ts'
},
'**/xplat/**/*.js': {
when: '$(basename).ts'
},
'**/xplat/**/*.d.ts': {
when: '$(basename).ts'
}
};
if (isVsCode) {
updateVSCode({
workspaceUpdates
});
}
if (isWebStorm) {
}
}
} catch (err) {
// console.warn('IDE Settings could not be updated at this time:', err);
}
return tree;
};
}
export function updateVSCode(options: {
userUpdates?: any;
workspaceUpdates?: any;
allApps?: string[];
focusOnApps?: string[];
appWildcards?: string[];
isFullstack?: boolean;
}) {
// VS Code support
let isVsCode: boolean;
const isMac = process.platform == 'darwin';
if (options.userUpdates) {
/**
* User settings
*/
// const homedir = os.homedir();
// console.log('os.homedir():',homedir);
let userSettingsVSCodePath = isMac
? process.env.HOME +
`/Library/Application Support/Code/User/settings.json`
: '/var/local/Code/User/settings.json';
const windowsHome = process.env.APPDATA;
if (windowsHome) {
userSettingsVSCodePath = join(
windowsHome,
'Code',
'User',
'settings.json'
);
}
// console.log('userSettingsVSCodePath:',userSettingsVSCodePath);
isVsCode = existsSync(userSettingsVSCodePath);
let vscodeCreateSettingsNote = `It's possible you don't have a user settings.json yet. If so, open VS Code User settings and save any kind of setting to have it created.`;
// console.log('isVsCode:',isVsCode);
if (isVsCode) {
const userSettings = readFileSync(userSettingsVSCodePath, 'UTF-8');
if (userSettings) {
const userSettingsJson = jsonParse(userSettings);
let exclude = userSettingsJson['files.exclude'];
if (!exclude) {
exclude = {};
}
let searchExclude = userSettingsJson['search.exclude'];
if (!searchExclude) {
searchExclude = {};
}
userSettingsJson['files.exclude'] = Object.assign(
exclude,
options.userUpdates
);
userSettingsJson['search.exclude'] = Object.assign(
searchExclude,
options.userUpdates
);
if (options.allApps.length) {
// always reset specific app filters
for (const app of options.allApps) {
delete userSettingsJson['files.exclude'][app];
delete userSettingsJson['search.exclude'][app];
}
}
if (
!options.isFullstack &&
options.focusOnApps.length &&
options.allApps.length
) {
// when focusing on projects, clear all specific app wildcards first if they exist
for (const wildcard of options.appWildcards) {
delete userSettingsJson['files.exclude'][wildcard];
delete userSettingsJson['search.exclude'][wildcard];
}
for (const focusApp of options.focusOnApps) {
userSettingsJson['files.exclude'][focusApp] = false;
userSettingsJson['search.exclude'][focusApp] = false;
}
// ensure all other apps are excluded (except for the one that's being focused on)
for (const app of options.allApps) {
if (!options.focusOnApps.includes(app)) {
userSettingsJson['files.exclude'][app] = true;
userSettingsJson['search.exclude'][app] = true;
}
}
}
writeFileSync(
userSettingsVSCodePath,
serializeJson(userSettingsJson)
);
} else {
console.warn(
`Warning: xplat could not read your VS Code settings.json file therefore development mode has not been set. ${vscodeCreateSettingsNote}`
);
}
} else {
console.log(
`Note to VS Code users: no development mode set. xplat could not find any VS Code settings in the standard location: ${userSettingsVSCodePath} ${vscodeCreateSettingsNote}`
);
}
} else {
/**
* Workspace settings
*/
const workspaceSettingsPath = join(
process.cwd(),
'.vscode',
'settings.json'
);
// console.log('workspaceSettingsPath:',workspaceSettingsPath);
let workspaceSettingsJson: any = {};
if (existsSync(workspaceSettingsPath)) {
const workspaceSettings = readFileSync(workspaceSettingsPath, 'UTF-8');
workspaceSettingsJson = jsonParse(workspaceSettings);
const exclude = workspaceSettingsJson['files.exclude'];
workspaceSettingsJson['files.exclude'] = Object.assign(
exclude,
options.workspaceUpdates
);
} else {
// console.log('creating workspace settings...');
mkdirSync('.vscode');
workspaceSettingsJson['files.exclude'] = options.workspaceUpdates;
}
writeFileSync(
workspaceSettingsPath,
serializeJson(workspaceSettingsJson)
);
}
return isVsCode;
}
export function updateWebStorem(options: {
userUpdates?: any;
workspaceUpdates?: any;
allApps?: string[];
focusOnApps?: string[];
appWildcards?: string[];
isFullstack?: boolean;
isExcluding?: boolean;
}) {
let isWebStorm = false;
// list preferences to get correct webstorm prefs file
// let preferencesFolder = isMac
// ? process.env.HOME +
// `/Library/Preferences`
// : __dirname;
// if (windowsHome) {
// preferencesFolder = windowsHome;
// }
// const prefs = fs.readdirSync(preferencesFolder).filter(f => fs.statSync(join(preferencesFolder, f)).isDirectory());
// find first one
// TODO: user may have multiple version installed (or at least older versions) so may need to handle if multiples
// let webStormPrefFolderName = prefs.find(f => f.indexOf('WebStorm20') > -1);
// if (webStormPrefFolderName) {
// isWebStorm = true;
// webStormPrefFolderName = webStormPrefFolderName.split('/').slice(-1)[0];
// // console.log('webStormPrefFolderName:',webStormPrefFolderName);
// // ensure folders are excluded from project view
// let projectViewWebStormPath =
// isMac
// ? process.env.HOME +
// `/Library/Preferences/${webStormPrefFolderName}/options/projectView.xml`
// : join(__dirname, webStormPrefFolderName, 'config');
// if (windowsHome) {
// projectViewWebStormPath = join(windowsHome, webStormPrefFolderName, 'config');
// }
// let projectView = fs.readFileSync(projectViewWebStormPath, "UTF-8");
// if (projectView) {
// // console.log('projectView:', projectView);
// xml2js.parseString(projectView, (err, settings) => {
// // console.log(util.inspect(settings, false, null));
// if (settings && settings.application && settings.application.component && settings.application.component.length) {
// const builder = new xml2js.Builder({ headless: true });
// const sharedSettingsIndex = (<Array<any>>settings.application.component).findIndex(c => c.$.name === 'ProjectViewSharedSettings');
// if (sharedSettingsIndex > -1) {
// const sharedSettings = settings.application.component[sharedSettingsIndex];
// if (sharedSettings.option && sharedSettings.option.length) {
// const showExcludedFilesIndex = sharedSettings.option.findIndex(o => o.$.name === 'showExcludedFiles');
// if (showExcludedFilesIndex > -1) {
// settings.application.component[sharedSettingsIndex].option[showExcludedFilesIndex].$.value = `${!isExcluding}`;
// } else {
// settings.application.component[sharedSettingsIndex].option.push(webStormExcludedViewNode(isExcluding));
// }
// } else {
// settings.application.component[sharedSettingsIndex].option = [
// webStormExcludedViewNode(isExcluding)
// ];
// }
// settings = builder.buildObject(settings);
// } else {
// (<Array<any>>settings.application.component).push({
// $: 'ProjectViewSharedSettings',
// option: [
// webStormExcludedViewNode(isExcluding)
// ]
// });
// settings = builder.buildObject(settings);
// }
// } else {
// // create projectView.xml
// settings = createWebStormProjectView(isExcluding);
// }
// // modify projectView
// // console.log('settings:', settings);
// fs.writeFileSync(
// projectViewWebStormPath,
// settings
// );
// });
// } else {
// // create projectView.xml
// fs.writeFileSync(
// projectViewWebStormPath,
// createWebStormProjectView(isExcluding)
// );
// }
// }
return isWebStorm;
}
export function updatePrettierIgnore(content: string) {
return (tree: Tree) => {
const prettierFileName = '.prettierignore';
if (tree.exists(prettierFileName)) {
let prettier = tree.read(prettierFileName)!.toString('utf-8');
if (prettier) {
// update prettier rules
prettier = `${prettier}\n${content}`;
// output.log({
// title: 'Note:',
// bodyLines: [
// `Updating "${prettierFileName}" with a few important extra rules. You may double-check the contents afterwards to ensure they meet your satisfaction.`
// ]
// });
tree.overwrite(prettierFileName, prettier);
}
}
return tree;
};
}
export function addPackageInstallTask(options: Schema) {
return (tree: Tree, context: SchematicContext) => {
// let packageTask;
if (!options.skipInstall) {
// packageTask = context.addTask(
// new NodePackageInstallTask() //options.directory)
// );
context.addTask(new NodePackageInstallTask());
}
};
}
}
export namespace XplatComponentHelpers {
export interface Schema {
name: string;
/**
* Target feature. Default is 'ui' if none specified.
*/
feature?: string;
/**
* Group it in a subfolder of the target feature
*/
subFolder?: string;
/**
* Target apps
*/
projects?: string;
/**
* Only generate for specified projects and ignore shared code
*/
onlyProject?: boolean;
/**
* Target platforms
*/
platforms?: string;
framework?: string;
/**
* Create a base component for maximum cross platform sharing
*/
createBase?: boolean;
/**
* Schematic processing helpers
*/
needsIndex?: boolean;
/**
* Skip formatting
*/
skipFormat?: boolean;
/**
* testing helper
*/
isTesting?: boolean;
}
export function prepare(
options: Schema
): XplatHelpers.IXplatGeneratorOptions {
if (!options.name) {
throw new Error(generateOptionError('component'));
}
// reset module globals
options.needsIndex = false;
let featureName: string;
let projectNames = null;
let platforms = [];
if (options.feature) {
featureName = options.feature.toLowerCase();
}
const projects = options.projects;
if (projects) {
options.onlyProject = true;
if (!featureName) {
// no feature targeted, default to shared
featureName = 'shared';
}
// building feature in shared code and in projects
projectNames = sanitizeCommaDelimitedArg(projects);
for (const name of projectNames) {
const projectParts = name.split('-');
const platPrefix = projectParts[0];
const platSuffix = projectParts.pop();
if (
supportedPlatforms.includes(platPrefix) &&
!platforms.includes(platPrefix)
) {
// if project name is prefixed with supported platform and not already added
platforms.push(platPrefix);
} else if (
supportedPlatforms.includes(platSuffix) &&
!platforms.includes(platSuffix)
) {
platforms.push(platSuffix);
}
}
} else if (options.platforms) {
if (!featureName) {
// no feature targeted, default to ui
featureName = 'ui';
}
// building feature in shared code only
platforms = sanitizeCommaDelimitedArg(options.platforms);
}
if (platforms.length === 0) {
let error = projects
? platformAppPrefixError()
: generatorError('component');
throw new Error(optionsMissingError(error));
}
return { featureName, projectNames, platforms };
}
}
export namespace XplatFeatureHelpers {
export interface Schema {
name: string;
/**
* Target apps
*/
projects?: string;
/**
* Target platforms
*/
platforms?: string;
framework?: string;
/**
* Only generate for specified projects and ignore shared code
*/
onlyProject?: boolean;
/**
* Only generate the module and ignore default component creation
*/
onlyModule?: boolean;
/**
* Configure routing
*/
routing?: boolean;
/**
* Create base component for maximum code sharing
*/
createBase?: boolean;
/**
* Add link to route for sandbox
*/
adjustSandbox?: boolean;
/**
* Skip formatting
*/
skipFormat?: boolean;
/**
* testing helper
*/
isTesting?: boolean;
}
export function prepare(
options: Schema
): XplatHelpers.IXplatGeneratorOptions {
if (!options.name) {
throw new SchematicsException(
`You did not specify the name of the feature you'd like to generate. For example: nx g @nstudio/angular:feature my-feature`
);
}
const featureName = options.name.toLowerCase();
let projects = options.projects;
let projectNames: Array<string>;
let platforms = [];
if (options.adjustSandbox) {
// when adjusting sandbox for the feature, turn dependent options on
// for convenience also setup some default fallbacks to avoid requiring so many options
// sandbox flags are meant to be quick and convenient
options.onlyProject = true;
options.routing = true;
if (!projects) {
if (!options.platforms) {
// default to {N} sandbox
projects = 'nativescript-sandbox';
} else {
platforms = sanitizeCommaDelimitedArg(options.platforms);
const projectSandboxNames = [];
// default to project with sandbox name
for (const p of platforms) {
if (supportedSandboxPlatforms.includes(p)) {
projectSandboxNames.push(`${p}-sandbox`);
} else {
throw new SchematicsException(
`The --adjustSandbox flag supports the following at the moment: ${supportedSandboxPlatforms}`
);
}
}
projects = projectSandboxNames.join(',');
}
}
}
if (options.routing && !options.onlyProject) {
throw new SchematicsException(
`When generating a feature with the --routing option, please also specify --onlyProject. Support for shared code routing is under development.`
);
}
if (projects) {
// building feature in shared code and in projects
projectNames = sanitizeCommaDelimitedArg(projects);
for (const name of projectNames) {
const projectParts = name.split('-');
const platPrefix = <PlatformTypes>projectParts[0];
const platSuffix = <PlatformTypes>projectParts.pop();
if (
supportedPlatforms.includes(platPrefix) &&
!platforms.includes(platPrefix)
) {
// if project name is prefixed with supported platform and not already added
platforms.push(platPrefix);
} else if (
supportedPlatforms.includes(platSuffix) &&
!platforms.includes(platSuffix)
) {
// if project name is suffixed with supported platform and not already added
platforms.push(platSuffix);
}
}
} else if (options.platforms) {
// building feature in shared code only
platforms = sanitizeCommaDelimitedArg(options.platforms);
}
if (platforms.length === 0) {
let error = projects
? platformAppPrefixError()
: generatorError('feature');
throw new SchematicsException(optionsMissingError(error));
}
return { featureName, projectNames, platforms };
}
export function addFiles(
options: Schema,
target: string = '',
projectName: string = '',
extra: string = '',
framework?: FrameworkTypes
) {
let moveTo: string;
if (target) {
moveTo = getMoveTo(options, target, projectName, framework);
} else {
target = 'lib';
moveTo = `libs/features/${options.name.toLowerCase()}`;
}
if (!extra) {
// make sure no `null` or `undefined` values get in the string path
extra = '';
}
// console.log('target:', target);
// console.log('addFiles moveTo:', moveTo);
// console.log('add files from:', `${workingDirectory}/${extra}_files`);
return branchAndMerge(
mergeWith(
apply(url(`./${extra}_files`), [
template(getTemplateOptions(options, target, framework)),
move(moveTo)
])
)
);
}
export function adjustBarrelIndex(
options: Schema,
indexFilePath: string
): Rule {
return (tree: Tree) => {
// console.log('adjustBarrelIndex indexFilePath:', indexFilePath);
// console.log('tree.exists(indexFilePath):', tree.exists(indexFilePath));
const indexSource = tree.read(indexFilePath)!.toString('utf-8');
const indexSourceFile = createSourceFile(
indexFilePath,
indexSource,
ScriptTarget.Latest,
true
);
insert(tree, indexFilePath, [
...addGlobal(
indexSourceFile,
indexFilePath,
`export * from './${options.name.toLowerCase()}';`,
true
)
]);
return tree;
};
}
export function getTemplateOptions(
options: Schema,
platform: string,
framework?: FrameworkTypes
) {
const nameParts = options.name.split('-');
let endingDashName = nameParts[0];
if (nameParts.length > 1) {
endingDashName = stringUtils.capitalize(nameParts[nameParts.length - 1]);
}
const xplatFolderName = XplatHelpers.getXplatFoldername(
<PlatformTypes>platform,
framework
);
return {
...(options as any),
...getDefaultTemplateOptions(),
name: options.name.toLowerCase(),
endingDashName,
xplatFolderName
};
}
export function getMoveTo(
options: Schema,
platform: string,
projectName?: string,
framework?: FrameworkTypes
) {
// console.log('getMoveTo framework:', framework);
const xplatFolderName = XplatHelpers.getXplatFoldername(
<PlatformTypes>platform,
framework
);
// console.log('getMoveTo xplatFolderName:', xplatFolderName);
const featureName = options.name.toLowerCase();
let moveTo = `xplat/${xplatFolderName}/features/${featureName}`;
if (projectName) {
let appDir = ['web', 'web-angular'].includes(xplatFolderName)
? '/app'
: '';
moveTo = `apps/${projectName}/src${appDir}/features/${featureName}`;
// console.log('moveTo:', moveTo);
}
return moveTo;
}
}
|
sr3dna/xplat
|
packages/nativescript/src/utils/xplat.ts
|
<gh_stars>0
import { Tree, SchematicContext } from '@angular-devkit/schematics';
import { updateFile, XplatHelpers } from '@nstudio/xplat';
import {
terserWebpackVersion,
nsCoreVersion,
nsThemeCoreVersion,
nodeSassVersion
} from './versions';
export namespace XplatNativeScriptHelpers {
export function updateRootDeps(options: XplatHelpers.Schema) {
return (tree: Tree, context: SchematicContext) => {
return XplatHelpers.updatePackageForXplat(options, {
dependencies: {
'nativescript-theme-core': nsThemeCoreVersion,
'tns-core-modules': nsCoreVersion
},
devDependencies: {
'node-sass': nodeSassVersion,
'terser-webpack-plugin': terserWebpackVersion,
'tns-platform-declarations': nsCoreVersion
}
})(tree, context);
};
}
export function updatePrettierIgnore() {
return XplatHelpers.updatePrettierIgnore(`\n
# xplat added rules
**/*.d.ts
**/apps/**/platforms/**/*
**/App_Resources/**/*
**/apps/nativescript*/hooks/**/*
**/apps/nativescript*/tools/**/*
**/apps/nativescript*/src/assets/*.min.css
**/apps/*nativescript/hooks/**/*
**/apps/*nativescript/tools/**/*
**/apps/*nativescript/src/assets/*.min.css
**/xplat/nativescript*/plugins/**/*`);
}
export function updateGitIgnore() {
return (tree: Tree) => {
const gitIgnorePath = '.gitignore';
let gitIgnore = tree.get(gitIgnorePath).content.toString();
if (gitIgnore) {
if (gitIgnore.indexOf('# nativescript') === -1) {
gitIgnore += `
# nativescript
hooks
`;
}
}
return updateFile(tree, gitIgnorePath, gitIgnore);
};
}
}
|
sr3dna/xplat
|
packages/nativescript-angular/src/utils/versions.ts
|
<reponame>sr3dna/xplat<filename>packages/nativescript-angular/src/utils/versions.ts
export const xplatVersion = '*';
export const nsCoreVersion = '~6.3.0';
export const nsNgVersion = '~8.20.0';
export const nsNgFonticonVersion = '^4.2.0';
export const nodeSassVersion = '^4.12.0';
export const terserWebpackVersion = '~2.2.0';
// in case workspace had not added angular yet
// TODO: move deps to nstudio/xplat to ref from everywhere for all supported framework versions
export const angularVersion = '^8.2.0';
export const ngxTranslateVersion = '~11.0.0';
export const reflectMetadataVersion = '^0.1.12';
export const rxjsVersion = '~6.5.3';
export const zonejsVersion = '~0.10.2';
export const codelyzerVersion = '~5.1.0';
|
sr3dna/xplat
|
packages/electron-angular/migrations/update-8-1-2/update-8-1-2.ts
|
import {
chain,
Rule,
SchematicContext,
Tree
} from '@angular-devkit/schematics';
import { join } from 'path';
import * as fs from 'fs';
import { updateJsonInTree, createOrUpdate } from '@nrwl/workspace';
import { getJsonFromFile, updateJsonFile, output } from '@nstudio/xplat';
import { electronBuilderVersion, electronInstallerDmgVersion, electronPackagerVersion, electronRebuildVersion, electronReloadVersion, electronStoreVersion, electronUpdaterVersion, electronVersion, npmRunAllVersion, waitOnVersion } from '@nstudio/electron';
function updateElectronApps(tree: Tree, context: SchematicContext) {
const nxConfigPath = `nx.json`;
const nxJson = getJsonFromFile(tree, nxConfigPath);
const npmScope = nxJson.npmScope;
const appsDir = tree.getDir('apps');
const appFolders = appsDir.subdirs;
const cwd = process.cwd();
const indexPath = join(
cwd,
'node_modules/@nstudio/electron-angular/src/schematics/application/_files/src/index.ts__tmpl__'
);
// console.log('webpackConfigPath:', webpackConfigPath);
const indexContent = fs.readFileSync(indexPath, 'UTF-8');
const servicePath = join(
cwd,
'node_modules/@nstudio/electron-angular/src/schematics/xplat/_files/core/services/electron.service.ts__tmpl__'
);
// console.log('webpackConfigPath:', webpackConfigPath);
let electronService = fs.readFileSync(servicePath, 'UTF-8');
electronService = electronService.replace(/<%= npmScope %>/ig, npmScope);
const appsNames = [];
// update electron apps and configs
for (const dir of appFolders) {
// console.log(dir);
if (
dir.indexOf('nativescript-') === 0 ||
dir.indexOf('-nativescript') === 0
) {
const appDir = `${appsDir.path}/${dir}`;
// console.log('appDir:', appDir);
appsNames.push(dir);
createOrUpdate(tree, `${appDir}/src/index.ts`, indexContent);
createOrUpdate(tree, `xplat/electron/core/services/electron.service.ts`, electronService);
}
output.log({
title: 'Migration Note:',
bodyLines: [
`The following Electron apps have been updated to 7: ${appsNames}.`
]
});
}
return tree;
}
function updateRootPackage(tree: Tree, context: SchematicContext) {
return updateJsonInTree('package.json', json => {
json.devDependencies = json.devDependencies || {};
json.devDependencies = {
...json.devDependencies,
electron: electronVersion,
'electron-builder': electronBuilderVersion,
'electron-rebuild': electronRebuildVersion,
'electron-installer-dmg': electronInstallerDmgVersion,
'electron-packager': electronPackagerVersion,
'electron-reload': electronReloadVersion,
'electron-store': electronStoreVersion,
'electron-updater': electronUpdaterVersion,
'npm-run-all': npmRunAllVersion,
'wait-on': waitOnVersion
};
return json;
})(tree, context);
}
export default function(): Rule {
return chain([updateElectronApps, updateRootPackage]);
}
|
sr3dna/xplat
|
packages/xplat/src/utils/versions.ts
|
export const xplatVersion = '*';
export const nxVersion = '~8.8.0';
|
sr3dna/xplat
|
packages/nativescript/src/utils/versions.ts
|
export const xplatVersion = '*';
export const nsCoreVersion = '~6.3.0';
export const nsThemeCoreVersion = '^1.0.4';
export const nodeSassVersion = '^4.12.0';
export const terserWebpackVersion = '~2.2.0';
|
davicotico/SortableRows
|
lib/index.d.ts
|
<filename>lib/index.d.ts
/**
* Draggable and sortable table rows. The output is an array of objects with a position attribute on each object.
* @author <NAME>
* @version 1.1.1
* @license MIT
*/
declare class SortableRows {
protected table: HTMLTableElement;
protected tbody: HTMLTableSectionElement;
protected currRow: HTMLTableRowElement | null;
protected dragElem: HTMLTableRowElement | null;
protected startX: number;
protected startY: number;
protected moveX: number;
protected moveY: number;
protected isDragged: boolean;
constructor(id: string);
protected init(): void;
protected onStartDragging(event: MouseEvent | TouchEvent): void;
protected onMove(event: MouseEvent | TouchEvent): void;
protected onEndDragging(event: MouseEvent | TouchEvent): void;
protected bindEvents(): void;
protected swapRow(row: HTMLTableRowElement, index: number): void;
protected moveRow(x: number, y: number): void;
protected addDraggableRow(target: HTMLTableRowElement): void;
protected getRows(): NodeListOf<HTMLTableRowElement>;
protected getTargetRow(target: HTMLTableRowElement): HTMLTableRowElement | null | undefined;
protected getCoords(event: MouseEvent | TouchEvent): {
x: number;
y: number;
};
protected getStyle(target: Element, styleName: string): string;
protected isIntersecting(min0: number, max0: number, min1: number, max1: number): boolean;
getData(): {
position: number;
}[];
}
export { SortableRows };
//# sourceMappingURL=index.d.ts.map
|
davicotico/SortableRows
|
src/index.ts
|
<gh_stars>1-10
/**
* Draggable and sortable table rows. The output is an array of objects with a position attribute on each object.
* @author <NAME>
* @version 1.1.1
* @license MIT
*/
class SortableRows {
protected table: HTMLTableElement;
protected tbody: HTMLTableSectionElement;
protected currRow: HTMLTableRowElement | null = null;
protected dragElem: HTMLTableRowElement | null = null;
protected startX = 0;
protected startY = 0;
protected moveX = 0;
protected moveY = 0;
protected isDragged = false;
constructor(id: string) {
this.table = document.getElementById(id) as HTMLTableElement;
this.tbody = this.table.querySelector("tbody") as HTMLTableSectionElement;
if (this.table == null) {
throw `You called the SortableRows constructor with "${id}" ID, but there is no such element in the document.`;
}
if (this.table.tagName.toLowerCase() != "table") {
throw "The selected element is not a <table>.";
}
this.table.classList.add("draggable-table");
this.init();
}
protected init(): void {
this.bindEvents();
}
protected onStartDragging(event: MouseEvent | TouchEvent): void{
if (event instanceof MouseEvent) {
if (event.button != 0) return;
}
let target = this.getTargetRow(event.target as HTMLTableRowElement);
if (target) {
this.currRow = target;
this.addDraggableRow(target);
this.currRow.classList.add("is-dragging");
let coords = this.getCoords(event);
this.startX = coords.x;
this.startY = coords.y;
this.isDragged = true;
}
}
protected onMove(event: MouseEvent | TouchEvent): void {
if (!this.isDragged) return;
let coords = this.getCoords(event);
this.moveX = coords.x - this.startX;
this.moveY = coords.y - this.startY;
this.moveRow(this.moveX, this.moveY);
}
protected onEndDragging(event: MouseEvent | TouchEvent): void {
if (!this.isDragged) return;
this.currRow?.classList.remove("is-dragging");
this.table.removeChild(this.dragElem as Node);
this.dragElem = null;
this.isDragged = false;
}
protected bindEvents(): void {
this.table.addEventListener("touchstart", (e) => this.onStartDragging(e));
this.table.addEventListener("touchmove", (e) => this.onMove(e));
this.table.addEventListener("touchend", (e) => this.onEndDragging(e));
this.table.addEventListener("mousedown", (e) => this.onStartDragging(e));
this.table.addEventListener("mousemove", (e) => this.onMove(e));
this.table.addEventListener("mouseup", (e) => this.onEndDragging(e));
}
protected swapRow(row: HTMLTableRowElement, index: number): void {
let currIndex = Array.from(this.tbody.children).indexOf(this.currRow as Element),
row1 = currIndex > index ? this.currRow : row,
row2 = currIndex > index ? row : this.currRow;
this.tbody.insertBefore(row1 as Node, row2);
}
protected moveRow(x: number, y: number): void {
var dragElem: HTMLTableRowElement = this.dragElem as HTMLTableRowElement;
dragElem.style.transform = "translate3d(" + x + "px, " + y + "px, 0)";
let dPos = dragElem.getBoundingClientRect(),
currStartY = dPos.y,
currEndY = currStartY + dPos.height,
rows = this.getRows();
for (var i = 0; i < rows.length; i++) {
let rowElem = rows[i];
let rowSize = rowElem.getBoundingClientRect(),
rowStartY = rowSize.y,
rowEndY = rowStartY + rowSize.height;
if (
this.currRow !== rowElem &&
this.isIntersecting(currStartY, currEndY, rowStartY, rowEndY)
) {
if (Math.abs(currStartY - rowStartY) < rowSize.height / 2)
this.swapRow(rowElem, i);
}
}
}
protected addDraggableRow(target: HTMLTableRowElement): void {
this.dragElem = target.cloneNode(true) as HTMLTableRowElement;
this.dragElem.classList.add("draggable-table-tr");
this.dragElem.style.height = this.getStyle(target, "height");
this.dragElem.style.background = this.getStyle(target, "background-color");
for (var i = 0; i < target.children.length; i++) {
let oldTD = target.children[i];
let newTD = this.dragElem.children[i] as HTMLElement;
newTD.style.width = this.getStyle(oldTD, "width");
newTD.style.height = this.getStyle(oldTD, "height");
newTD.style.padding = this.getStyle(oldTD, "padding");
newTD.style.margin = this.getStyle(oldTD, "margin");
}
this.table.appendChild(this.dragElem);
let tPos = target.getBoundingClientRect(),
dPos = this.dragElem.getBoundingClientRect();
this.dragElem.style.bottom = dPos.y - tPos.y - tPos.height + "px";
this.dragElem.style.left = "-1px";
this.table.dispatchEvent(
new MouseEvent("mousemove", {
view: window,
cancelable: true,
bubbles: true,
})
);
}
protected getRows(): NodeListOf<HTMLTableRowElement> {
return this.table.querySelectorAll("tbody tr");
}
protected getTargetRow(target: HTMLTableRowElement): HTMLTableRowElement | null | undefined {
let elemName = target.tagName.toLowerCase();
if (elemName == "tr") return target;
if (elemName == "td") return target.closest("tr");
}
protected getCoords(event: MouseEvent | TouchEvent): { x: number; y: number; } {
let x = 0, y = 0;
if (event instanceof MouseEvent) {
x = event.clientX;
y = event.clientY;
} else {
x = event.touches[0].clientX;
y = event.touches[0].clientY;
}
return { x, y };
}
protected getStyle(target: Element, styleName: string): string {
let compStyle = getComputedStyle(target);
return compStyle.getPropertyValue(styleName);
}
protected isIntersecting(min0: number, max0: number, min1: number, max1: number): boolean {
return (
Math.max(min0, max0) >= Math.min(min1, max1) &&
Math.min(min0, max0) <= Math.max(min1, max1)
);
}
public getData(): { position: number; }[] {
var output = [];
var table = this.table;
for (let ib = 0; ib < table.tBodies.length; ib++) {
let tbody = table.tBodies[ib];
for (let i = 0; i < tbody.rows.length; i++) {
let filaDataset = tbody.rows.item(i)?.dataset;
output.push({ position: i, ...filaDataset });
}
}
return output;
}
}
export { SortableRows };
|
pierophp/node-queue-manager
|
src/jobs/job.abstract.ts
|
import { QueueManagerOptions } from '../queue.manager.options';
import { QueueAbstract } from '../queue.abstract';
export abstract class JobAbstract {
protected options: QueueManagerOptions;
constructor(options: QueueManagerOptions) {
this.options = options;
}
public abstract async listen(queues: QueueAbstract, callback?: Function);
public async listenAll(queues: QueueAbstract[], callback?: Function) {
const queuesPromises: Promise<QueueAbstract>[] = [];
for (const queue of queues) {
queuesPromises.push(this.listen(queue, callback));
}
await Promise.all(queuesPromises);
}
}
|
pierophp/node-queue-manager
|
src/jobs/sync.job.ts
|
import { JobInterface } from '../contracts/job.interface';
import { QueueAbstract } from '../queue.abstract';
import { JobAbstract } from './job.abstract';
import { JobResponse } from './job.response';
import { QueueManagerOptions } from '../queue.manager.options';
export class SyncJob extends JobAbstract implements JobInterface {
constructor(options: QueueManagerOptions) {
super(options);
}
public async publish(queue: QueueAbstract): Promise<JobResponse> {
await queue.run();
return new JobResponse({ id: null, queue });
}
public async listen(queue: QueueAbstract, callback?: Function): Promise<any> {
}
public async close(): Promise<any> {
}
}
|
pierophp/node-queue-manager
|
src/contracts/job.interface.ts
|
import { QueueAbstract } from '../queue.abstract';
import { JobResponse } from '../jobs/job.response';
export interface JobInterface {
publish(queue: QueueAbstract): Promise<JobResponse>;
listen(queue: QueueAbstract, callback?: Function): Promise<any>;
listenAll(queue: QueueAbstract[], callback?: Function): Promise<any>;
close(): Promise<any>;
}
|
pierophp/node-queue-manager
|
__tests__/queues/example.queue.ts
|
import { QueueAbstract } from '../../src/queue.abstract';
export class ExampleQueue extends QueueAbstract {
public queueExecuted: boolean = false;
public getName(): string {
return 'example.queue';
}
public async run(data?: any): Promise<any> {
this.queueExecuted = true;
return 'example.queue.run';
}
public getConcurrency(): number {
return 3;
}
}
|
pierophp/node-queue-manager
|
src/jobs/job.response.ts
|
import { QueueAbstract } from '../queue.abstract';
export class JobResponse {
public id: number | string;
public queue: QueueAbstract;
constructor(data) {
Object.keys(data).forEach((key) => {
this[key] = data[key];
});
}
}
|
pierophp/node-queue-manager
|
src/queue.abstract.ts
|
export abstract class QueueAbstract {
protected data: any = {};
public setData(data: any) {
this.data = data;
}
public getData(): any {
return this.data;
}
public abstract getName(): string;
public abstract async run(data?: any): Promise<any>;
public getConcurrency(): number {
return 1;
}
}
|
pierophp/node-queue-manager
|
src/queue.manager.ts
|
<gh_stars>1-10
import { merge } from 'lodash';
import { JobInterface } from './contracts/job.interface';
import { QueueAbstract } from './queue.abstract';
import { QueueManagerOptions } from './queue.manager.options';
import { BullJob } from './jobs/bull.job';
import { SyncJob } from './jobs/sync.job';
import { JobResponse } from './jobs/job.response';
const jobTypes = {
bull: BullJob,
sync: SyncJob,
};
export class QueueManager {
protected job: JobInterface;
protected options: QueueManagerOptions;
protected defaultOptions = {
redis: {
port: 6379,
},
type: 'bull',
};
constructor(queueManagerOptions?: QueueManagerOptions) {
if (!queueManagerOptions) {
queueManagerOptions = new QueueManagerOptions();
}
queueManagerOptions = this.mergeOptions(queueManagerOptions);
this.options = queueManagerOptions;
const jobName: string = queueManagerOptions.type || this.defaultOptions.type;
this.job = new jobTypes[jobName](queueManagerOptions);
}
protected mergeOptions(options: QueueManagerOptions): QueueManagerOptions {
return merge(new QueueManagerOptions(), this.defaultOptions, options);
}
public async publish(queue: QueueAbstract): Promise<JobResponse> {
return await this.job.publish(queue);
}
public async listen(queue: QueueAbstract, callback?: Function): Promise<void> {
await this.job.listen(queue, callback);
}
public async listenAll(queues: QueueAbstract[], callback?: Function): Promise<void> {
await this.job.listenAll(queues, callback);
}
public async close(): Promise<void> {
await this.job.close();
}
}
|
pierophp/node-queue-manager
|
__tests__/jobs/bull.job.test.ts
|
import { expect } from 'chai';
import { QueueManager } from '../../src/queue.manager';
import { ExampleQueue } from '../queues/example.queue';
describe('BullJobTest', function () {
this.timeout(5000);
const queueManager = new QueueManager({
redis: {
host: 'redis',
},
type: 'bull',
});
it('publish', async () => {
const exampleQueue = new ExampleQueue();
exampleQueue.setData({
name: 'test',
});
const queueResponse = await queueManager.publish(exampleQueue);
expect(queueResponse.id).not.null;
await queueManager.listen(exampleQueue, (queueExecutedResponse) => {
expect(queueResponse.id).to.equal(queueExecutedResponse.id);
expect(JSON.stringify(queueResponse.queue.getData())).to.equal(JSON.stringify({
name: 'test',
}));
queueManager.close();
});
});
});
|
pierophp/node-queue-manager
|
src/queue.manager.options.ts
|
<reponame>pierophp/node-queue-manager
export class QueueManagerOptions {
public redis?: {
port?: number,
host: string,
};
public type?: 'bull' | 'sync';
}
|
pierophp/node-queue-manager
|
src/jobs/bull.job.ts
|
<reponame>pierophp/node-queue-manager<filename>src/jobs/bull.job.ts
import * as Bull from 'bull';
import { JobInterface } from '../contracts/job.interface';
import { QueueAbstract } from '../queue.abstract';
import { JobAbstract } from './job.abstract';
import { JobResponse } from './job.response';
import { RedisNotConfiguredError } from '../errors/redis.not.configured.error';
import { QueueManagerOptions } from '../queue.manager.options';
const instances = {};
export class BullJob extends JobAbstract implements JobInterface {
protected closed: boolean = false;
constructor(options: QueueManagerOptions) {
super(options);
}
protected getInstance(name: string): any {
if (instances[name]) {
return instances[name];
}
if (!this.options.redis) {
throw new RedisNotConfiguredError();
}
const bullQueue = new Bull(name, {
redis: {
port: this.options.redis.port,
host: this.options.redis.host,
},
});
instances[name] = bullQueue;
return bullQueue;
}
public async publish(queue: QueueAbstract): Promise<JobResponse> {
const bullQueue = this.getInstance(queue.getName());
const bullJobReponse = await bullQueue.add(queue.getData());
return new JobResponse({ id: bullJobReponse.id, queue });
}
public async listen(queue: QueueAbstract, callback?: Function): Promise<any> {
const bullQueue = this.getInstance(queue.getName());
return new Promise((done) => {
bullQueue.process(queue.getConcurrency(), async (job, jobDone) => {
queue.setData(job.data);
await queue.run();
if (callback) {
callback(new JobResponse({ id: job.id, queue }));
}
jobDone();
});
const interval = setInterval(() => {
if (this.closed) {
done();
clearInterval(interval);
}
}, 1000);
});
}
public async close(): Promise<any> {
for (const instance of Object.keys(instances)) {
await instances[instance].close();
}
this.closed = true;
}
}
|
pierophp/node-queue-manager
|
src/errors/redis.not.configured.error.ts
|
export class RedisNotConfiguredError extends Error {
}
|
pierophp/node-queue-manager
|
__tests__/jobs/sync.job.test.ts
|
import { expect } from 'chai';
import { QueueManager } from '../../src/queue.manager';
import { ExampleQueue } from '../queues/example.queue';
describe('SyncJobTest', function () {
this.timeout(5000);
const queueManager = new QueueManager({
type: 'sync',
});
it('publish', async () => {
const exampleQueue = new ExampleQueue();
exampleQueue.setData({
name: 'test',
});
const queueResponse: any = await queueManager.publish(exampleQueue);
expect(queueResponse.queue.queueExecuted).not.null;
});
});
|
pierophp/node-queue-manager
|
src/index.ts
|
<reponame>pierophp/node-queue-manager<filename>src/index.ts
import { QueueManager } from './queue.manager';
import { QueueAbstract } from './queue.abstract';
import { QueueManagerOptions } from './queue.manager.options';
export { QueueManager, QueueManagerOptions, QueueAbstract } ;
|
Pondorasti/tailwindcss-snippets
|
data/snippets/TextShimmer.tsx
|
const TextShimmer: ISnippet = {
title: "Shimmer",
editLink: "https://github.com/Pondorasti/tailwindcss-snippets/blob/main/data/snippets/TextShimmer.tsx",
playgroundLink: "https://play.tailwindcss.com/iOPPOIJo2q",
source: (
<div className="animate-text-shimmer bg-clip-text text-transparent bg-[linear-gradient(110deg,#e2e8f0,45%,#1e293b,55%,#e2e8f0)] bg-[length:250%_100%]">
Text Shimmer Effect
</div>
),
animation: `keyframes: {
"text-shimmer": {
from: { backgroundPosition: "0 0" },
to: { backgroundPosition: "-200% 0" },
},
},
animation: {
"text-shimmer": "text-shimmer 2.5s ease-out infinite alternate",
},`,
}
export default TextShimmer
|
Pondorasti/tailwindcss-snippets
|
data/snippets/TextTransformColor.tsx
|
const TextTransformColor: ISnippet = {
title: "Text Transform & Color",
editLink: "https://github.com/Pondorasti/tailwindcss-snippets/blob/main/data/snippets/TextTransformColor.tsx",
playgroundLink: "https://play.tailwindcss.com/YQEPZafzdC",
source: (
<div className="group text-gray-200 hover:text-sky-600 transition ease-in-out duration-200">
Hover over me{" "}
<span
aria-hidden="true"
className="inline-block translate-x-0 group-hover:translate-x-1 transition-transform ease-in-out duration-200"
>
→
</span>
</div>
),
}
export default TextTransformColor
|
Pondorasti/tailwindcss-snippets
|
data/snippets.tsx
|
<reponame>Pondorasti/tailwindcss-snippets<filename>data/snippets.tsx
import UnderlineLeftRight from "./snippets/UnderlineLeftRight"
import Pulse from "./snippets/Pulse"
import KeyboardButton from "./snippets/KeyboardButton"
import UnderlayMarker from "./snippets/UnderlayMarker"
import UnderlayLeft from "./snippets/UnderlayLeft"
import Spinner from "./snippets/Spinner"
import HoverActiveScaleButton from "./snippets/HoverActiveScaleButton"
import Swing from "./snippets/Swing"
import UnderlineBottomTop from "./snippets/UnderlineBottomTop"
import UnderlayLeftRight from "./snippets/UnderlayLeftRight"
import TextTransformColor from "./snippets/TextTransformColor"
import Shimmer from "./snippets/Shimmer"
import UnderlayExpandingCircle from "./snippets/UnderlayExpandingCircle"
import ThreeDotsLoader from "./snippets/ThreeDotsLoader"
import HoverScaleButton from "./snippets/HoverScaleButton"
import ActiveUnderlineLeftRight from "./snippets/ActiveUnderlineLeftRight"
import FlickUp from "./snippets/FlickUp"
import GradientTilt from "./snippets/GradientTilt"
import BackgroundPulse from "./snippets/BackgroundPulse"
import UnderlineSquiggle from "./snippets/UnderlineSquiggle"
import MaterialTextInput from "./snippets/MaterialTextInput"
import TextShimmer from "./snippets/TextShimmer"
const snippets: ISnippet[] = [
UnderlineLeftRight,
UnderlineBottomTop,
ActiveUnderlineLeftRight,
UnderlineSquiggle,
UnderlayLeft,
UnderlayLeftRight,
UnderlayExpandingCircle,
GradientTilt,
UnderlayMarker,
Swing,
FlickUp,
TextTransformColor,
KeyboardButton,
HoverScaleButton,
HoverActiveScaleButton,
MaterialTextInput,
Spinner,
BackgroundPulse,
ThreeDotsLoader,
Shimmer,
Pulse,
TextShimmer,
]
export default snippets
|
Pondorasti/tailwindcss-snippets
|
components/Card/Card.tsx
|
import { useRef } from "react"
import ReactDOMServer from "react-dom/server"
import * as ContextMenu from "@radix-ui/react-context-menu"
import { CodeIcon, MagicWandIcon, PlayIcon, GitHubLogoIcon } from "@radix-ui/react-icons"
import { useHotkeys } from "react-hotkeys-hook"
import { trackGoal } from "fathom-client"
export default function Card({ source, animation, editLink, playgroundLink }: ISnippet): JSX.Element {
const copySourceRef = useRef<HTMLDivElement>(null)
const copyAnimationRef = useRef<HTMLDivElement>(null)
const openPlaygroundRef = useRef<HTMLDivElement>(null)
const openGithubRef = useRef<HTMLDivElement>(null)
const itemStyle =
"flex items-center px-2 py-2 text-xs rounded-md outline-none cursor-default select-none text-gray-500 focus:bg-white/5 radix-disabled:opacity-50 radix-disabled:cursor-not-allowed transition-colors ease-out duration-200 disabled:opacity-75"
const itemTextStyle = "ml-2 flex-grow text-gray-200"
// Copy Source
useHotkeys("s", () => copySourceRef.current?.click())
function handleCopySource() {
navigator.clipboard.writeText(ReactDOMServer.renderToStaticMarkup(source))
trackGoal("GHMTI4HH", 1)
}
// Copy Animation
useHotkeys("k", () => copyAnimationRef.current?.click())
function handleCopyAnimation() {
navigator.clipboard.writeText(animation || "no custom animation used")
}
// Open in Playground
useHotkeys("p", () => openPlaygroundRef.current?.click())
function handleOpenInPlayground() {
window.open(playgroundLink, "_blank")
}
// Open in Github
useHotkeys("g", () => openGithubRef.current?.click())
function handleOpenInGithub() {
window.open(editLink, "_blank")
}
return (
<ContextMenu.Root>
<ContextMenu.Trigger>
<div className="bg-gray-800/50 ring-1 ring-inset ring-gray-500/20 h-28 w-full rounded-lg flex cursor-context-menu">
<div className="m-auto text-gray-200 select-none">{source}</div>
</div>
</ContextMenu.Trigger>
<ContextMenu.Content className="radix-state-open:animate-fade-in radix-state-closed:animate-fade-out origin-top-left w-52 px-1.5 py-1.5 rounded-lg bg-gray-900/95 backdrop-blur ring-1 ring-inset ring-gray-500/30">
{/* Copy Source */}
<ContextMenu.Item ref={copySourceRef} className={itemStyle} onSelect={() => handleCopySource()}>
<CodeIcon className="mb-px" />
<span className={itemTextStyle}>Copy Source</span>
<kbd>S</kbd>
</ContextMenu.Item>
{/* Copy Animation */}
<ContextMenu.Item
ref={copyAnimationRef}
className={itemStyle}
disabled={!animation}
onSelect={() => handleCopyAnimation()}
>
<MagicWandIcon className="mb-[2px]" />
<span className={itemTextStyle}>Copy Keyframes</span>
<kbd>K</kbd>
</ContextMenu.Item>
<ContextMenu.Separator className="h-px m-1 bg-gray-500/30" />
{/* Open in Playground */}
<ContextMenu.Item
ref={openPlaygroundRef}
className={itemStyle}
disabled={!playgroundLink}
onSelect={() => handleOpenInPlayground()}
>
<PlayIcon className="mb-px" />
<span className={itemTextStyle}>Open in Playground</span>
<kbd>P</kbd>
</ContextMenu.Item>
{/* Open in Github */}
<ContextMenu.Item ref={openGithubRef} className={itemStyle} onSelect={() => handleOpenInGithub()}>
<GitHubLogoIcon className="mb-px" />
<span className={itemTextStyle}>Open in Github</span>
<kbd>G</kbd>
</ContextMenu.Item>
</ContextMenu.Content>
</ContextMenu.Root>
)
}
|
cjcj5438/ts-axios
|
src/API/interface.ts
|
<gh_stars>0
/**
*
*/
export interface ResponseData<T= any> {
code:number
result:T
message:string
}
|
cjcj5438/ts-axios
|
src/API/testApi.ts
|
// import { ResponseData } from './interface'
// import axios from '../axios'
//
// export function getUser<T>() {
// return axios.get<ResponseData<T>>('/somepath')
// .then(res => res.data)
// .catch(err => console.log(err))
//
// }
|
andreiox/fastify-test-drive
|
src/server.ts
|
<reponame>andreiox/fastify-test-drive<gh_stars>0
import dotenv from 'dotenv';
import buildApp from './app';
dotenv.config();
const server = buildApp({
logger: {
level: 'info',
prettyPrint: true,
},
});
const port = +process.env.PORT! || 3000;
server.listen(port, '0.0.0.0', (err, address) => {
if (err) {
console.log(err);
process.exit(1);
}
});
|
andreiox/fastify-test-drive
|
test/app.test.ts
|
<gh_stars>0
import test from 'ava';
import build from '../src/app';
test('GET "/" should return hello world', async t => {
const app = build();
const response = await app.inject({ method: 'GET', url: '/' });
const expected = JSON.stringify({ hello: 'world' });
t.is(response.statusCode, 200);
t.is(response.body, expected);
});
test('POST "/" should return request body', async t => {
const app = build();
const payload = { fastify: 'inject is great' };
const response = await app.inject({ method: 'POST', url: '/', payload });
t.is(response.statusCode, 200);
t.is(response.body, JSON.stringify(payload));
});
test('POST "/body-validation" should return 200 for valid body', async t => {
const app = build();
const payload = { username: 'andreiox', age: 24 };
const response = await app.inject({
method: 'POST',
url: '/body-validation',
payload,
});
t.is(response.statusCode, 200);
t.is(response.body, JSON.stringify(payload));
});
test('POST "/body-validation" should return 400 for invalid body', async t => {
const app = build();
const payload = { username: 'andreiox', age: 'a' };
const response = await app.inject({
method: 'POST',
url: '/body-validation',
payload,
});
t.is(response.statusCode, 400);
t.is(response.json().message, 'body.age should be number');
});
test('POST "/body-validation" should return 400 and multiple error in body', async t => {
const app = build({ ajv: { customOptions: { allErrors: true } } });
const payload = { age: 'a' };
const response = await app.inject({
method: 'POST',
url: '/body-validation',
payload,
});
const expected =
"body should have required property 'username', body.age should be number";
t.is(response.statusCode, 400);
t.is(response.json().message, expected);
});
test('GET "/header-validation" should validate header', async t => {
const app = build();
const response = await app.inject({
method: 'GET',
url: '/header-validation',
headers: {
'super-important-header': 'this is important',
},
});
const expected = 'this is important';
t.is(response.statusCode, 200);
t.is(response.body, expected);
});
test('GET "/header-validation" should return 400 for invalid header', async t => {
const app = build();
const response = await app.inject({ method: 'GET', url: '/header-validation' });
const expected =
"headers should have required property 'super-important-header'";
t.is(response.statusCode, 400);
t.is(response.json().message, expected);
});
test('GET "/query-validation" should validate query param', async t => {
const app = build();
const response = await app.inject({
method: 'GET',
url: '/query-validation',
query: { param1: 'value1' },
});
const expected = { param1: 'value1' };
t.is(response.statusCode, 200);
t.deepEqual(response.json(), expected);
});
test('GET "/query-validation" should return 400 for invalid query param', async t => {
const app = build();
const response = await app.inject({ method: 'GET', url: '/query-validation' });
const expected = "querystring should have required property 'param1'";
t.is(response.statusCode, 400);
t.is(response.json().message, expected);
});
test('POST "/response-schema" should return request body values based on schema', async t => {
const app = build();
const payload = { value1: 'string', value2: true, value3: 'hello' };
const response = await app.inject({
method: 'POST',
url: '/response-schema',
payload,
});
const expected = { ...payload };
delete expected.value3;
t.is(response.statusCode, 200);
t.deepEqual(response.json(), expected);
});
test('GET "/with-error" should lower case the error message', async t => {
const app = build();
const response = await app.inject({ method: 'GET', url: '/with-error' });
const expected = 'hello error!';
t.is(response.statusCode, 500);
t.is(response.body, expected);
});
|
andreiox/fastify-test-drive
|
src/schemas.ts
|
export const userSchema = {
type: 'object',
properties: {
username: { type: 'string' },
age: { type: 'number' },
},
required: ['username', 'age'],
};
export const headerSchema = {
type: 'object',
properties: {
'super-important-header': {
type: 'string',
},
},
required: ['super-important-header'],
};
export const querySchema = {
type: 'object',
properties: {
param1: { type: 'string' },
},
required: ['param1'],
};
export const responseSchema = {
200: {
type: 'object',
properties: {
value1: { type: 'string' },
value2: { type: 'boolean' },
},
},
};
|
andreiox/fastify-test-drive
|
src/app.ts
|
import fastify from 'fastify';
import swagger from 'fastify-swagger';
import * as schemas from './schemas';
import swaggerOptions from './swagger';
export default (opts = {}) => {
const app = fastify(opts);
app.register(swagger, swaggerOptions);
app.setErrorHandler((err, req, res) => {
if (err.validation) return res.status(400).send(err);
return res.status(500).send(err.message.toLowerCase());
});
app.get('/', async (req, res) => {
return { hello: 'world' };
});
app.post('/', async (req, res) => {
return req.body;
});
app.post(
'/body-validation',
{ schema: { body: schemas.userSchema } },
async (req, res) => {
return req.body;
},
);
app.get(
'/header-validation',
{ schema: { headers: schemas.headerSchema } },
async (req, res) => {
return req.headers['super-important-header'];
},
);
app.get(
'/query-validation',
{ schema: { querystring: schemas.querySchema } },
async (req, res) => {
return req.query;
},
);
app.post(
'/response-schema',
{ schema: { response: schemas.responseSchema } },
async (req, res) => {
return req.body;
},
);
app.get('/with-error', async (req, res) => {
throw Error('Hello Error!');
});
app.ready(err => {
if (err) throw err;
app.swagger();
});
return app;
};
|
andreiox/fastify-test-drive
|
src/swagger.ts
|
export default {
routePrefix: '/documentation',
exposeRoute: true,
swagger: {
info: {
title: 'Fastify Test Drive Documentation',
description: 'Taking fastfiy for a spin!',
version: '1.0.0',
},
externalDocs: {
url: 'https://swagger.io',
description: 'Find more info here',
},
host: 'localhost:3000',
schemes: ['http'],
consumes: ['application/json'],
produces: ['application/json'],
},
};
|
koykis/angular-test
|
src/app/components/chart.component.ts
|
<filename>src/app/components/chart.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'simple-chart',
template: '<chart [options]="options"></chart>'
})
export class ChartComponent {
constructor() {
this.options = {
title : { text : 'simple chart' },
series: [{
data: [29.9, 71.5, 106.4, 129.2],
}]
};
}
options: Object;
}
|
kingsingh415/SystemsCapstone
|
src/client/main.ts
|
/**
* Hello world
*/
import {
establishConnection,
establishPayer,
loadProgram,
sayHello,
reportHellos,
reportAccounts,
getArrayOfPosts
} from './hello_world';
async function main() {
console.log("--------------------Solana forum demo--------------------");
console.log("THIS NO LONGER WORKS PROPERLY!!! USE THE UI INSTEAD");
const readlineSync = require('readline-sync');
let options = ["View Posts", "New Post", "Like Post"];
let response = readlineSync.keyInSelect(options, "Choose one (New post assumes you have a valid store)")
// Establish connection to the cluster
await establishConnection();
// Determine who pays for the fees
await establishPayer();
// Load the program if not already loaded
await loadProgram();
switch(response) {
case 0:
// Get accounts owned by the program
// await reportAccounts();
await reportAccounts();
/*
let view = await getArrayOfPosts();
for (var val of view) {
console.log(val);
}
*/
break;
case 1:
// Enter post text
let postBody = readlineSync.question('Enter your post: ', { hideEchoBack: false });
// Say hello to an account
await sayHello(postBody, "post");
// Find out how many times that account has been greeted
await reportHellos();
// Get accounts owned by the program
// await reportAccounts();
/*let postRet = await getArrayOfPosts();
for (var val of postRet) {
console.log(val);
}*/
break;
case 2:
//let choice = readlineSync.question('Enter which post number you would like to send a like to: ', { hideEchoBack: false });
//var num: number = +choice;
//var split = ret[num].split(" - ");
// console.log(split);
//await sayHello(split[2], "like");
// Find out how many times that account has been greeted
await reportHellos();
break
default:
break;
}
console.log('Success');
}
main().then(
() => process.exit(),
err => {
console.error(err);
process.exit(-1);
},
);
|
kingsingh415/SystemsCapstone
|
src/client/hello_world.ts
|
<reponame>kingsingh415/SystemsCapstone
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/ban-ts-comment */
import {
Account,
Connection,
BpfLoader,
BPF_LOADER_PROGRAM_ID,
PublicKey,
LAMPORTS_PER_SOL,
SystemProgram,
TransactionInstruction,
Transaction,
sendAndConfirmTransaction,
} from '@solana/web3.js';
import fs, { read } from 'mz/fs';
// @ts-ignore
import BufferLayout from 'buffer-layout';
const lo = BufferLayout;
import {url, urlTls} from './util/url';
import {Store} from './util/store';
import {newAccountWithLamports} from './util/new-account-with-lamports';
import BaseConverter from 'base-x';
const bs58 = BaseConverter("base58");
/**
* Connection to the network
*/
let connection: Connection;
/**
* Connection to the network
*/
let payerAccount: Account;
/**
* Hello world's program id
*/
let programId: PublicKey;
/**
* Greeted account
*/
let greetedAccount: Account;
const pathToProgram = 'dist/program/helloworld.so';
/**
* Layout of a single post
*/
const postLayout = BufferLayout.struct([
//BufferLayout.u32('numGreets'),
BufferLayout.u8('type'),
BufferLayout.cstr('body'),
]);
/**
* Layout of account data
*/
const accountLayout = BufferLayout.struct([
BufferLayout.u16('numPosts'),
BufferLayout.seq(postLayout, BufferLayout.offset(BufferLayout.u16(), -1), 'posts'),
]);
/**
* Layout of the greeted account data
*/
const greetedAccountDataLayout = BufferLayout.struct([
//BufferLayout.seq(BufferLayout.u8(), 1024, 'account_data'),
BufferLayout.seq(BufferLayout.u8(), 1024, 'account_data'),
]);
function printAccountPosts(d: Buffer) {
const postCount = d.readUInt16LE(0);
console.log("# of posts on account:", postCount);
//const accountData = accountLayout.decode(d);
//console.log(accountData.posts);
// For now, just print with a for loop
let readType = false;
let currentPost = "";
let i = 2;
for(; i < d.length; i++) {
// Stop after reading 2 terminators in a row
if(d.readUInt8(i) == 0 && d.readUInt8(i - 1) == 0) {
return;
}
if(!readType) {
process.stdout.write("Type: " + String.fromCharCode(d.readUInt8(i)));
readType = true;
}
else if(d.readUInt8(i) == 0) {
console.log("\tBody:", currentPost);
currentPost = "";
readType = false;
}
else {
currentPost += String.fromCharCode(d.readUInt8(i));
}
}
console.log("Account has used", i, "out of", d.length, "available bytes");
}
export function arrayOfPosts(d: Buffer, key: PublicKey):string[] {
let readType = false;
let currentPost = "";
let i = 2;
let x = 1;
const postCount = d.readUInt16LE(0);
var ret = new Array("")
for(; i < d.length; i++) {
// Stop after reading 2 terminators in a row
if(d.readUInt8(i) == 0 && d.readUInt8(i - 1) == 0) {
return ret;
}
if(!readType) {
// process.stdout.write("Type: " + String.fromCharCode(d.readUInt8(i)));
currentPost += "Type: " + String.fromCharCode(d.readUInt8(i)) + " - ";
readType = true;
}
else if(d.readUInt8(i) == 0) {
// console.log("\tBody:", currentPost);
let toPush = (x + " - " + currentPost + " - Posted By: " + key);
x++;
ret.push(toPush)
currentPost = "";
readType = false;
}
else {
currentPost += String.fromCharCode(d.readUInt8(i));
}
}
// console.log("Account has used", i, "out of", d.length, "available bytes");
// console.log(ret)
return ret;
}
/**
* Establish a connection to the cluster
*/
export async function establishConnection(): Promise<void> {
connection = new Connection(url, 'singleGossip');
const version = await connection.getVersion();
console.log('Connection to cluster established:', url, version);
}
/**
* Establish an account to pay for everything
*/
export async function establishPayer(): Promise<void> {
if (!payerAccount) {
let fees = 0;
const {feeCalculator} = await connection.getRecentBlockhash();
// Calculate the cost to load the program
const data = await fs.readFile(pathToProgram);
const NUM_RETRIES = 500; // allow some number of retries
fees +=
feeCalculator.lamportsPerSignature *
(BpfLoader.getMinNumSignatures(data.length) + NUM_RETRIES) +
(await connection.getMinimumBalanceForRentExemption(data.length));
// Calculate the cost to fund the greeter account
fees += await connection.getMinimumBalanceForRentExemption(
greetedAccountDataLayout.span,
);
// Calculate the cost of sending the transactions
fees += feeCalculator.lamportsPerSignature * 100; // wag
// Fund a new payer via airdrop
payerAccount = await newAccountWithLamports(connection, fees);
}
const lamports = await connection.getBalance(payerAccount.publicKey);
console.log(
'Using account',
payerAccount.publicKey.toBase58(),
'containing',
lamports / LAMPORTS_PER_SOL,
'Sol to pay for fees',
);
}
/**
* Load the hello world BPF program if not already loaded
*/
export async function loadProgram(): Promise<void> {
const store = new Store();
// Check if the program has already been loaded
let config: any;
try {
config = await store.load('config.json');
programId = new PublicKey(config.programId);
await connection.getAccountInfo(programId);
console.log('Program already loaded to account', programId.toBase58());
} catch (err) {
// try to load the program
// Load the program
console.log('Loading hello world program...');
const data = await fs.readFile(pathToProgram);
const programAccount = new Account();
await BpfLoader.load(
connection,
payerAccount,
programAccount,
data,
BPF_LOADER_PROGRAM_ID,
);
programId = programAccount.publicKey;
console.log('Program loaded to account', programId.toBase58());
}
//if(config.secretKey) {
// console.log("Using existing account with secret key", config.secretKey);
// greetedAccount = new Account(Buffer.from(config.secretKey));
//} else {
console.log("Creating new account");
greetedAccount = new Account();
// Create the greeted account
console.log('Creating account', greetedAccount.publicKey.toBase58(), 'to say hello to');
const space = greetedAccountDataLayout.span;
const lamports = await connection.getMinimumBalanceForRentExemption(
greetedAccountDataLayout.span,
);
const transaction = new Transaction().add(
SystemProgram.createAccount({
fromPubkey: payerAccount.publicKey,
newAccountPubkey: greetedAccount.publicKey,
lamports,
space,
programId,
}),
);
await sendAndConfirmTransaction(
connection,
transaction,
[payerAccount, greetedAccount],
{
commitment: 'singleGossip',
preflightCommitment: 'singleGossip',
},
);
//}
// Save this info for next time
await store.save('config.json', {
url: urlTls,
programId: programId.toBase58(),
publicKey: greetedAccount.publicKey.toBase58(),
secretKey: bs58.encode(greetedAccount.secretKey),
});
}
/**
* Say hello
*/
export async function sayHello(body: string, type: string): Promise<void> {
console.log('Saying hello to', greetedAccount.publicKey.toBase58());
/*
rl.on("close", function() {
console.log("\nBYE BYE !!!");
process.exit(0);
});
*/
//const post = Buffer.from('Ptest\0');
let post = Buffer.from("");
if (type == "post") {
post = Buffer.from('P' + body + '\0');
}
else if (type == "like") {
post = Buffer.from('L' + body + '\0');
}
console.log("Length of post:", post.length);
const instruction = new TransactionInstruction({
keys: [{pubkey: greetedAccount.publicKey, isSigner: true, isWritable: true}],
programId,
data: post,//Buffer.alloc(0), // All instructions are hellos
});
await sendAndConfirmTransaction(
connection,
new Transaction().add(instruction),
[payerAccount, greetedAccount],
{
commitment: 'singleGossip',
preflightCommitment: 'singleGossip',
},
);
}
/**
* Report the number of times the greeted account has been said hello to
*/
export async function reportHellos(): Promise<void> {
const accountInfo = await connection.getAccountInfo(greetedAccount.publicKey);
if (accountInfo === null) {
throw 'Error: cannot find the greeted account';
}
//const info = greetedAccountDataLayout.decode(Buffer.from(accountInfo.data));
/*
console.log(
greetedAccount.publicKey.toBase58(),
'has been greeted',
info.numGreets.toString(),
'times',
);
*/
//console.log(greetedAccount.publicKey.toBase58(), ":");
//console.log("Account data:", info.account_data.toString());
}
/**
* Print given accounts' data
*/
async function printAccountData(account: PublicKey): Promise<void> {
const accountInfo = await connection.getAccountInfo(greetedAccount.publicKey);
if (accountInfo === null) {
throw 'Error: cannot get data for account ' + account.toBase58();
}
//const info = accountLayout.decode(Buffer.from(accountInfo.data));
//console.log("Account has", accountInfo.data.length, "bytes");
printAccountPosts(accountInfo.data);
}
/**
* Report the accounts owned by the program
*/
export async function reportAccounts(): Promise<void> {
const accounts = await connection.getProgramAccounts(programId);
console.log("Accounts owned by program:");
for(let i = 0; i < accounts.length; i++) {
console.log(accounts[i].pubkey.toBase58());
let posts = await getArrayOfPosts(accounts[i].pubkey);
console.log(posts);
}
}
export async function getArrayOfPosts(pk: PublicKey): Promise<string[]> {
const accountInfo = await connection.getAccountInfo(pk);
if (accountInfo === null) {
throw 'Error: cannot get data for account ';
}
if (arrayOfPosts(accountInfo.data, pk) != null) {
return arrayOfPosts(accountInfo.data, pk);
}
else {
let x: string[] = [""];
return x;
}
}
|
nitesh55/assignment-wednesday
|
node_modules/@storybook/api/dist/version.d.ts
|
export declare const version = "5.2.5";
|
nitesh55/assignment-wednesday
|
node_modules/@storybook/addon-knobs/dist/components/types/Checkboxes.d.ts
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { KnobControlConfig, KnobControlProps } from './types';
declare type CheckboxesTypeKnobValue = string[];
export interface CheckboxesTypeKnob extends KnobControlConfig<CheckboxesTypeKnobValue> {
options: Record<string, string>;
}
interface CheckboxesTypeProps extends KnobControlProps<CheckboxesTypeKnobValue>, CheckboxesWrapperProps {
knob: CheckboxesTypeKnob;
}
interface CheckboxesTypeState {
values: CheckboxesTypeKnobValue;
}
interface CheckboxesWrapperProps {
isInline: boolean;
}
export default class CheckboxesType extends Component<CheckboxesTypeProps, CheckboxesTypeState> {
static defaultProps: CheckboxesTypeProps;
static propTypes: {
knob: PropTypes.Validator<CheckboxesTypeKnob>;
onChange: PropTypes.Validator<(value: string[]) => string[]>;
isInline: PropTypes.Validator<boolean>;
};
static serialize: (value: string[]) => string[];
static deserialize: (value: string[]) => string[];
constructor(props: CheckboxesTypeProps);
handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
renderCheckboxList: ({ options }: CheckboxesTypeKnob) => JSX.Element[];
renderCheckbox: (label: string, value: string) => JSX.Element;
render(): JSX.Element;
}
export {};
|
nitesh55/assignment-wednesday
|
node_modules/react-intl/dist/components/plural.d.ts
|
<gh_stars>0
import * as React from 'react';
import { IntlShape, FormatPluralOptions } from '../types';
interface Props extends FormatPluralOptions {
value: number;
intl: IntlShape;
other: React.ReactNode;
zero?: React.ReactNode;
one?: React.ReactNode;
two?: React.ReactNode;
few?: React.ReactNode;
many?: React.ReactNode;
children?(value: React.ReactNode): React.ReactElement | null;
}
declare const _default: React.ForwardRefExoticComponent<Pick<Props, "children" | "other" | "zero" | "one" | "two" | "few" | "many" | "value" | "localeMatcher" | "format" | "type"> & {
forwardedRef?: ((instance: any) => void) | React.RefObject<any> | null | undefined;
} & React.RefAttributes<any>> & {
WrappedComponent: React.ComponentType<Props>;
};
export default _default;
//# sourceMappingURL=plural.d.ts.map
|
nitesh55/assignment-wednesday
|
node_modules/react-intl/lib/error.d.ts
|
<reponame>nitesh55/assignment-wednesday<filename>node_modules/react-intl/lib/error.d.ts
import { MessageDescriptor } from './types';
export declare const enum ReactIntlErrorCode {
FORMAT_ERROR = "FORMAT_ERROR",
UNSUPPORTED_FORMATTER = "UNSUPPORTED_FORMATTER",
INVALID_CONFIG = "INVALID_CONFIG",
MISSING_DATA = "MISSING_DATA",
MISSING_TRANSLATION = "MISSING_TRANSLATION"
}
export declare class ReactIntlError extends Error {
readonly code: ReactIntlErrorCode;
constructor(code: ReactIntlErrorCode, message: string, exception?: Error);
}
export declare class MessageFormatError extends ReactIntlError {
readonly descriptor?: MessageDescriptor;
constructor(message: string, locale: string, descriptor: MessageDescriptor, exception?: Error);
}
export declare class MissingTranslationError extends ReactIntlError {
readonly descriptor?: MessageDescriptor;
constructor(descriptor: MessageDescriptor, locale: string);
}
//# sourceMappingURL=error.d.ts.map
|
nitesh55/assignment-wednesday
|
node_modules/react-intl/src/formatters/number.ts
|
import {IntlConfig, Formatters, IntlFormatters} from '../types';
import {getNamedFormat, filterProps} from '../utils';
import {NumberFormatOptions} from '@formatjs/intl-numberformat';
import {ReactIntlError, ReactIntlErrorCode} from '../error';
const NUMBER_FORMAT_OPTIONS: Array<keyof NumberFormatOptions> = [
'localeMatcher',
'style',
'currency',
'currencyDisplay',
'unit',
'unitDisplay',
'useGrouping',
'minimumIntegerDigits',
'minimumFractionDigits',
'maximumFractionDigits',
'minimumSignificantDigits',
'maximumSignificantDigits',
// Unified NumberFormat (Stage 3 as of 10/22/19)
'compactDisplay',
'currencyDisplay',
'currencySign',
'notation',
'signDisplay',
'unit',
'unitDisplay',
];
export function getFormatter(
{
locale,
formats,
onError,
}: Pick<IntlConfig, 'locale' | 'formats' | 'onError'>,
getNumberFormat: Formatters['getNumberFormat'],
options: Parameters<IntlFormatters['formatNumber']>[1] = {}
): Intl.NumberFormat {
const {format} = options;
const defaults = ((format &&
getNamedFormat(formats!, 'number', format, onError)) ||
{}) as NumberFormatOptions;
const filteredOptions = filterProps(options, NUMBER_FORMAT_OPTIONS, defaults);
return getNumberFormat(locale, filteredOptions);
}
export function formatNumber(
config: Pick<IntlConfig, 'locale' | 'formats' | 'onError'>,
getNumberFormat: Formatters['getNumberFormat'],
value: Parameters<IntlFormatters['formatNumber']>[0],
options: Parameters<IntlFormatters['formatNumber']>[1] = {}
): string {
try {
return getFormatter(config, getNumberFormat, options).format(value);
} catch (e) {
config.onError(
new ReactIntlError(
ReactIntlErrorCode.FORMAT_ERROR,
'Error formatting number.',
e
)
);
}
return String(value);
}
export function formatNumberToParts(
config: Pick<IntlConfig, 'locale' | 'formats' | 'onError'>,
getNumberFormat: Formatters['getNumberFormat'],
value: Parameters<IntlFormatters['formatNumber']>[0],
options: Parameters<IntlFormatters['formatNumber']>[1] = {}
): Intl.NumberFormatPart[] {
try {
return getFormatter(config, getNumberFormat, options).formatToParts(value);
} catch (e) {
config.onError(
new ReactIntlError(
ReactIntlErrorCode.FORMAT_ERROR,
'Error formatting number.',
e
)
);
}
return [];
}
|
nitesh55/assignment-wednesday
|
node_modules/deep-map-keys/lib/deep-map-keys.d.ts
|
<reponame>nitesh55/assignment-wednesday<gh_stars>0
export interface MapFn {
(key: string, value: any): string;
}
export interface Opts {
thisArg?: any;
}
export declare class DeepMapKeys {
private mapFn;
private opts;
private cache;
constructor(mapFn: MapFn, opts: Opts);
map(value: any): any;
private mapArray;
private mapObject;
}
|
nitesh55/assignment-wednesday
|
node_modules/@storybook/addon-knobs/dist/components/types/Number.d.ts
|
<reponame>nitesh55/assignment-wednesday
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { KnobControlConfig, KnobControlProps } from './types';
declare type NumberTypeKnobValue = number;
export interface NumberTypeKnobOptions {
range?: boolean;
min?: number;
max?: number;
step?: number;
}
export interface NumberTypeKnob extends KnobControlConfig<NumberTypeKnobValue>, NumberTypeKnobOptions {
value: NumberTypeKnobValue;
}
interface NumberTypeProps extends KnobControlProps<NumberTypeKnobValue | null> {
knob: NumberTypeKnob;
}
export default class NumberType extends Component<NumberTypeProps> {
static propTypes: {
knob: PropTypes.Validator<NumberTypeKnob>;
onChange: PropTypes.Validator<(value: number | null) => number | null>;
};
static defaultProps: NumberTypeProps;
static serialize: (value: number | null | undefined) => string;
static deserialize: (value: string) => number | null;
shouldComponentUpdate(nextProps: NumberTypeProps): boolean;
handleChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
render(): JSX.Element;
}
export {};
|
nitesh55/assignment-wednesday
|
node_modules/@formatjs/intl-utils/src/polyfill-utils.ts
|
import {invariant} from './invariant';
import {
NumberFormatDigitInternalSlots,
NumberFormatDigitOptions,
NumberFormatNotation,
RawNumberFormatResult,
} from './number-types';
import {SANCTIONED_UNITS} from './units';
export function hasOwnProperty(o: unknown, key: string): boolean {
return Object.prototype.hasOwnProperty.call(o, key);
}
/**
* https://tc39.es/ecma262/#sec-toobject
* @param arg
*/
export function toObject<T>(
arg: T
): T extends null ? never : T extends undefined ? never : T {
if (arg == null) {
throw new TypeError('undefined/null cannot be converted to object');
}
return Object(arg);
}
/**
* https://tc39.es/ecma262/#sec-tostring
*/
export function toString(o: unknown): string {
// Only symbol is irregular...
if (typeof o === 'symbol') {
throw TypeError('Cannot convert a Symbol value to a string');
}
return String(o);
}
/**
* https://tc39.es/ecma402/#sec-getoption
* @param opts
* @param prop
* @param type
* @param values
* @param fallback
*/
export function getOption<T extends object, K extends keyof T, F>(
opts: T,
prop: K,
type: 'string' | 'boolean',
values: T[K][] | undefined,
fallback: F
): Exclude<T[K], undefined> | F {
// const descriptor = Object.getOwnPropertyDescriptor(opts, prop);
let value: any = opts[prop];
if (value !== undefined) {
if (type !== 'boolean' && type !== 'string') {
throw new TypeError('invalid type');
}
if (type === 'boolean') {
value = Boolean(value);
}
if (type === 'string') {
value = toString(value);
}
if (values !== undefined && !values.filter(val => val == value).length) {
throw new RangeError(`${value} is not within ${values.join(', ')}`);
}
return value;
}
return fallback;
}
/**
* https://tc39.es/ecma402/#sec-defaultnumberoption
* @param val
* @param min
* @param max
* @param fallback
*/
export function defaultNumberOption(
val: any,
min: number,
max: number,
fallback: number
) {
if (val !== undefined) {
val = Number(val);
if (isNaN(val) || val < min || val > max) {
throw new RangeError(`${val} is outside of range [${min}, ${max}]`);
}
return Math.floor(val);
}
return fallback;
}
/**
* https://tc39.es/ecma402/#sec-getnumberoption
* @param options
* @param property
* @param min
* @param max
* @param fallback
*/
export function getNumberOption<T extends object, K extends keyof T>(
options: T,
property: K,
minimum: number,
maximum: number,
fallback: number
): number {
const val = options[property];
return defaultNumberOption(val, minimum, maximum, fallback);
}
export function setInternalSlot<
Instance extends object,
Internal extends object,
Field extends keyof Internal
>(
map: WeakMap<Instance, Internal>,
pl: Instance,
field: Field,
value: NonNullable<Internal>[Field]
) {
if (!map.get(pl)) {
map.set(pl, Object.create(null));
}
const slots = map.get(pl)!;
slots[field] = value;
}
export function setMultiInternalSlots<
Instance extends object,
Internal extends object,
K extends keyof Internal
>(
map: WeakMap<Instance, Internal>,
pl: Instance,
props: Pick<NonNullable<Internal>, K>
) {
for (const k of Object.keys(props) as K[]) {
setInternalSlot(map, pl, k, props[k]);
}
}
export function getInternalSlot<
Instance extends object,
Internal extends object,
Field extends keyof Internal
>(
map: WeakMap<Instance, Internal>,
pl: Instance,
field: Field
): Internal[Field] {
return getMultiInternalSlots(map, pl, field)[field];
}
export function getMultiInternalSlots<
Instance extends object,
Internal extends object,
Field extends keyof Internal
>(
map: WeakMap<Instance, Internal>,
pl: Instance,
...fields: Field[]
): Pick<Internal, Field> {
const slots = map.get(pl);
if (!slots) {
throw new TypeError(`${pl} InternalSlot has not been initialized`);
}
return fields.reduce((all, f) => {
all[f] = slots[f];
return all;
}, Object.create(null) as Pick<Internal, Field>);
}
export interface LiteralPart {
type: 'literal';
value: string;
}
export function isLiteralPart(
patternPart: LiteralPart | {type: string; value?: string}
): patternPart is LiteralPart {
return patternPart.type === 'literal';
}
export function partitionPattern(pattern: string) {
const result = [];
let beginIndex = pattern.indexOf('{');
let endIndex = 0;
let nextIndex = 0;
const length = pattern.length;
while (beginIndex < pattern.length && beginIndex > -1) {
endIndex = pattern.indexOf('}', beginIndex);
invariant(endIndex > beginIndex, `Invalid pattern ${pattern}`);
if (beginIndex > nextIndex) {
result.push({
type: 'literal',
value: pattern.substring(nextIndex, beginIndex),
});
}
result.push({
type: pattern.substring(beginIndex + 1, endIndex),
value: undefined,
});
nextIndex = endIndex + 1;
beginIndex = pattern.indexOf('{', nextIndex);
}
if (nextIndex < length) {
result.push({
type: 'literal',
value: pattern.substring(nextIndex, length),
});
}
return result;
}
/**
* https://tc39.es/ecma402/#sec-setnfdigitoptions
*/
export function setNumberFormatDigitOptions(
internalSlots: NumberFormatDigitInternalSlots,
opts: NumberFormatDigitOptions,
mnfdDefault: number,
mxfdDefault: number,
notation: NumberFormatNotation
) {
const mnid = getNumberOption(opts, 'minimumIntegerDigits', 1, 21, 1);
let mnfd = opts.minimumFractionDigits;
let mxfd = opts.maximumFractionDigits;
let mnsd = opts.minimumSignificantDigits;
let mxsd = opts.maximumSignificantDigits;
internalSlots.minimumIntegerDigits = mnid;
if (mnsd !== undefined || mxsd !== undefined) {
internalSlots.roundingType = 'significantDigits';
mnsd = defaultNumberOption(mnsd, 1, 21, 1);
mxsd = defaultNumberOption(mxsd, mnsd, 21, 21);
internalSlots.minimumSignificantDigits = mnsd;
internalSlots.maximumSignificantDigits = mxsd;
} else if (mnfd !== undefined || mxfd !== undefined) {
internalSlots.roundingType = 'fractionDigits';
mnfd = defaultNumberOption(mnfd, 0, 20, mnfdDefault);
const mxfdActualDefault = Math.max(mnfd, mxfdDefault);
mxfd = defaultNumberOption(mxfd, mnfd, 20, mxfdActualDefault);
internalSlots.minimumFractionDigits = mnfd;
internalSlots.maximumFractionDigits = mxfd;
} else if (notation === 'compact') {
internalSlots.roundingType = 'compactRounding';
} else {
internalSlots.roundingType = 'fractionDigits';
internalSlots.minimumFractionDigits = mnfdDefault;
internalSlots.maximumFractionDigits = mxfdDefault;
}
}
export function objectIs(x: any, y: any) {
if (Object.is) {
return Object.is(x, y);
}
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
}
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
const NOT_A_Z_REGEX = /[^A-Z]/;
/**
* This follows https://tc39.es/ecma402/#sec-case-sensitivity-and-case-mapping
* @param str string to convert
*/
function toUpperCase(str: string): string {
return str.replace(/([a-z])/g, (_, c) => c.toUpperCase());
}
/**
* https://tc39.es/ecma402/#sec-iswellformedcurrencycode
*/
export function isWellFormedCurrencyCode(currency: string): boolean {
currency = toUpperCase(currency);
if (currency.length !== 3) {
return false;
}
if (NOT_A_Z_REGEX.test(currency)) {
return false;
}
return true;
}
/**
* https://tc39.es/ecma402/#sec-formatnumberstring
* TODO: dedup with intl-pluralrules
*/
export function formatNumericToString(
internalSlots: Pick<
NumberFormatDigitInternalSlots,
| 'roundingType'
| 'minimumSignificantDigits'
| 'maximumSignificantDigits'
| 'minimumIntegerDigits'
| 'minimumFractionDigits'
| 'maximumFractionDigits'
>,
x: number
) {
const isNegative = x < 0 || objectIs(x, -0);
if (isNegative) {
x = -x;
}
let result: RawNumberFormatResult;
const rourndingType = internalSlots.roundingType;
switch (rourndingType) {
case 'significantDigits':
result = toRawPrecision(
x,
internalSlots.minimumSignificantDigits!,
internalSlots.maximumSignificantDigits!
);
break;
case 'fractionDigits':
result = toRawFixed(
x,
internalSlots.minimumFractionDigits!,
internalSlots.maximumFractionDigits!
);
break;
default:
result = toRawPrecision(x, 1, 2);
if (result.integerDigitsCount > 1) {
result = toRawFixed(x, 0, 0);
}
break;
}
x = result.roundedNumber;
let string = result.formattedString;
const int = result.integerDigitsCount;
const minInteger = internalSlots.minimumIntegerDigits;
if (int < minInteger) {
const forwardZeros = repeat('0', minInteger - int);
string = forwardZeros + string;
}
if (isNegative) {
x = -x;
}
return {roundedNumber: x, formattedString: string};
}
/**
* TODO: dedup with intl-pluralrules and support BigInt
* https://tc39.es/ecma402/#sec-torawfixed
* @param x a finite non-negative Number or BigInt
* @param minFraction and integer between 0 and 20
* @param maxFraction and integer between 0 and 20
*/
export function toRawFixed(
x: number,
minFraction: number,
maxFraction: number
): RawNumberFormatResult {
const f = maxFraction;
let n: number;
{
const exactSolve = x * 10 ** f;
const roundDown = Math.floor(exactSolve);
const roundUp = Math.ceil(exactSolve);
n = exactSolve - roundDown < roundUp - exactSolve ? roundDown : roundUp;
}
const xFinal = n / 10 ** f;
// n is a positive integer, but it is possible to be greater than 1e21.
// In such case we will go the slow path.
// See also: https://tc39.es/ecma262/#sec-numeric-types-number-tostring
let m: string;
if (n < 1e21) {
m = n.toString();
} else {
m = n.toString();
const idx1 = m.indexOf('.');
const idx2 = m.indexOf('e+');
const exponent = parseInt(m.substring(idx2 + 2), 10);
m =
m.substring(0, idx1) +
m.substring(idx1 + 1, idx2) +
repeat('0', exponent - (idx2 - idx1 - 1));
}
let int: number;
if (f !== 0) {
let k = m.length;
if (k <= f) {
const z = repeat('0', f + 1 - k);
m = z + m;
k = f + 1;
}
const a = m.slice(0, k - f);
const b = m.slice(k - f);
m = `${a}.${b}`;
int = a.length;
} else {
int = m.length;
}
let cut = maxFraction - minFraction;
while (cut > 0 && m[m.length - 1] === '0') {
m = m.slice(0, -1);
cut--;
}
if (m[m.length - 1] === '.') {
m = m.slice(0, -1);
}
return {formattedString: m, roundedNumber: xFinal, integerDigitsCount: int};
}
// https://tc39.es/ecma402/#sec-torawprecision
export function toRawPrecision(
x: number,
minPrecision: number,
maxPrecision: number
): RawNumberFormatResult {
const p = maxPrecision;
let m: string;
let e: number;
let xFinal: number;
if (x === 0) {
m = repeat('0', p);
e = 0;
xFinal = 0;
} else {
e = getMagnitude(x);
let n: number;
{
const magnitude = e - p + 1;
const exactSolve =
// Preserve floating point precision as much as possible with multiplication.
magnitude < 0 ? x * 10 ** -magnitude : x / 10 ** magnitude;
const roundDown = Math.floor(exactSolve);
const roundUp = Math.ceil(exactSolve);
n = exactSolve - roundDown < roundUp - exactSolve ? roundDown : roundUp;
}
// See: https://tc39.es/ecma262/#sec-numeric-types-number-tostring
// No need to worry about scientific notation because it only happens for values >= 1e21,
// which has 22 significant digits. So it will at least be divided by 10 here to bring the
// value back into non-scientific-notation range.
m = n.toString();
xFinal = n * 10 ** (e - p + 1);
}
let int: number;
if (e >= p - 1) {
m = m + repeat('0', e - p + 1);
int = e + 1;
} else if (e >= 0) {
m = `${m.slice(0, e + 1)}.${m.slice(e + 1)}`;
int = e + 1;
} else {
m = `0.${repeat('0', -e - 1)}${m}`;
int = 1;
}
if (m.indexOf('.') >= 0 && maxPrecision > minPrecision) {
let cut = maxPrecision - minPrecision;
while (cut > 0 && m[m.length - 1] === '0') {
m = m.slice(0, -1);
cut--;
}
if (m[m.length - 1] === '.') {
m = m.slice(0, -1);
}
}
return {formattedString: m, roundedNumber: xFinal, integerDigitsCount: int};
}
export function repeat(s: string, times: number): string {
if (typeof s.repeat === 'function') {
return s.repeat(times);
}
const arr = new Array(times);
for (let i = 0; i < arr.length; i++) {
arr[i] = s;
}
return arr.join('');
}
/**
* Cannot do Math.log(x) / Math.log(10) bc if IEEE floating point issue
* @param x number
*/
export function getMagnitude(x: number): number {
// Cannot count string length via Number.toString because it may use scientific notation
// for very small or very large numbers.
return Math.floor(Math.log(x) * Math.LOG10E);
}
/**
* This follows https://tc39.es/ecma402/#sec-case-sensitivity-and-case-mapping
* @param str string to convert
*/
function toLowerCase(str: string): string {
return str.replace(/([A-Z])/g, (_, c) => c.toLowerCase());
}
const SHORTENED_SACTION_UNITS = SANCTIONED_UNITS.map(unit =>
unit.replace(/^(.*?)-/, '')
);
/**
* https://tc39.es/ecma402/#sec-iswellformedunitidentifier
* @param unit
*/
export function isWellFormedUnitIdentifier(unit: string) {
unit = toLowerCase(unit);
if (SHORTENED_SACTION_UNITS.indexOf(unit) > -1) {
return true;
}
const units = unit.split('-per-');
if (units.length !== 2) {
return false;
}
if (
SHORTENED_SACTION_UNITS.indexOf(units[0]) < 0 ||
SHORTENED_SACTION_UNITS.indexOf(units[1]) < 0
) {
return false;
}
return true;
}
/*
17 ECMAScript Standard Built-in Objects:
Every built-in Function object, including constructors, that is not
identified as an anonymous function has a name property whose value
is a String.
Unless otherwise specified, the name property of a built-in Function
object, if it exists, has the attributes { [[Writable]]: false,
[[Enumerable]]: false, [[Configurable]]: true }.
*/
export function defineProperty<T extends object>(
target: T,
name: string | symbol,
{value}: {value: any} & ThisType<any>
) {
Object.defineProperty(target, name, {
configurable: true,
enumerable: false,
writable: true,
value,
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.