repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
my-msblog/msblog-vite
|
src/locales/lang/module/constants/index.ts
|
export default {
zh: {
year: '年',
month: '月',
day: '日',
week: '周',
hour: '时',
minute: '分',
seconds: '秒',
all: '全部',
},
en: {
year: 'Year',
month: 'Month',
day: 'Day',
week: 'Week',
hour: 'Hour',
minute: 'Minute',
seconds: 'Seconds',
all: 'All',
}
};
|
my-msblog/msblog-vite
|
src/api/model/custom.ts
|
export interface IdDTO{
id?: number;
idList?: Array<number>;
}
export interface UserVO {
id: number;
username: string;
phone: string;
email: string;
token: string;
introduction: string;
sex: number;
createTime: string;
}
|
my-msblog/msblog-vite
|
src/hooks/useModalContext.ts
|
import { InjectionKey } from 'vue';
import { useContext } from './core/useContext';
export interface ModalContextProps {
redoModalHeight: () => void;
}
const key: InjectionKey<ModalContextProps> = Symbol();
export function useModalContext() {
return useContext<ModalContextProps>(key);
}
|
my-msblog/msblog-vite
|
src/locales/index.ts
|
import { createI18n } from 'vue-i18n';
import type { App } from 'vue';
import zh from './lang/zh';
import en from './lang/en';
import ElementPlus from 'element-plus';
import ZhLocale from 'element-plus/lib/locale/lang/zh-cn'; // 中文
import EhLocale from 'element-plus/lib/locale/lang/en'; // 英文
export const i18nOption = createI18n({
//fallbackLocale: 'zh',
locale: localStorage.getItem('lang') || 'zh', //默认显示的语言
//globalInjection: true,
//legacy: true, // you must specify 'legacy: false' option
messages: {
zh: {
...zh,
//...ZhLocale
},
en: {
...en,
//...EhLocale
}
}
});
export function setupI18n(app: App) {
let locale = '';
// 控制 element-plus 组件语言
if(i18nOption.global.fallbackLocale == 'zh') {
locale = ZhLocale as unknown as string;
} else {
locale = EhLocale as unknown as string;
}
app.use(i18nOption);
app.use(ElementPlus, { locale });
}
|
my-msblog/msblog-vite
|
src/constant/StoreOption.ts
|
export interface TabOption {
label: string;
name: string;
path: string;
}
export interface MenuOptions{
path: string;
nameZh: string;
component: any;
icon: string;
children: Array<MenuOptions>;
}
|
my-msblog/msblog-vite
|
src/views/client/article/data.ts
|
import { RecommendVO } from '@/api/model/client/article';
import { TagVO } from '@/api/model/client/home';
export interface IData{
commentList: Array<any>;
article: IArticle;
nouns: Array<TitleElement>;
like: number;
recommendList: Array<RecommendVO>;
}
export interface TitleElement{
title: any,
lineIndex: any,
indent: number,
}
export interface IArticle{
id: number;
title: string;
content: string;
writer: string;
contentMd: string;
likes: number;
reading: number;
wordCount: number;
cover: string;
tags: Array<TagVO>;
type: number;
typeName: string;
createTime: Date | string;
updateTime: Date | string;
}
export const data = {
cover: '../src/assets/background/archive.jpg',
title: '',
writer: '',
typeName: '',
likes: 0,
reading: 0,
content: '',
contentMd: '',
tags: [] as TagVO[],
createTime: new Date().toLocaleDateString(),
updateTime: new Date().toLocaleDateString(),
} as IArticle;
|
my-msblog/msblog-vite
|
src/views/admin/user-manage/userProfile/components/data.ts
|
<reponame>my-msblog/msblog-vite
import { FormRulesMap} from 'element-plus/es/components/form/src/form.type';
import { BaseOptions } from '@/constant/Type';
import { useI18n } from '@/hooks/useI18n';
import { RoleString } from '@/constant/enums/role';
const { t } = useI18n();
export const editFormRule: FormRulesMap = {
id: [{
required: true,
message: '',
trigger: 'blur',
}],
username: [{
required: true,
message: '请输入用户名',
trigger: 'blur',
}],
sex: [{
required: true,
message: '性别不能为空',
trigger: 'change'
}],
email: [{
required: false,
message: '请输入邮箱',
trigger: 'blur'
}],
phone: [{
required: true,
message: '请输入手机号',
trigger: 'blur'
}],
};
export const sexOptions: Array<BaseOptions<any>> =[
{
label: 1,
value: t('sex.male')
}, {
label: 0,
value: t('sex.female')
}
];
interface RolesOptions extends BaseOptions<String>{
label: string,
value: string,
disabled?: boolean,
}
export const roleOptions: Array<RolesOptions> = [
{
label: RoleString.VISITOR,
value: t('role.' + RoleString.VISITOR),
disabled: false,
},
{
label: RoleString.CONTENT_MANAGER,
value: t('role.' + RoleString.CONTENT_MANAGER),
disabled: false,
},
{
label: RoleString.SYSTEM_ADMIN,
value: t('role.' + RoleString.SYSTEM_ADMIN),
disabled: false,
},
];
|
my-msblog/msblog-vite
|
src/store/mutations.ts
|
export default {
setCodeKey(state: any, code: string) {
state.code_key = code;
},
clearUser(state: any) {
sessionStorage.clear();
state.user.user_id = 0;
state.user.username = '';
state.user.user_token = '';
state.user.user_email = '';
state.user.user_phone = '';
state.user.user_introduction = '';
state.permission.permission_menu = [];
state.user.user_role = '';
},
};
|
my-msblog/msblog-vite
|
src/constant/enums/sex.ts
|
const sexEnum = {
0: '女',
1: '男',
};
export enum Sex {
FEMALE = 0,
MALE = 1,
}
export function getSex(id: number):string {
return sexEnum[id];
}
|
my-msblog/msblog-vite
|
src/locales/lang/en.ts
|
<filename>src/locales/lang/en.ts
import { module } from './module';
export default {
message: {
language: 'English',
successful_logout: 'Successful logout',
login_success: 'Login success',
enter_email: 'Please enter your email',
enter_username: 'Please enter your username',
input_phone: 'Please enter the correct cell phone number ',
sms_send_success: 'Captcha sent successfully',
modified_successfully: 'Modified successfully',
whether_to_modify_information: 'Whether to modify information?',
tips: 'Tips',
confirm: 'Confirm',
cancel: 'Cancel',
get_captcha: 'Get Captcha',
captcha: 'Captcha',
introduce_yourself_briefly: 'Introduce yourself briefly',
no_data_selected: 'No data selected',
operation_success: 'Operation success',
confirm_submit:'Confirm Submit',
must_login: 'Please login first',
add_to_label: 'Failed to add to collection, please use Ctrl+D to add',
...module.message.en,
},
pages: {
...module.pages.en,
},
bar: {
title: 'MS BLOG',
categories: 'Categories',
homepage: 'Homepage',
tags: 'Tags',
archives: 'Archives',
about: 'About',
links: 'Links',
login: 'Sign In',
archive: 'Archive',
change_password: '<PASSWORD>',
personal_center: 'Personal center',
sign_out: 'Sign Out',
to_admin: 'Backstage control panel',
},
router: {
...module.route.en,
},
sex: {
male: 'Male',
female: 'Female'
},
role: {
...module.role.en,
},
button: {
...module.button.en,
},
constants: module.constants.en,
};
|
my-msblog/msblog-vite
|
src/api/admin/context/write/index.ts
|
<reponame>my-msblog/msblog-vite<filename>src/api/admin/context/write/index.ts
import { BaseOptions, CustomOptions } from '@/constant/Type';
import request from '@/utils/axios/request';
enum API {
categoryList = '',
tags = '',
}
export function categoryList(){
return request.get<Array<CustomOptions>>({
url: API.categoryList
});
}
export function tagsList(){
return request.get<Array<CustomOptions>>({
url: API.tags
});
}
|
my-msblog/msblog-vite
|
src/api/admin/api-list/index.ts
|
<filename>src/api/admin/api-list/index.ts
import request from '@/utils/axios/request';
import { RequestItemVO } from '@/api/model/admin/api-list';
enum Api {
getApi = '/sys/all/interface',
}
export function getAllApi(){
return request.get<Array<RequestItemVO>>({
url: Api.getApi,
});
}
|
my-msblog/msblog-vite
|
src/api/model/client/login-model.ts
|
<filename>src/api/model/client/login-model.ts
export interface CaptchaVO{
key: string;
img: string;
}
export interface LoginDTO{
code: string;
key: string;
password: string;
username: string;
}
|
my-msblog/msblog-vite
|
src/locales/lang/module/role/index.ts
|
export default {
zh: {
SYSTEM_ADMIN: '系统管理员',
CONTENT_MANAGER: '内容管理员',
VISITOR: '访客',
},
en: {
SYSTEM_ADMIN: 'SYSTEM ADMIN',
CONTENT_MANAGER: 'CONTENT MANAGER',
VISITOR: 'VISITOR',
}
};
|
my-msblog/msblog-vite
|
src/utils/axios/type.ts
|
<gh_stars>0
import { AxiosRequestConfig } from 'axios';
interface requestOption{
url: string;
data?: any;
config?: AxiosRequestConfig;
}
// 泛型接口
export interface Get {
<T>(option: requestOption): Promise<T>;
}
export interface Post {
<T>(option: requestOption): Promise<T>;
}
export interface Put {
<T>(option: requestOption): Promise<T>;
}
export interface Delete {
<T>(option: requestOption): Promise<T>;
}
|
my-msblog/msblog-vite
|
src/store/modules/index.ts
|
import { ModuleTree } from 'vuex';
import tagView from './members/tag-views';
import user from '@/store/modules/members/user';
import permission from '@/store/modules/members/permission';
import list from './members/list';
export const modules: ModuleTree<any> = {
tagView,
user,
permission,
list,
};
|
my-msblog/msblog-vite
|
src/store/modules/members/list.ts
|
import { CategoryVO } from '@/api/model/client/category';
import { ActionTree, GetterTree } from 'vuex';
import { arryIsEmpty, strIsEmpty } from '@/utils';
interface ListState{
categoryList: Array<CategoryVO>;
category: string;
tag: string;
}
const state: ListState = {
categoryList: [],
category: '',
tag: '',
};
const getters: GetterTree<ListState, any> = {
getCategoryList(state: ListState){
return arryIsEmpty(state.categoryList)
? JSON.parse(sessionStorage.getItem('categoryList') as string)
: state.categoryList;
},
getCategory(state: ListState) {
return strIsEmpty(state.category) ? sessionStorage.getItem('category') : state.category;
},
getTag(state: ListState) {
return strIsEmpty(state.tag) ? sessionStorage.getItem('tag') : state.tag;
}
};
const mutations = {
setCategoryList(state: ListState, list: Array<CategoryVO>){
state.categoryList = list;
sessionStorage.setItem('categoryList', JSON.stringify(list));
},
setCategory(state: ListState, category: string) {
state.category = category;
sessionStorage.setItem('category', category);
},
setTag(state: ListState, tag: string) {
state.tag = tag;
sessionStorage.setItem('tag', tag);
},
};
const actions: ActionTree<ListState, any> = {};
export default {
state,
mutations,
actions,
getters,
};
|
my-msblog/msblog-vite
|
src/layout/client/components/data.ts
|
interface BarMenuItem {
route: string;
icon: string;
text: string;
}
export const menuBarItem: BarMenuItem[]= [
{
route: '/',
icon: 'HomeFilled',
text: 'homepage',
},
{
route: '/archive',
icon: 'FolderOpened',
text: 'archive',
},
{
route: '/categories',
icon: 'Menu',
text: 'categories',
},
{
route: '/tags',
icon: 'Management',
text: 'tags',
},
{
route: '/links',
icon: 'Connection',
text: 'links',
},
{
route: '/about',
icon: 'Promotion',
text: 'about',
},
];
|
my-msblog/msblog-vite
|
src/api/client/login/index.ts
|
<reponame>my-msblog/msblog-vite<filename>src/api/client/login/index.ts
import request from '@/utils/axios/request';
import { CaptchaVO, LoginDTO } from '@/api/model/client/login-model';
import { UserVO } from '@/api/model/custom';
enum Api {
login = '/login',
spec = '/code/captcha/spec',
arithmetic = '/code/captcha/arithmetic',
}
export function loginByPwd(dto: LoginDTO) {
return request.post<UserVO>({
url: Api.login,
data: dto,
});
}
export function getSpecCode() {
return request.get<CaptchaVO>({
url: Api.spec
});
}
export function getArithmeticCode() {
return request.get<CaptchaVO>({
url: Api.arithmetic
});
}
|
my-msblog/msblog-vite
|
src/api/model/sys-model.ts
|
export interface PhoneDTO{
phone: string;
}
export interface MenuVO{
path: string;
nameZh: string;
component: string;
icon: string;
children: Array<MenuVO>;
}
|
my-msblog/msblog-vite
|
src/api/sys/index.ts
|
<filename>src/api/sys/index.ts
import request from '@/utils/axios/request';
import { MenuVO, PhoneDTO } from '@/api/model/sys-model';
enum Api {
sms = '/code/sms',
authentication = 'api/authentication',
menu = '/info/menu',
logout = '/logout',
}
export function getSMS(dto: PhoneDTO) {
return request.post<string>({
url: Api.sms,
data: dto
});
}
export function authentication() {
return request.post<string>({
url: Api.authentication,
});
}
export function getMenu() {
return request.post<Array<MenuVO>>({
url: Api.menu,
});
}
export function logout() {
return request.get<string>({
url: Api.logout,
});
}
|
my-msblog/msblog-vite
|
src/views/admin/dashboard/components/data.ts
|
<filename>src/views/admin/dashboard/components/data.ts
export interface GrowCardItem {
icon: string;
title: string;
value: number;
total: number;
color: string;
action: string;
}
export interface CardValue {
visit: number;
user: number;
articles: number;
comments: number;
}
|
my-msblog/msblog-vite
|
src/plugins/vm-editor.ts
|
<reponame>my-msblog/msblog-vite
import VMdEditor from '@kangc/v-md-editor';
import '@kangc/v-md-editor/lib/style/base-editor.css';
import githubTheme from '@kangc/v-md-editor/lib/theme/github.js';
import '@kangc/v-md-editor/lib/theme/style/github.css';
import VMdPreview from '@kangc/v-md-editor/lib/preview';
import '@kangc/v-md-editor/lib/style/preview.css';
// highlightjs
import hljs from 'highlight.js';
export default function loadEditor(app: any) {
VMdEditor.use(githubTheme, {
Hljs: hljs,
});
VMdPreview.use(githubTheme, {
Hljs: hljs,
});
app.use(VMdEditor);
app.use(VMdPreview);
}
|
my-msblog/msblog-vite
|
src/store/index.ts
|
import { createStore } from 'vuex';
import { modules } from './modules';
import actions from './actions';
import getters from './getters';
import mutations from '@/store/mutations';
export default createStore({
state: {
code_key: '',
},
mutations,
actions,
modules,
getters,
});
|
my-msblog/msblog-vite
|
src/store/getters.ts
|
export default {
getCodeKey(state: any) {
return state.code_key;
},
};
|
my-msblog/msblog-vite
|
src/views/client/links/data.ts
|
<gh_stars>0
export interface ILink{
url?: string;
name: string;
desc: string;
}
export const mock: ILink[] = [
{
url: 'https://crazywong.com/img/avatar.png',
name: 'dd',
desc: 'i am dd',
},
{
url: 'https://crazywong.com/img/avatar.png',
name: 'dd',
desc: 'i am dd',
},
{
url: 'https://crazywong.com/img/avatar.png',
name: 'dd',
desc: 'i am dd',
},
];
|
my-msblog/msblog-vite
|
src/api/admin/system/menu-manage/index.ts
|
import request from '@/utils/axios/request';
import { MenuTreeVO } from '@/api/model/admin/system';
enum Api {
getMenuTress = '',
}
export function getMenuTrees(){
return request.get<MenuTreeVO[]>({
url: Api.getMenuTress,
});
}
|
my-msblog/msblog-vite
|
src/locales/lang/zh.ts
|
<reponame>my-msblog/msblog-vite
import { module } from './module';
export default {
message: {
language: '中文',
successful_logout: '成功登出',
login_success: '登录成功',
input_phone: '请输入手机号',
enter_email: '请输入邮箱',
enter_username: '请输入用户名',
sms_send_success: '验证码发送成功',
modified_successfully: '修改成功',
whether_to_modify_information: '是否修改信息?',
confirm_submit: '确认提交',
tips: '提示',
confirm: '确定',
cancel: '取消',
get_captcha: '获取验证码',
captcha: '验证码',
introduce_yourself_briefly: '简单的介绍下自己吧',
no_data_selected: '未选中任何数据',
operation_success: '操作成功',
must_login: '请先登录!',
add_to_label: '加入收藏失败,请使用Ctrl+D进行添加',
...module.message.zh,
},
pages:{
...module.pages.zh,
},
bar:{
title: 'MS BLOG',
categories: '分类',
homepage: '首页',
tags: '标签',
archives: '归档',
about: '关于',
links: '链接',
login: '登录',
archive: '归档',
change_password: '<PASSWORD>',
personal_center: '个人中心',
sign_out: '登出',
to_admin: '控制面板',
},
router: {
...module.route.zh,
},
sex: {
male: '男',
female: '女'
},
role: module.role.zh,
button: {
...module.button.zh,
},
constants: module.constants.zh,
};
|
my-msblog/msblog-vite
|
src/api/admin/user-profile/index.ts
|
<reponame>my-msblog/msblog-vite
import request from '@/utils/axios/request';
import { IdDTO } from '@/api/model/custom';
import { BaseDTO, PageInfo } from '@/api/model/core';
import { UserProfileVO, StatusDTO } from '@/api/model/admin/user-profile';
import { UserTableChangeDTO } from '@/api/model/user-info-model';
enum Api {
page = '/account/user/page',
delete = '/user/remove',
deleteList = '/user/remove/list',
change = '/account/admin/change/user',
add = '/account/admin/add',
status_change = '/account/admin/status/change'
}
export function userStatusChange(dto: StatusDTO){
return request.post<string>({
url: Api.status_change,
data: dto
});
}
export function adminAdd(dto: UserTableChangeDTO){
return request.post<string>({
url: Api.add,
data: dto
});
}
export function adminChangeUser(dto: UserTableChangeDTO) {
return request.post<string>({
url: Api.change,
data: dto,
});
}
export function adminUserPage(params: BaseDTO) {
return request.post<PageInfo<UserProfileVO>>({
url: Api.page,
data: params,
});
}
export function deletedUser(params: IdDTO) {
return request.post<string>({
url: Api.delete,
data: params,
});
}
export function deleteList(idList: IdDTO) {
return request.post<string>({
url: Api.deleteList,
data: idList,
});
}
|
my-msblog/msblog-vite
|
src/api/model/client/article.ts
|
<reponame>my-msblog/msblog-vite<filename>src/api/model/client/article.ts
import { TagVO } from "./home";
export interface CommentItemVO{
id: number;
articleId: number;
parentId: number;
publishTime: Date;
children: CommentItemVO[];
context: string;
like: number;
commenterId: number;
isLike: boolean;
publisher: string;
respondent: string;
}
export interface ArticleVO{
id: number;
title: string;
content: string;
writer: string;
contentMd: string;
likes: number;
reading: number;
wordCount: number;
cover: string;
tags: Array<TagVO>;
type: number;
typeName: string;
createTime: Date | string;
updateTime: Date | string;
}
export interface CommentSubmitDTO{
commentId: number;
context: string;
replyTime: Date;
}
export interface GiveLikesDTO{
userId: number;
commentId: number;
is: boolean;
time: Date;
}
export interface RecommendVO{
id: number;
title: string;
cover: string;
createTime: string;
}
|
my-msblog/msblog-vite
|
src/api/client/acrhive/index.ts
|
import request from '@/utils/axios/request';
import { BaseDTO, PageInfo } from '@/api/model/core';
import { AcrhiveVO } from'@/api/model/client/acrhive';
enum Api {
page = '/article/date/page',
}
export function getArchivePage(dto: BaseDTO){
return request.post<PageInfo<AcrhiveVO>>({
url: Api.page,
data: dto,
});
}
|
nukeguys/thenueye
|
src/pages/index.tsx
|
import { Meta } from '../layout/Meta';
import { Main } from '../main';
import PostCard from '../main/PostCard';
import { Post } from '../type';
const POSTS: Post[] = [
{
topic: { id: 'sports', name: 'Sports' },
title: 'One-Hit Wonders in Sports',
description: `The greatest single-season anomalies in the last 30 years`,
authors: [{ id: 'kim', name: 'Kim' }],
publishedOn: 'April 25th, 2020',
img: 'https://pudding.cool/common/assets/thumbnails/640/2018_04_one-hit-wonders.jpg',
id: 'one-hit-wonders',
},
{
topic: { id: 'sports', name: 'Sports' },
title: 'nike',
description: `The greatest single-season anomalies in the last 30 years`,
authors: [{ id: 'kim', name: 'Kim' }],
publishedOn: 'April 25th, 2020',
img: 'https://pudding.cool/common/assets/thumbnails/640/2018_04_one-hit-wonders.jpg',
id: 'nike',
},
];
const Index = () => {
return (
<Main
meta={<Meta title="The Nueye" description="is a digital publication." />}
topics={[
{ id: 'technology', name: 'Technology' },
{ id: 'automotive', name: 'Automotive' },
{ id: 'finance', name: 'Finance' },
{ id: 'politics', name: 'Politics' },
{ id: 'culture', name: 'Culture' },
{ id: 'sports', name: 'Sports' },
]}
>
<section className="flex flex-col items-center px-3">
{POSTS.map((post, index) => (
<PostCard key={index} {...post} />
))}
</section>
</Main>
);
};
export default Index;
|
Bhaskers-Blu-Org2/monaco-json
|
src/jsonWorker.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import Thenable = monaco.Thenable;
import IWorkerContext = monaco.worker.IWorkerContext;
import * as jsonService from 'vscode-json-languageservice';
let defaultSchemaRequestService;
if (typeof fetch !== 'undefined') {
defaultSchemaRequestService = function (url) { return fetch(url).then(response => response.text()) };
}
class PromiseAdapter<T> implements jsonService.Thenable<T> {
private wrapped: Promise<T>;
constructor(executor: (resolve: (value?: T | jsonService.Thenable<T>) => void, reject: (reason?: any) => void) => void) {
this.wrapped = new Promise<T>(executor);
}
public then<TResult>(onfulfilled?: (value: T) => TResult | jsonService.Thenable<TResult>, onrejected?: (reason: any) => void): jsonService.Thenable<TResult> {
let thenable: jsonService.Thenable<T> = this.wrapped;
return thenable.then(onfulfilled, onrejected);
}
public getWrapped(): monaco.Thenable<T> {
return this.wrapped;
}
public static resolve<T>(v: T | Thenable<T>): jsonService.Thenable<T> {
return <monaco.Thenable<T>>Promise.resolve(v);
}
public static reject<T>(v: T): jsonService.Thenable<T> {
return Promise.reject(<any>v);
}
public static all<T>(values: jsonService.Thenable<T>[]): jsonService.Thenable<T[]> {
return Promise.all(values);
}
}
export class JSONWorker {
private _ctx: IWorkerContext;
private _languageService: jsonService.LanguageService;
private _languageSettings: jsonService.LanguageSettings;
private _languageId: string;
constructor(ctx: IWorkerContext, createData: ICreateData) {
this._ctx = ctx;
this._languageSettings = createData.languageSettings;
this._languageId = createData.languageId;
this._languageService = jsonService.getLanguageService({
schemaRequestService: createData.enableSchemaRequest && defaultSchemaRequestService,
promiseConstructor: PromiseAdapter
});
this._languageService.configure(this._languageSettings);
}
doValidation(uri: string): Thenable<jsonService.Diagnostic[]> {
let document = this._getTextDocument(uri);
if (document) {
let jsonDocument = this._languageService.parseJSONDocument(document);
return this._languageService.doValidation(document, jsonDocument);
}
return Promise.resolve([]);
}
doComplete(uri: string, position: jsonService.Position): Thenable<jsonService.CompletionList> {
let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document);
return this._languageService.doComplete(document, position, jsonDocument);
}
doResolve(item: jsonService.CompletionItem): Thenable<jsonService.CompletionItem> {
return this._languageService.doResolve(item);
}
doHover(uri: string, position: jsonService.Position): Thenable<jsonService.Hover> {
let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document);
return this._languageService.doHover(document, position, jsonDocument);
}
format(uri: string, range: jsonService.Range, options: jsonService.FormattingOptions): Thenable<jsonService.TextEdit[]> {
let document = this._getTextDocument(uri);
let textEdits = this._languageService.format(document, range, options);
return Promise.resolve(textEdits);
}
resetSchema(uri: string): Thenable<boolean> {
return Promise.resolve(this._languageService.resetSchema(uri));
}
findDocumentSymbols(uri: string): Thenable<jsonService.SymbolInformation[]> {
let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document);
let symbols = this._languageService.findDocumentSymbols(document, jsonDocument);
return Promise.resolve(symbols);
}
findDocumentColors(uri: string): Thenable<jsonService.ColorInformation[]> {
let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document);
let colorSymbols = this._languageService.findDocumentColors(document, jsonDocument);
return Promise.resolve(colorSymbols);
}
getColorPresentations(uri: string, color: jsonService.Color, range: jsonService.Range): Thenable<jsonService.ColorPresentation[]> {
let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document);
let colorPresentations = this._languageService.getColorPresentations(document, jsonDocument, color, range);
return Promise.resolve(colorPresentations);
}
getFoldingRanges(uri: string, context?: { rangeLimit?: number; }): Thenable<jsonService.FoldingRange[]> {
let document = this._getTextDocument(uri);
let ranges = this._languageService.getFoldingRanges(document, context);
return Promise.resolve(ranges);
}
getSelectionRanges(uri: string, positions: jsonService.Position[]): Thenable<jsonService.SelectionRange[]> {
let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document);
let ranges = this._languageService.getSelectionRanges(document, positions, jsonDocument);
return Promise.resolve(ranges);
}
private _getTextDocument(uri: string): jsonService.TextDocument {
let models = this._ctx.getMirrorModels();
for (let model of models) {
if (model.uri.toString() === uri) {
return jsonService.TextDocument.create(uri, this._languageId, model.version, model.getValue());
}
}
return null;
}
}
export interface ICreateData {
languageId: string;
languageSettings: jsonService.LanguageSettings;
enableSchemaRequest: boolean;
}
export function create(ctx: IWorkerContext, createData: ICreateData): JSONWorker {
return new JSONWorker(ctx, createData);
}
|
Bhaskers-Blu-Org2/monaco-json
|
src/languageFeatures.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { LanguageServiceDefaultsImpl } from './monaco.contribution';
import { JSONWorker } from './jsonWorker';
import * as jsonService from 'vscode-json-languageservice';
import Uri = monaco.Uri;
import Position = monaco.Position;
import Range = monaco.Range;
import IRange = monaco.IRange;
import Thenable = monaco.Thenable;
import CancellationToken = monaco.CancellationToken;
import IDisposable = monaco.IDisposable;
export interface WorkerAccessor {
(...more: Uri[]): Thenable<JSONWorker>
}
// --- diagnostics --- ---
export class DiagnosticsAdapter {
private _disposables: IDisposable[] = [];
private _listener: { [uri: string]: IDisposable } = Object.create(null);
constructor(private _languageId: string, private _worker: WorkerAccessor, defaults: LanguageServiceDefaultsImpl) {
const onModelAdd = (model: monaco.editor.IModel): void => {
let modeId = model.getModeId();
if (modeId !== this._languageId) {
return;
}
let handle: number;
this._listener[model.uri.toString()] = model.onDidChangeContent(() => {
clearTimeout(handle);
handle = setTimeout(() => this._doValidate(model.uri, modeId), 500);
});
this._doValidate(model.uri, modeId);
};
const onModelRemoved = (model: monaco.editor.IModel): void => {
monaco.editor.setModelMarkers(model, this._languageId, []);
let uriStr = model.uri.toString();
let listener = this._listener[uriStr];
if (listener) {
listener.dispose();
delete this._listener[uriStr];
}
};
this._disposables.push(monaco.editor.onDidCreateModel(onModelAdd));
this._disposables.push(monaco.editor.onWillDisposeModel(model => {
onModelRemoved(model);
this._resetSchema(model.uri);
}));
this._disposables.push(monaco.editor.onDidChangeModelLanguage(event => {
onModelRemoved(event.model);
onModelAdd(event.model);
this._resetSchema(event.model.uri);
}));
this._disposables.push(defaults.onDidChange(_ => {
monaco.editor.getModels().forEach(model => {
if (model.getModeId() === this._languageId) {
onModelRemoved(model);
onModelAdd(model);
}
});
}));
this._disposables.push({
dispose: () => {
monaco.editor.getModels().forEach(onModelRemoved);
for (let key in this._listener) {
this._listener[key].dispose();
}
}
});
monaco.editor.getModels().forEach(onModelAdd);
}
public dispose(): void {
this._disposables.forEach(d => d && d.dispose());
this._disposables = [];
}
private _resetSchema(resource: Uri): void {
this._worker().then(worker => {
worker.resetSchema(resource.toString());
});
}
private _doValidate(resource: Uri, languageId: string): void {
this._worker(resource).then(worker => {
return worker.doValidation(resource.toString()).then(diagnostics => {
const markers = diagnostics.map(d => toDiagnostics(resource, d));
let model = monaco.editor.getModel(resource);
if (model && model.getModeId() === languageId) {
monaco.editor.setModelMarkers(model, languageId, markers);
}
});
}).then(undefined, err => {
console.error(err);
});
}
}
function toSeverity(lsSeverity: number): monaco.MarkerSeverity {
switch (lsSeverity) {
case jsonService.DiagnosticSeverity.Error: return monaco.MarkerSeverity.Error;
case jsonService.DiagnosticSeverity.Warning: return monaco.MarkerSeverity.Warning;
case jsonService.DiagnosticSeverity.Information: return monaco.MarkerSeverity.Info;
case jsonService.DiagnosticSeverity.Hint: return monaco.MarkerSeverity.Hint;
default:
return monaco.MarkerSeverity.Info;
}
}
function toDiagnostics(resource: Uri, diag: jsonService.Diagnostic): monaco.editor.IMarkerData {
let code = typeof diag.code === 'number' ? String(diag.code) : <string>diag.code;
return {
severity: toSeverity(diag.severity),
startLineNumber: diag.range.start.line + 1,
startColumn: diag.range.start.character + 1,
endLineNumber: diag.range.end.line + 1,
endColumn: diag.range.end.character + 1,
message: diag.message,
code: code,
source: diag.source
};
}
// --- completion ------
function fromPosition(position: Position): jsonService.Position {
if (!position) {
return void 0;
}
return { character: position.column - 1, line: position.lineNumber - 1 };
}
function fromRange(range: IRange): jsonService.Range {
if (!range) {
return void 0;
}
return { start: { line: range.startLineNumber - 1, character: range.startColumn - 1 }, end: { line: range.endLineNumber - 1, character: range.endColumn - 1 } };
}
function toRange(range: jsonService.Range): Range {
if (!range) {
return void 0;
}
return new Range(range.start.line + 1, range.start.character + 1, range.end.line + 1, range.end.character + 1);
}
function toCompletionItemKind(kind: number): monaco.languages.CompletionItemKind {
let mItemKind = monaco.languages.CompletionItemKind;
switch (kind) {
case jsonService.CompletionItemKind.Text: return mItemKind.Text;
case jsonService.CompletionItemKind.Method: return mItemKind.Method;
case jsonService.CompletionItemKind.Function: return mItemKind.Function;
case jsonService.CompletionItemKind.Constructor: return mItemKind.Constructor;
case jsonService.CompletionItemKind.Field: return mItemKind.Field;
case jsonService.CompletionItemKind.Variable: return mItemKind.Variable;
case jsonService.CompletionItemKind.Class: return mItemKind.Class;
case jsonService.CompletionItemKind.Interface: return mItemKind.Interface;
case jsonService.CompletionItemKind.Module: return mItemKind.Module;
case jsonService.CompletionItemKind.Property: return mItemKind.Property;
case jsonService.CompletionItemKind.Unit: return mItemKind.Unit;
case jsonService.CompletionItemKind.Value: return mItemKind.Value;
case jsonService.CompletionItemKind.Enum: return mItemKind.Enum;
case jsonService.CompletionItemKind.Keyword: return mItemKind.Keyword;
case jsonService.CompletionItemKind.Snippet: return mItemKind.Snippet;
case jsonService.CompletionItemKind.Color: return mItemKind.Color;
case jsonService.CompletionItemKind.File: return mItemKind.File;
case jsonService.CompletionItemKind.Reference: return mItemKind.Reference;
}
return mItemKind.Property;
}
function fromCompletionItemKind(kind: monaco.languages.CompletionItemKind): jsonService.CompletionItemKind {
let mItemKind = monaco.languages.CompletionItemKind;
switch (kind) {
case mItemKind.Text: return jsonService.CompletionItemKind.Text;
case mItemKind.Method: return jsonService.CompletionItemKind.Method;
case mItemKind.Function: return jsonService.CompletionItemKind.Function;
case mItemKind.Constructor: return jsonService.CompletionItemKind.Constructor;
case mItemKind.Field: return jsonService.CompletionItemKind.Field;
case mItemKind.Variable: return jsonService.CompletionItemKind.Variable;
case mItemKind.Class: return jsonService.CompletionItemKind.Class;
case mItemKind.Interface: return jsonService.CompletionItemKind.Interface;
case mItemKind.Module: return jsonService.CompletionItemKind.Module;
case mItemKind.Property: return jsonService.CompletionItemKind.Property;
case mItemKind.Unit: return jsonService.CompletionItemKind.Unit;
case mItemKind.Value: return jsonService.CompletionItemKind.Value;
case mItemKind.Enum: return jsonService.CompletionItemKind.Enum;
case mItemKind.Keyword: return jsonService.CompletionItemKind.Keyword;
case mItemKind.Snippet: return jsonService.CompletionItemKind.Snippet;
case mItemKind.Color: return jsonService.CompletionItemKind.Color;
case mItemKind.File: return jsonService.CompletionItemKind.File;
case mItemKind.Reference: return jsonService.CompletionItemKind.Reference;
}
return jsonService.CompletionItemKind.Property;
}
function toTextEdit(textEdit: jsonService.TextEdit): monaco.editor.ISingleEditOperation {
if (!textEdit) {
return void 0;
}
return {
range: toRange(textEdit.range),
text: textEdit.newText
}
}
export class CompletionAdapter implements monaco.languages.CompletionItemProvider {
constructor(private _worker: WorkerAccessor) {
}
public get triggerCharacters(): string[] {
return [' ', ':'];
}
provideCompletionItems(model: monaco.editor.IReadOnlyModel, position: Position, context: monaco.languages.CompletionContext, token: CancellationToken): Thenable<monaco.languages.CompletionList> {
const resource = model.uri;
return this._worker(resource).then(worker => {
return worker.doComplete(resource.toString(), fromPosition(position));
}).then(info => {
if (!info) {
return;
}
const wordInfo = model.getWordUntilPosition(position);
const wordRange = new Range(position.lineNumber, wordInfo.startColumn, position.lineNumber, wordInfo.endColumn);
let items: monaco.languages.CompletionItem[] = info.items.map(entry => {
let item: monaco.languages.CompletionItem = {
label: entry.label,
insertText: entry.insertText || entry.label,
sortText: entry.sortText,
filterText: entry.filterText,
documentation: entry.documentation,
detail: entry.detail,
range: wordRange,
kind: toCompletionItemKind(entry.kind),
};
if (entry.textEdit) {
item.range = toRange(entry.textEdit.range);
item.insertText = entry.textEdit.newText;
}
if (entry.additionalTextEdits) {
item.additionalTextEdits = entry.additionalTextEdits.map(toTextEdit)
}
if (entry.insertTextFormat === jsonService.InsertTextFormat.Snippet) {
item.insertTextRules = monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet;
}
return item;
});
return {
isIncomplete: info.isIncomplete,
suggestions: items
};
});
}
}
function isMarkupContent(thing: any): thing is jsonService.MarkupContent {
return thing && typeof thing === 'object' && typeof (<jsonService.MarkupContent>thing).kind === 'string';
}
function toMarkdownString(entry: jsonService.MarkupContent | jsonService.MarkedString): monaco.IMarkdownString {
if (typeof entry === 'string') {
return {
value: entry
};
}
if (isMarkupContent(entry)) {
if (entry.kind === 'plaintext') {
return {
value: entry.value.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&')
};
}
return {
value: entry.value
};
}
return { value: '```' + entry.language + '\n' + entry.value + '\n```\n' };
}
function toMarkedStringArray(contents: jsonService.MarkupContent | jsonService.MarkedString | jsonService.MarkedString[]): monaco.IMarkdownString[] {
if (!contents) {
return void 0;
}
if (Array.isArray(contents)) {
return contents.map(toMarkdownString);
}
return [toMarkdownString(contents)];
}
// --- hover ------
export class HoverAdapter implements monaco.languages.HoverProvider {
constructor(private _worker: WorkerAccessor) {
}
provideHover(model: monaco.editor.IReadOnlyModel, position: Position, token: CancellationToken): Thenable<monaco.languages.Hover> {
let resource = model.uri;
return this._worker(resource).then(worker => {
return worker.doHover(resource.toString(), fromPosition(position));
}).then(info => {
if (!info) {
return;
}
return <monaco.languages.Hover>{
range: toRange(info.range),
contents: toMarkedStringArray(info.contents)
};
});
}
}
// --- definition ------
function toLocation(location: jsonService.Location): monaco.languages.Location {
return {
uri: Uri.parse(location.uri),
range: toRange(location.range)
};
}
// --- document symbols ------
function toSymbolKind(kind: jsonService.SymbolKind): monaco.languages.SymbolKind {
let mKind = monaco.languages.SymbolKind;
switch (kind) {
case jsonService.SymbolKind.File: return mKind.Array;
case jsonService.SymbolKind.Module: return mKind.Module;
case jsonService.SymbolKind.Namespace: return mKind.Namespace;
case jsonService.SymbolKind.Package: return mKind.Package;
case jsonService.SymbolKind.Class: return mKind.Class;
case jsonService.SymbolKind.Method: return mKind.Method;
case jsonService.SymbolKind.Property: return mKind.Property;
case jsonService.SymbolKind.Field: return mKind.Field;
case jsonService.SymbolKind.Constructor: return mKind.Constructor;
case jsonService.SymbolKind.Enum: return mKind.Enum;
case jsonService.SymbolKind.Interface: return mKind.Interface;
case jsonService.SymbolKind.Function: return mKind.Function;
case jsonService.SymbolKind.Variable: return mKind.Variable;
case jsonService.SymbolKind.Constant: return mKind.Constant;
case jsonService.SymbolKind.String: return mKind.String;
case jsonService.SymbolKind.Number: return mKind.Number;
case jsonService.SymbolKind.Boolean: return mKind.Boolean;
case jsonService.SymbolKind.Array: return mKind.Array;
}
return mKind.Function;
}
export class DocumentSymbolAdapter implements monaco.languages.DocumentSymbolProvider {
constructor(private _worker: WorkerAccessor) {
}
public provideDocumentSymbols(model: monaco.editor.IReadOnlyModel, token: CancellationToken): Thenable<monaco.languages.DocumentSymbol[]> {
const resource = model.uri;
return this._worker(resource).then(worker => worker.findDocumentSymbols(resource.toString())).then(items => {
if (!items) {
return;
}
return items.map(item => ({
name: item.name,
detail: '',
containerName: item.containerName,
kind: toSymbolKind(item.kind),
range: toRange(item.location.range),
selectionRange: toRange(item.location.range),
tags: []
}));
});
}
}
function fromFormattingOptions(options: monaco.languages.FormattingOptions): jsonService.FormattingOptions {
return {
tabSize: options.tabSize,
insertSpaces: options.insertSpaces
};
}
export class DocumentFormattingEditProvider implements monaco.languages.DocumentFormattingEditProvider {
constructor(private _worker: WorkerAccessor) {
}
public provideDocumentFormattingEdits(model: monaco.editor.IReadOnlyModel, options: monaco.languages.FormattingOptions, token: CancellationToken): Thenable<monaco.editor.ISingleEditOperation[]> {
const resource = model.uri;
return this._worker(resource).then(worker => {
return worker.format(resource.toString(), null, fromFormattingOptions(options)).then(edits => {
if (!edits || edits.length === 0) {
return;
}
return edits.map(toTextEdit);
});
});
}
}
export class DocumentRangeFormattingEditProvider implements monaco.languages.DocumentRangeFormattingEditProvider {
constructor(private _worker: WorkerAccessor) {
}
public provideDocumentRangeFormattingEdits(model: monaco.editor.IReadOnlyModel, range: Range, options: monaco.languages.FormattingOptions, token: CancellationToken): Thenable<monaco.editor.ISingleEditOperation[]> {
const resource = model.uri;
return this._worker(resource).then(worker => {
return worker.format(resource.toString(), fromRange(range), fromFormattingOptions(options)).then(edits => {
if (!edits || edits.length === 0) {
return;
}
return edits.map(toTextEdit);
});
});
}
}
export class DocumentColorAdapter implements monaco.languages.DocumentColorProvider {
constructor(private _worker: WorkerAccessor) {
}
public provideDocumentColors(model: monaco.editor.IReadOnlyModel, token: CancellationToken): Thenable<monaco.languages.IColorInformation[]> {
const resource = model.uri;
return this._worker(resource).then(worker => worker.findDocumentColors(resource.toString())).then(infos => {
if (!infos) {
return;
}
return infos.map(item => ({
color: item.color,
range: toRange(item.range)
}));
});
}
public provideColorPresentations(model: monaco.editor.IReadOnlyModel, info: monaco.languages.IColorInformation, token: CancellationToken): Thenable<monaco.languages.IColorPresentation[]> {
const resource = model.uri;
return this._worker(resource).then(worker => worker.getColorPresentations(resource.toString(), info.color, fromRange(info.range))).then(presentations => {
if (!presentations) {
return;
}
return presentations.map(presentation => {
let item: monaco.languages.IColorPresentation = {
label: presentation.label,
};
if (presentation.textEdit) {
item.textEdit = toTextEdit(presentation.textEdit)
}
if (presentation.additionalTextEdits) {
item.additionalTextEdits = presentation.additionalTextEdits.map(toTextEdit)
}
return item;
});
});
}
}
export class FoldingRangeAdapter implements monaco.languages.FoldingRangeProvider {
constructor(private _worker: WorkerAccessor) {
}
public provideFoldingRanges(model: monaco.editor.IReadOnlyModel, context: monaco.languages.FoldingContext, token: CancellationToken): Thenable<monaco.languages.FoldingRange[]> {
const resource = model.uri;
return this._worker(resource).then(worker => worker.getFoldingRanges(resource.toString(), context)).then(ranges => {
if (!ranges) {
return;
}
return ranges.map(range => {
let result: monaco.languages.FoldingRange = {
start: range.startLine + 1,
end: range.endLine + 1
};
if (typeof range.kind !== 'undefined') {
result.kind = toFoldingRangeKind(<jsonService.FoldingRangeKind>range.kind);
}
return result;
});
});
}
}
function toFoldingRangeKind(kind: jsonService.FoldingRangeKind): monaco.languages.FoldingRangeKind {
switch (kind) {
case jsonService.FoldingRangeKind.Comment: return monaco.languages.FoldingRangeKind.Comment;
case jsonService.FoldingRangeKind.Imports: return monaco.languages.FoldingRangeKind.Imports;
case jsonService.FoldingRangeKind.Region: return monaco.languages.FoldingRangeKind.Region;
}
return void 0;
}
export class SelectionRangeAdapter implements monaco.languages.SelectionRangeProvider {
constructor(private _worker: WorkerAccessor) {
}
public provideSelectionRanges(model: monaco.editor.IReadOnlyModel, positions: Position[], token: CancellationToken): Thenable<monaco.languages.SelectionRange[][]> {
const resource = model.uri;
return this._worker(resource).then(worker => worker.getSelectionRanges(resource.toString(), positions.map(fromPosition))).then(selectionRanges => {
if (!selectionRanges) {
return;
}
return selectionRanges.map(selectionRange => {
const result: monaco.languages.SelectionRange[] = [];
while (selectionRange) {
result.push({ range: toRange(selectionRange.range) });
selectionRange = selectionRange.parent;
}
return result;
});
});
}
}
|
Bhaskers-Blu-Org2/monaco-json
|
src/jsonMode.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { WorkerManager } from './workerManager';
import { JSONWorker } from './jsonWorker';
import { LanguageServiceDefaultsImpl } from './monaco.contribution';
import * as languageFeatures from './languageFeatures';
import { createTokenizationSupport } from './tokenization';
import Uri = monaco.Uri;
import IDisposable = monaco.IDisposable;
export function setupMode(defaults: LanguageServiceDefaultsImpl): IDisposable {
const disposables: IDisposable[] = [];
const providers: IDisposable[] = [];
const client = new WorkerManager(defaults);
disposables.push(client);
const worker: languageFeatures.WorkerAccessor = (...uris: Uri[]): Promise<JSONWorker> => {
return client.getLanguageServiceWorker(...uris);
};
function registerProviders(): void {
const { languageId, modeConfiguration } = defaults;
disposeAll(providers);
if (modeConfiguration.documentFormattingEdits) {
providers.push(monaco.languages.registerDocumentFormattingEditProvider(languageId, new languageFeatures.DocumentFormattingEditProvider(worker)));
}
if (modeConfiguration.documentRangeFormattingEdits) {
providers.push(monaco.languages.registerDocumentRangeFormattingEditProvider(languageId, new languageFeatures.DocumentRangeFormattingEditProvider(worker)));
}
if (modeConfiguration.completionItems) {
providers.push(monaco.languages.registerCompletionItemProvider(languageId, new languageFeatures.CompletionAdapter(worker)));
}
if (modeConfiguration.hovers) {
providers.push(monaco.languages.registerHoverProvider(languageId, new languageFeatures.HoverAdapter(worker)));
}
if (modeConfiguration.documentSymbols) {
providers.push(monaco.languages.registerDocumentSymbolProvider(languageId, new languageFeatures.DocumentSymbolAdapter(worker)));
}
if (modeConfiguration.tokens) {
providers.push(monaco.languages.setTokensProvider(languageId, createTokenizationSupport(true)));
}
if (modeConfiguration.colors) {
providers.push(monaco.languages.registerColorProvider(languageId, new languageFeatures.DocumentColorAdapter(worker)));
}
if (modeConfiguration.foldingRanges) {
providers.push(monaco.languages.registerFoldingRangeProvider(languageId, new languageFeatures.FoldingRangeAdapter(worker)));
}
if (modeConfiguration.diagnostics) {
providers.push(new languageFeatures.DiagnosticsAdapter(languageId, worker, defaults));
}
if (modeConfiguration.selectionRanges) {
providers.push(monaco.languages.registerSelectionRangeProvider(languageId, new languageFeatures.SelectionRangeAdapter(worker)));
}
}
registerProviders();
disposables.push(monaco.languages.setLanguageConfiguration(defaults.languageId, richEditConfiguration));
let modeConfiguration = defaults.modeConfiguration;
defaults.onDidChange((newDefaults) => {
if (newDefaults.modeConfiguration !== modeConfiguration) {
modeConfiguration = newDefaults.modeConfiguration;
registerProviders();
}
});
disposables.push(asDisposable(providers));
return asDisposable(disposables);
}
function asDisposable(disposables: IDisposable[]): IDisposable {
return { dispose: () => disposeAll(disposables) };
}
function disposeAll(disposables: IDisposable[]) {
while (disposables.length) {
disposables.pop().dispose();
}
}
const richEditConfiguration: monaco.languages.LanguageConfiguration = {
wordPattern: /(-?\d*\.\d\w*)|([^\[\{\]\}\:\"\,\s]+)/g,
comments: {
lineComment: '//',
blockComment: ['/*', '*/']
},
brackets: [
['{', '}'],
['[', ']']
],
autoClosingPairs: [
{ open: '{', close: '}', notIn: ['string'] },
{ open: '[', close: ']', notIn: ['string'] },
{ open: '"', close: '"', notIn: ['string'] }
]
};
|
Bhaskers-Blu-Org2/monaco-json
|
src/monaco.contribution.ts
|
<filename>src/monaco.contribution.ts
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as mode from './jsonMode';
import Emitter = monaco.Emitter;
import IEvent = monaco.IEvent;
// --- JSON configuration and defaults ---------
export class LanguageServiceDefaultsImpl implements monaco.languages.json.LanguageServiceDefaults {
private _onDidChange = new Emitter<monaco.languages.json.LanguageServiceDefaults>();
private _diagnosticsOptions: monaco.languages.json.DiagnosticsOptions;
private _modeConfiguration: monaco.languages.json.ModeConfiguration;
private _languageId: string;
constructor(languageId: string, diagnosticsOptions: monaco.languages.json.DiagnosticsOptions, modeConfiguration: monaco.languages.json.ModeConfiguration) {
this._languageId = languageId;
this.setDiagnosticsOptions(diagnosticsOptions);
this.setModeConfiguration(modeConfiguration);
}
get onDidChange(): IEvent<monaco.languages.json.LanguageServiceDefaults> {
return this._onDidChange.event;
}
get languageId(): string {
return this._languageId;
}
get modeConfiguration(): monaco.languages.json.ModeConfiguration {
return this._modeConfiguration;
}
get diagnosticsOptions(): monaco.languages.json.DiagnosticsOptions {
return this._diagnosticsOptions;
}
setDiagnosticsOptions(options: monaco.languages.json.DiagnosticsOptions): void {
this._diagnosticsOptions = options || Object.create(null);
this._onDidChange.fire(this);
}
setModeConfiguration(modeConfiguration: monaco.languages.json.ModeConfiguration): void {
this._modeConfiguration = modeConfiguration || Object.create(null);
this._onDidChange.fire(this);
};
}
const diagnosticDefault: Required<monaco.languages.json.DiagnosticsOptions> = {
validate: true,
allowComments: true,
schemas: [],
enableSchemaRequest: false
};
const modeConfigurationDefault: Required<monaco.languages.json.ModeConfiguration> = {
documentFormattingEdits: true,
documentRangeFormattingEdits: true,
completionItems: true,
hovers: true,
documentSymbols: true,
tokens: true,
colors: true,
foldingRanges: true,
diagnostics: true,
selectionRanges: true
}
const jsonDefaults = new LanguageServiceDefaultsImpl('json', diagnosticDefault, modeConfigurationDefault);
// Export API
function createAPI(): typeof monaco.languages.json {
return {
jsonDefaults: jsonDefaults
}
}
monaco.languages.json = createAPI();
// --- Registration to monaco editor ---
function getMode(): Promise<typeof mode> {
return import('./jsonMode');
}
monaco.languages.register({
id: 'json',
extensions: ['.json', '.bowerrc', '.jshintrc', '.jscsrc', '.eslintrc', '.babelrc', '.har'],
aliases: ['JSON', 'json'],
mimetypes: ['application/json'],
});
monaco.languages.onLanguage('json', () => {
getMode().then(mode => mode.setupMode(jsonDefaults));
});
|
Modelata/fire
|
src/decorators/deletion-mode.decorator.ts
|
import 'reflect-metadata';
import { MFDeleteMode } from '../enums/mf-delete-mode.enum';
/**
* Sets default deletion mode of the targetted DAO
*
* @param mode hard or soft mode (default: hard)
*/
export function DeletionMode(mode: MFDeleteMode): any {
// eslint-disable-next-line @typescript-eslint/ban-types
return (target: Object) => {
Reflect.defineMetadata('deletionMode', mode, target);
};
}
|
Modelata/fire
|
src/interfaces/tool-types.ts
|
<reponame>Modelata/fire
// eslint-disable-next-line @typescript-eslint/ban-types
export declare type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
export declare type MFOmit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
|
Modelata/fire
|
config/angular.exports.ts
|
<gh_stars>0
import firebase from 'firebase/compat/app';
import { Observable } from 'rxjs';
export declare type OrderByDirection = firebase.firestore.OrderByDirection;
export declare type WhereFilterOp = firebase.firestore.WhereFilterOp;
export declare type DocumentReference<M> = firebase.firestore.DocumentReference;
export declare type CollectionReference<M> = firebase.firestore.CollectionReference;
export declare type DocumentData = firebase.firestore.DocumentData;
export declare type DocumentSnapshot<T> = DocumentSnapshotExists<T> | DocumentSnapshotDoesNotExist;
export declare type AsyncType<M> = Observable<M>;
export interface DocumentSnapshotExists<T> extends firebase.firestore.DocumentSnapshot {
readonly exists: true;
data(options?: firebase.firestore.SnapshotOptions): T;
}
export interface DocumentSnapshotDoesNotExist extends firebase.firestore.DocumentSnapshot {
readonly exists: false;
data(options?: firebase.firestore.SnapshotOptions): undefined;
get(fieldPath: string | firebase.firestore.FieldPath, options?: firebase.firestore.SnapshotOptions): undefined;
}
export interface QueryDocumentSnapshot<T> extends firebase.firestore.QueryDocumentSnapshot {
data(options?: firebase.firestore.SnapshotOptions): T;
}
|
Modelata/fire
|
src/helpers/object.helper.ts
|
import { MFLogger } from '../mf-logger';
/**
* creates an hidden property in the given object
*
* @param obj the object to create the attribute on
* @param propName the name of the property
* @param propVal the value of the property
*/
export function createHiddenProperty(obj: { [key: string]: any }, propName: string, propVal: any): void {
if (obj) {
const hiddenPropName = `_${propName}`;
// eslint-disable-next-line no-prototype-builtins
if (obj.hasOwnProperty(hiddenPropName)) {
obj[hiddenPropName] = propVal;
} else {
Object.defineProperty(obj, hiddenPropName, {
value: propVal,
enumerable: false,
configurable: true,
writable: true
});
}
} else {
MFLogger.error('you must define an object to set it an hidden property');
}
}
|
Modelata/fire
|
src/decorators/users-collection-path.decorator.ts
|
<reponame>Modelata/fire
import 'reflect-metadata';
/**
* Sets userCollectionPath attribute of the targetted AuthDAO
*
* @param path user collection path
*/
export function UsersCollectionPath(path: string): any {
// eslint-disable-next-line @typescript-eslint/ban-types
return (target: Object) => {
Reflect.defineMetadata('usersCollectionPath', path, target);
};
}
|
Modelata/fire
|
src/helpers/model.helper.ts
|
<gh_stars>0
/* eslint-disable no-prototype-builtins */
import { IMFLocation, IMFModel } from '../interfaces';
import { mustache } from './string.helper';
import 'reflect-metadata';
import { MFLogger } from '../mf-logger';
/**
* Returns the path from a collection mustache path ad a location object.
*
* @param mustachePath Collection mustache path
* @param idOrLocation id or Location object containin path ids and document id or not.
* @returns The path filled with ids
*/
export function getPath<M extends IMFModel<M>>(mustachePath: string, idOrLocation?: string | Partial<IMFLocation>): string {
const realLocation = getLocation<M>(idOrLocation, mustachePath);
if (!(mustachePath && mustachePath.length)) {
throw new Error('@collectionPath() must be defined at the beginning of the DAO service');
}
let path = mustache(mustachePath, realLocation);
if (path.includes('{')) {
const missingIdRegex = /{(.*?)}/g;
const missingIds: string[] = [];
let missingId;
while ((missingId = missingIdRegex.exec(path)) !== null) {
missingIds.push(missingId[1]);
}
throw new Error(`Failed to fill "${missingIds.join('", ')}" parameter(s) in the path "${mustachePath}" (with the provided location "${idOrLocation}") => please check the location parameter of your query`);
}
if (realLocation.id) {
path += `${path.endsWith('/') ? '' : '/'}${realLocation.id}`;
}
return path;
}
/**
* Returns true if the document path is in the same format as the collection path (meaning the document is from this kind of collection)
* or false if it doesn't
*
* @param mustachePath Collection path
* @param refPath Document path
* @returns boolean
*/
export function isCompatiblePath(mustachePath: string, refPath: string): boolean {
if (mustachePath && refPath) {
const { pathSplitted, mustachePathSplitted } = getSplittedPath(refPath, mustachePath);
if (mustachePathSplitted.length < pathSplitted.length - 1 || mustachePathSplitted.length > pathSplitted.length) {
return false;
}
return mustachePathSplitted.every((path, index) => {
return pathSplitted[index] && (path.startsWith('{') || pathSplitted[index] === path);
});
}
return false;
}
/**
* Return a location object from either unvalued, string id, location object or model
*
* @param idOrLocationOrModel string id or location object
* @returns The location built from params
*/
export function getLocation<M extends IMFModel<M>>(
idOrLocationOrModel?: string | Partial<IMFLocation> | M,
mustachePath?: string
): Partial<IMFLocation> {
MFLogger.debugLibrary('ModelHelper getLocation', idOrLocationOrModel, mustachePath);
if (idOrLocationOrModel) {
if (typeof idOrLocationOrModel === 'string') {
return { id: idOrLocationOrModel };
}
if (idOrLocationOrModel.hasOwnProperty('_collectionPath') && mustachePath) {
return getLocationFromPath((idOrLocationOrModel._collectionPath as string), mustachePath, idOrLocationOrModel._id) as IMFLocation;
}
return idOrLocationOrModel as Partial<IMFLocation>;
}
return {};
}
/**
* Returns a location object from path and mustache path
*
* @param path the path to convert to a location
* @param mustachePath the collectionPath with mustache ids
* @param id document id
* @returns The location object built from params
*/
export function getLocationFromPath(path: string, mustachePath: string, id?: string): Partial<IMFLocation> {
if (path && mustachePath) {
const { pathSplitted, mustachePathSplitted } = getSplittedPath(path, mustachePath);
return mustachePathSplitted.reduce(
(location: Partial<IMFLocation>, partOfMustachePath: string, index: number) => {
if (partOfMustachePath.startsWith('{')) {
location[partOfMustachePath.slice(1, -1)] = pathSplitted[index];
}
return location;
},
{
id
});
}
return {};
}
/**
* Returns arrays of elements constituting model path and mustache path
*
* @param path Model path
* @param mustachePath Dao mustache path
* @returns an object containing the path splitted and the mustache path splitted too
*/
export function getSplittedPath(path: string, mustachePath: string): {
pathSplitted: string[],
mustachePathSplitted: string[],
} {
const pathSplitted = path.split('/');
const mustachePathSplitted = mustachePath.split('/');
if (pathSplitted[0] === '') {
pathSplitted.shift();
}
if (pathSplitted[pathSplitted.length - 1] === '') {
pathSplitted.pop();
}
if (mustachePathSplitted[0] === '') {
mustachePathSplitted.shift();
}
if (mustachePathSplitted[mustachePathSplitted.length - 1] === '') {
mustachePathSplitted.pop();
}
return {
pathSplitted,
mustachePathSplitted,
};
}
/**
* Returns true if every property of data exists in model. Else, returns false
*
* @param data Data that will be checked
* @param model Model in wich data must fit
* @param logInexistingData Optional: display log for property missing in model (default is true)
*/
export function allDataExistInModel<M extends IMFModel<M>>(data: Partial<M>, model: M, logInexistingData = true): boolean {
for (const key in data) {
if (typeof model[key] !== 'function' && !model.hasOwnProperty(key.includes('.') ? key.split('.')[0] : key)) {
if (logInexistingData) {
MFLogger.error(`try to update/add an attribute that is not defined in the model = ${key}`);
}
return false;
}
}
return true;
}
/**
* method used to prepare the data for save removing methods and hidden properties (underscore prefixed).
*
* @param modelObj the data to save
* @returns the object cleaned from properties and methods that will not be saved in database
*/
export function getSavableData<M extends IMFModel<M>>(modelObj: Partial<M>): Partial<M> {
return Object.keys(modelObj)
.filter(key =>
!isHiddenProperty(key as string) &&
typeof modelObj[(key as keyof M)] !== 'undefined' &&
typeof modelObj[(key as keyof M)] !== 'function'
)
.reduce(
(dbObj: Partial<M>, keyp) => {
const key: keyof M = keyp as keyof M;
if (modelObj[key] && (modelObj[key] as any).constructor.name === 'Object') {
// if (modelObj[key] && typeof modelObj[key] === 'object') {
(dbObj[key] as any) = getSavableData<any>((modelObj[key] as any));
} else {
dbObj[key] = modelObj[key];
}
return dbObj;
},
{}
);
}
export function clearNullAttributes<M extends IMFModel<M>>(modelToClear: Partial<M>): Partial<M> {
return Object.keys(modelToClear)
.filter(key => !(modelToClear[key as keyof M] == null))
.reduce(
(clearedObj: Partial<M>, keyp) => {
const key: keyof M = keyp as keyof M;
if (
modelToClear[key] &&
(modelToClear[key] as any).constructor.name === 'Object'
) {
(clearedObj[key] as any) = getSavableData<any>(
modelToClear[key] as any,
);
} else {
clearedObj[key] = modelToClear[key];
}
return clearedObj;
},
{},
);
}
/**
* returns list of AuthUser properties defined in the model
*
* @param model The model object
* @return array of AuthUser properties names
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export function getAuthUserProperties(model: Object): string[] {
return Object.keys(model).filter((key) => {
// eslint-disable-next-line @typescript-eslint/ban-types
return Reflect.hasMetadata('authUserProperty', model as Object, key);
});
}
/**
* returns list of file(s) properties defined in the model
*
* @param model The model object
* @return array of file properties names
*/
export function getFileProperties<M extends IMFModel<M>>(model: Partial<M>): string[] {
return Object.keys(model).filter((key: string) => {
return Reflect.hasMetadata('storageProperty', model, key) || (model as any)[key] && (model as any)[key]._file instanceof File;
});
}
/**
* returns list of subPath in model
*
* @param model The model object
*/
export function getSubPaths<M extends IMFModel<M>>(model: M): string[] {
return Array.from(new Set(Object.keys(model).map((key) => {
if (Reflect.hasMetadata('subDocPath', model, key)) {
return Reflect.getMetadata('subDocPath', model, key);
}
return null;
}).filter(a => !!a)));
}
/**
* Returns main model merged with properties from subModels
*
* @param mainModel The main model (container)
* @param subModels The sub models (where nested data can be found)
* @returns The main model merged with all data
*/
export function mergeModels<M>(mainModel: M, subModels: { [subPath: string]: IMFModel<any> }): M {
Object.keys(mainModel).forEach((key) => {
if (
Reflect.hasMetadata('subDocPath', mainModel, key)
) {
const subPath = Reflect.getMetadata('subDocPath', mainModel, key);
if (
subModels.hasOwnProperty(subPath) &&
// eslint-disable-next-line @typescript-eslint/ban-types
(subModels[subPath] as Object).hasOwnProperty(key)
) {
(mainModel as any)[key] = (subModels[subPath] as any)[key];
}
}
});
return mainModel;
}
export function isHiddenProperty(propertyName: string): boolean {
return !!(propertyName && propertyName.startsWith('_'));
}
export function isDaoObject(param: unknown): boolean {
if (param && typeof param === 'object') {
// eslint-disable-next-line @typescript-eslint/ban-types
const obj = param as Object;
return (obj.constructor &&
(obj.constructor as any).__proto__ &&
(obj.constructor as any).__proto__.name === 'MFDao')
||
(obj.hasOwnProperty &&
obj.hasOwnProperty('db') &&
obj.hasOwnProperty('mustachePath'));
}
return false;
}
|
Modelata/fire
|
src/helpers/firestore.helper.ts
|
<filename>src/helpers/firestore.helper.ts
import { DocumentData } from './../specifics/exports';
export function convertDataFromDb(data: DocumentData): DocumentData {
if (data) {
for (const key in data) {
// eslint-disable-next-line no-prototype-builtins
if (data.hasOwnProperty(key) && data[key]) {
if (typeof (data[key] as any).toDate === 'function') {
// attribute is a Firebase Timestamp
data[key] = (data[key] as any).toDate();
} else if (typeof (data[key] as any) === 'object') {
// attribute is an object or an array
if (Object.keys(data[key]).length > 0 && !isDocumentReference(data[key])) {
data[key] = convertDataFromDb(data[key]);
}
}
}
}
}
return data;
}
export function isDocumentReference(data: any): boolean {
return !!(data && data.id && data.parent && data.path && data.firestore);
}
|
Amirhoseinpg/myshoppingapi
|
src/http-exception.filter.ts
|
import { ArgumentsHost, Catch, ExceptionFilter, HttpException ,HttpStatus} from '@nestjs/common';
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
response.status(status).render("e.g.404.ejs",{
statusCode: status,
response: exception.getResponse(),
pageTitle: `Error ${status}`,
})
}
}
|
Amirhoseinpg/myshoppingapi
|
test/constant.ts
|
import 'dotenv/config';
export const app=`http://localhost:${process.env.PORT}`
export const database=process.env.MONGO_TEST;
|
Amirhoseinpg/myshoppingapi
|
src/interfaces/product.ts
|
import { Document } from 'mongoose';
export interface Product extends Document {
title: string;
image: string;
description: string;
price: number;
created: Date;
}
|
Amirhoseinpg/myshoppingapi
|
src/app.controller.ts
|
import { Controller, Get, Render } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
@Render("index.ejs")
mainroot(){
return {pageTitle:"محصولات"}
}
@Get("/create")
@Render("create.ejs")
createroot(){
return {pageTitle:"ساخت محصول"}
}
@Get("/delete")
@Render("delete.ejs")
deleteroot(){
return {pageTitle:"حذف محصول"}
}
@Get("/update")
@Render("update.ejs")
updateroot(){
return {pageTitle:"بروزرسانی محصول"}
}
@Get("/showallproduct")
@Render("showall.ejs")
Showallroot(){
return {pageTitle:"نمایش همه محصولات"}
}
@Get("/showproduct")
@Render("show.ejs")
Showproduct(){
return {pageTitle:"نمایش محصول"}
}
}
|
Amirhoseinpg/myshoppingapi
|
test/product.e2e-spec.ts
|
import { CreateProductDTO } from './../dist/product/product.dto.d';
import * as mongoose from 'mongoose'
import axios from 'axios'
import * as request from 'supertest'
import { app, database } from './constant'
import { HttpStatus } from '@nestjs/common';
beforeAll(async () => {
await mongoose.connect(database);
await mongoose.connection.db.dropDatabase();
});
afterAll(async done => {
await mongoose.disconnect(done);
});
describe("PRODUCT",()=>{
const product: CreateProductDTO = {
title: 'new phone',
image: '/qwerr/asd',
description: 'description',
price: 10,
};
let productId:string;
it("should list all products",()=>{
return request(app)
.get("/api/products")
.expect(200)
});
it("should create product",()=>{
return request(app)
.post("/api/products")
.send(product)
.expect(({body})=>{
expect(body._id).toBeDefined();
productId = body._id;
expect(body.title).toEqual(product.title);
expect(body.description).toEqual(product.description);
expect(body.price).toEqual(product.price);
})
.expect(HttpStatus.CREATED)
});
it("should read product",()=>{
return request(app)
.get(`/api/products/${productId}`)
.expect(({ body }) => {
expect(body._id).toEqual(productId)
expect(body.title).toEqual(product.title);
expect(body.description).toEqual(product.description);
expect(body.price).toEqual(product.price);
})
.expect(200);
});
it("should update product",()=>{
return request(app)
.put(`/api/products/${productId}`)
.set('Accept', 'application/json')
.send({
title: 'testTitle',
})
.expect(({ body }) => {
expect(body._id).toEqual(productId)
expect(body.title).not.toEqual(product.title);
expect(body.description).toEqual(product.description);
expect(body.price).toEqual(product.price);
})
.expect(200);
})
it("should delete product",async ()=>{
await axios.delete(`${app}/api/products/${productId}`)
return request(app)
.get(`/api/products/${productId}`)
.expect(404);
})
})
|
Amirhoseinpg/myshoppingapi
|
test/app.e2e-spec.ts
|
<reponame>Amirhoseinpg/myshoppingapi<filename>test/app.e2e-spec.ts<gh_stars>0
import 'dotenv/config'
import * as request from 'supertest';
import {app} from './constant'
describe('ROOT', () => {
it('should connect and ping', () => {
return request(app)
.get('/')
.expect(200)
.expect('Content-Type',"text/html; charset=utf-8");
});
it('should connect and ping', () => {
return request(app)
.get('/create')
.expect(200)
.expect('Content-Type',"text/html; charset=utf-8");
});
it('should connect and ping', () => {
return request(app)
.get('/delete')
.expect(200)
.expect('Content-Type',"text/html; charset=utf-8");
});
it('should connect and ping', () => {
return request(app)
.get('/update')
.expect(200)
.expect('Content-Type',"text/html; charset=utf-8");
});
it('should connect and ping', () => {
return request(app)
.get('/showallproduct')
.expect(200)
.expect('Content-Type',"text/html; charset=utf-8");
});
it('should connect and ping', () => {
return request(app)
.get('/showproduct')
.expect(200)
.expect('Content-Type',"text/html; charset=utf-8");
});
});
|
Amirhoseinpg/myshoppingapi
|
src/product/product.dto.ts
|
export interface CreateProductDTO {
title: string;
image: string;
description: string;
price: number;
}
export type UpdateProductDTO = Partial<CreateProductDTO>;
|
Amirhoseinpg/myshoppingapi
|
src/product/product.service.ts
|
<reponame>Amirhoseinpg/myshoppingapi<filename>src/product/product.service.ts<gh_stars>0
import { CreateProductDTO, UpdateProductDTO } from './product.dto';
import { Product } from './../interfaces/product';
import { HttpException, HttpStatus, Injectable, NotFoundException,} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import {Model} from 'mongoose'
@Injectable()
export class ProductService {
constructor(@InjectModel("Product") private productModel:
Model<Product>){}
/**
* Returns a list with all products
* available in the database.
*/
public async findAll():Promise<Product[]>{
const allProduct= await this.productModel.find().exec()
return allProduct;
}
/**
* Returns a product based on an id.
*
*/
public async findone(id:string):Promise<Product>{
try {
const product= await this.productModel.findById(id)
if(!product){
throw new HttpException("product does not exist",HttpStatus.NO_CONTENT)
}
return product
} catch (error) {
throw new NotFoundException("cant find this product")
}
}
/**
* Create a product based on a DTO object
* for product: [CreateProductDTO].
*
*/
public async create(productDTO:CreateProductDTO):Promise <Product>{
const product = await this.productModel.create(productDTO)
await product.save();
return product
}
/**
* Update a product in Database
*
*/
public async update(id:string,productDTO:UpdateProductDTO):Promise <Product>{
const product = await this.productModel.findById(id)
if(!product){
throw new HttpException("product does not exist",HttpStatus.NO_CONTENT)
}
await product.update(productDTO);
return await this.productModel.findById(id)
}
/**
* Delete a product in the Database
*/
public async delete(id:string):Promise<Product>{
try {
const product = await this.productModel.findById(id)
await product.remove();
return product;
} catch (error) {
throw new NotFoundException("cant find this product")
}
}
}
|
Amirhoseinpg/myshoppingapi
|
src/product/product.controller.ts
|
<reponame>Amirhoseinpg/myshoppingapi
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
} from '@nestjs/common';
import { Product } from '../interfaces/product';
import { CreateProductDTO, UpdateProductDTO } from './product.dto';
import { ProductService } from './product.service';
@Controller('/api/products')
export class ProductController {
constructor(private productService: ProductService) {}
@Get()
async getAllProduct(): Promise<Product[]> {
return await this.productService.findAll()
}
@Post()
async createProduct(
@Body() product: CreateProductDTO,
): Promise<Product> {
return await this.productService.create(product);
}
@Get(':id')
async read(@Param('id') id: string): Promise<Product> {
return await this.productService.findone(id);
}
@Put(':id')
async updateProduct(
@Param('id') id: string,
@Body() product: UpdateProductDTO,
): Promise<Product> {
return await this.productService.update(id, product);
}
@Delete(':id')
async deleteProduct(
@Param('id') id: string,
): Promise<Product> {
return await this.productService.delete(id);
}
}
|
SproutProject/sptoj-web
|
src/api.ts
|
<reponame>SproutProject/sptoj-web<filename>src/api.ts
import axios from 'axios'
import * as _ from 'lodash'
import * as moment from 'moment-timezone'
import { User, UserCategory } from './user-service'
export interface PartialList<T> {
data: T[]
count: number
}
export interface Profile {
uid: number
name: string
category: UserCategory
rate?: number
}
interface TriedProblem {
[key: string]: { result: number }
}
export interface UserStatistic {
tried_problems: TriedProblem
}
export interface Problem {
uid: number
revision: string
name: string
timelimit: number
memlimit: number
lang: string
checker: string
subtask: number[]
}
export interface ProblemRate {
index: number
count: number
score: number
}
export interface ProItem {
uid: number
hidden: boolean
deadline: string | null
metadata: { section?: string }
problem: Problem
}
export interface ProSet {
uid: number
name: string
hidden: boolean
metadata: { category: number }
}
export enum JudgeState {
pending = 0,
judging = 1,
done = 2,
}
export interface Subtask {
uid: number
index: number
state: JudgeState
metadata: void
}
export interface Ranker {
profile: Profile
rate: number
results: { [key: number]: number }
}
export interface Challenge {
uid: number
state: JudgeState
timestamp: string
metadata: void
submitter: User
problem: Problem
subtasks?: Subtask[]
code?: string
}
export class ChallengeFilter {
user_uid: number | null | '' = null
problem_uid: number | null | '' = null
result: number | null = null
load(data: string) {
let obj = JSON.parse(data)
this.user_uid = obj['user_uid']
this.problem_uid = obj['problem_uid']
this.result = obj['result']
}
serialize(): string {
if (this.user_uid === '') {
this.user_uid = null
}
if (this.problem_uid === '') {
this.problem_uid = null
}
return JSON.stringify(this)
}
}
export async function emit<T>(path: string, data = {}): Promise<T> {
let result = await axios.post('/api' + path, data);
return result.data as T
}
export async function getProfile(user_uid: number): Promise<'Error' | Profile> {
return await emit<'Error' | Profile>(`/user/${user_uid}/profile`, {})
}
export async function getUserStatistic(user_uid: number): Promise<'Error' | UserStatistic> {
return await emit<'Error' | UserStatistic>(`/user/${user_uid}/statistic`, {})
}
export async function listUser(): Promise<'Error' | User[]> {
return await emit<'Error' | User[]>('/user/list', {})
}
export async function setUser(data: { uid: number, name: string, password?: string, category?: UserCategory }): Promise<'Error' | 'Success'> {
return await emit<'Error' | 'Success'>(`/user/${data.uid}/set`, data)
}
export async function removeUser(user_uid: number): Promise<'Error' | 'Success'> {
return await emit<'Error' | 'Success'>(`/user/${user_uid}/remove`, {})
}
export async function listProSet(): Promise<'Error' | ProSet[]> {
return await emit<'Error' | ProSet[]>('/proset/list', {})
}
export async function createProSet(name: string): Promise<'Error' | number> {
return await emit<'Error' | number>('/proset/create', {
name: name,
})
}
export async function getProSet(proset_uid: number): Promise<'Error' | ProSet> {
return await emit<'Error' | ProSet>(`/proset/${proset_uid}/get`, {})
}
export async function setProSet(proset: ProSet): Promise<'Error' | 'Success'> {
return await emit<'Error' | 'Success'>(`/proset/${proset.uid}/set`, proset)
}
export async function removeProSet(proset_uid: number): Promise<'Error' | 'Success'> {
return await emit<'Error' | 'Success'>(`/proset/${proset_uid}/remove`, {})
}
export async function addProItem(proset_uid: number, problem: Problem): Promise<'Error' | number> {
return await emit<'Error' | number>(`/proset/${proset_uid}/add`, {
problem_uid: problem.uid,
})
}
export async function getProItem(proset_uid: number, proitem_uid: number): Promise<'Error' | ProItem> {
let proitem = await emit<'Error' | ProItem>(`/proset/${proset_uid}/${proitem_uid}/get`, {})
if (proitem !== 'Error') {
if (proitem.deadline !== null) {
let date = moment(proitem.deadline, moment.ISO_8601).tz(moment.tz.guess())
proitem.deadline = date.format('YYYY/MM/DD')
}
}
return proitem
}
export async function setProItem(proset_uid: number, proitem: ProItem): Promise<'Error' | 'Success'> {
let modified_proitem = _.cloneDeep(proitem)
if (proitem.deadline === '') {
modified_proitem.deadline = null
} else if (proitem.deadline !== null) {
modified_proitem.deadline = proitem.deadline + '+0800'
}
return await emit<'Error' | 'Success'>(`/proset/${proset_uid}/${proitem.uid}/set`, modified_proitem)
}
export async function removeProItem(proset_uid: number, proitem_uid: number): Promise<'Error' | 'Success'> {
return await emit<'Error' | 'Success'>(`/proset/${proset_uid}/${proitem_uid}/remove`, {})
}
export async function listProItem(proset_uid: number): Promise<'Error' | ProItem[]> {
let proitems = await emit<'Error' | ProItem[]>(`/proset/${proset_uid}/list`, {})
if (proitems !== 'Error') {
for (let proitem of proitems) {
if (proitem.deadline !== null) {
let date = moment(proitem.deadline, moment.ISO_8601).tz(moment.tz.guess())
proitem.deadline = date.format('YYYY/MM/DD')
}
}
}
return proitems
}
export async function updateProblem(problem_uid: number, git_url: string): Promise<'Error' | 'Success'> {
return await emit<'Error' | 'Success'>(`/problem/${problem_uid}/update`, { git_url })
}
export async function removeProblem(problem_uid: number): Promise<'Error' | 'Success'> {
return await emit<'Error' | 'Success'>(`/problem/${problem_uid}/remove`, {})
}
export async function listProblem(): Promise<'Error' | { problem: Problem, git: string }[]> {
return await emit<'Error' | { problem: Problem, git: string }[]>(`/problem/list`, {})
}
export async function getProblem(problem_uid: number): Promise<'Error' | Problem> {
return await emit<'Error' | Problem>(`/problem/${problem_uid}/get`, {})
}
export async function getProblemRate(problem_uid: number, category: UserCategory): Promise<'Error' | ProblemRate[]> {
return await emit<'Error' | ProblemRate[]>(`/problem/${problem_uid}/rate`, { category })
}
export async function submit(problem_uid: number, code: string, lang: string): Promise<'Error' | number> {
return await emit<'Error' | number>(`/problem/${problem_uid}/submit`, { code, lang })
}
export async function rejudgeChallenge(problem_uid: number): Promise<'Error' | 'Success'> {
return await emit<'Error' | 'Success'>(`/challenge/rejudge`, { problem_uid })
}
export async function getChallenge(challenge_uid: number): Promise<'Error' | Challenge> {
let challenge = await emit<'Error' | Challenge>(`/challenge/${challenge_uid}/get`, {})
if (challenge !== 'Error') {
let date = moment(challenge.timestamp, moment.ISO_8601).tz(moment.tz.guess())
challenge.timestamp = date.format('YYYY/MM/DD HH:mm:ss')
}
return challenge
}
export async function listChallenge(offset: number, filter: ChallengeFilter | null = null): Promise<'Error' | (PartialList<Challenge | null>)> {
let partial_list = await emit<'Error' | (PartialList<Challenge | null>)>(`/challenge/list`, { offset, filter })
if (partial_list !== 'Error') {
for (let challenge of partial_list.data) {
if (challenge !== null) {
let date = moment(challenge.timestamp, moment.ISO_8601).tz(moment.tz.guess())
challenge.timestamp = date.format('YYYY/MM/DD HH:mm:ss')
}
}
}
return partial_list
}
export async function getRank(proset_uid: number): Promise<'Error' | Ranker[]> {
return await emit<'Error' | Ranker[]>(`/rank/${proset_uid}/list`, {})
}
export function getCategory(category: UserCategory): string {
switch(category) {
case UserCategory.universe: return 'Universe'
case UserCategory.algo: return 'Algo'
case UserCategory.clang: return 'CLang'
case UserCategory.pylang: return 'PyLang'
}
}
export function getResult(state: JudgeState, result: number, abbreviation=false): string {
if (abbreviation) {
switch (state) {
case JudgeState.pending: return 'PD'
case JudgeState.judging: return 'JD'
case JudgeState.done:
switch (result) {
case 1: return 'AC'
case 2: return 'WA'
case 3: return 'RE'
case 4: return 'TLE'
case 5: return 'MLE'
case 6: return 'CE'
default: return 'OTH'
}
default: return 'UNK'
}
} else {
switch (state) {
case JudgeState.pending: return 'Pending'
case JudgeState.judging: return 'Judging'
case JudgeState.done:
switch (result) {
case 1: return 'Accepted'
case 2: return 'Wrong Answer'
case 3: return 'Runtime Error'
case 4: return 'Time Limit Exceeded'
case 5: return 'Memory Limit Exceeded'
case 6: return 'Compile Error'
default: return 'Other'
}
default: return 'Unknown'
}
}
}
|
SproutProject/sptoj-web
|
src/user-service.ts
|
<reponame>SproutProject/sptoj-web<filename>src/user-service.ts
export enum UserLevel {
user = 3,
kernel = 0,
}
export enum UserCategory {
universe = 0,
algo = 1,
clang = 2,
pylang = 3,
}
export interface User {
uid: number
mail: string
name: string
level: UserLevel
category: UserCategory
}
export let login: boolean = false
export let identity: User | null = null
export function initialize(user: User) {
login = true
identity = user
}
|
gurwinderiam/Semantic-UI-React
|
src/modules/Modal/index.d.ts
|
<reponame>gurwinderiam/Semantic-UI-React
import { SemanticSIZES } from '../..';
import * as React from 'react';
interface ModalProps {
/** An element type to render as (string or function). */
as?: any;
/** A modal can reduce its complexity */
basic?: boolean;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** Icon */
closeIcon?:any;
/**
* Whether or not the Modal should close when the dimmer is clicked.
*/
closeOnDimmerClick?: boolean;
/** Whether or not the Modal should close when the document is clicked. */
closeOnDocumentClick?: boolean;
/** Initial value of open. */
defaultOpen?:boolean;
/** A modal can appear in a dimmer */
dimmer?: boolean | 'blurring' | 'inverted';
/**
* Called when a close event happens
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClose?: Function;
/**
* Called when the portal is mounted on the DOM
*
* @param {null}
* @param {object} data - All props.
*/
onMount?: Function;
/**
* Called when an open event happens
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onOpen?:Function;
/**
* Called when the dropdown is unmounted from the DOM
*
* @param {null}
* @param {object} data - All props.
*/
onUnmount?: Function;
open?: boolean;
/** The node where the modal should mount.. */
mountNode?: any;
/** A modal can vary in size */
size?: SemanticSIZES;
}
interface ModalClass extends React.ComponentClass<ModalProps> {
Header: typeof ModalHeader;
Content: typeof ModalContent;
Description: typeof ModalDescription;
Actions: typeof ModalActions;
}
export const Modal: ModalClass;
interface ModalHeaderProps {
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
}
export const ModalHeader: React.ComponentClass<ModalHeaderProps>;
interface ModalContentProps {
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** A modal can contain image content */
image?: boolean;
}
export const ModalContent: React.ComponentClass<ModalContentProps>;
interface ModalDescriptionProps {
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
}
export const ModalDescription: React.ComponentClass<ModalDescriptionProps>;
interface ModalActionsProps {
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
}
export const ModalActions: React.ComponentClass<ModalActionsProps>;
|
gurwinderiam/Semantic-UI-React
|
src/collections/Form/index.d.ts
|
<filename>src/collections/Form/index.d.ts
import { ButtonProps } from '../../elements/Button';
import {
ReactFocusEvents,
ReactFormEvents,
SemanticFormOnClick,
SemanticGenericOnClick,
SemanticWIDTHS
} from '../..';
import * as React from 'react';
import { InputProps } from '../../elements/Input/index';
import { DropdownProps } from '../../modules/Dropdown/index';
interface FormProps {
method?: 'get' | 'post';
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** Automatically show any error Message children */
error?: boolean;
/** A form can have its color inverted for contrast */
inverted?: boolean;
/** Automatically show a loading indicator */
loading?: boolean;
/**
* Called on submit
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props and the form's serialized values.
*/
onSubmit?: SemanticFormOnClick;
/** A comment can contain a form to reply to a comment. This may have arbitrary content. */
reply?: boolean;
/** Called onSubmit with the form node that returns the serialized form object */
serializer?: ()=>void; // TODO, check;
/** A form can vary in size */
size?: string;
/** Automatically show any success Message children */
success?: boolean;
/** Automatically show any warning Message children */
warning?: boolean;
/** Forms can automatically divide fields to be equal width */
widths?: SemanticWIDTHS | 'equal';
}
interface FormClass extends React.ComponentClass<FormProps> {
Field: typeof FormField;
Button: typeof FormButton;
Checkbox: typeof FormCheckbox;
Dropdown: typeof FormDropdown;
Group: typeof FormGroup;
Input: typeof FormInput;
Radio: typeof FormRadio;
Select: typeof FormSelect;
TextArea: typeof FormTextArea;
}
export const Form: FormClass;
interface FormFieldProps {
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/**
* A form control component (i.e. Dropdown) or HTML tagName (i.e. 'input').
* Extra FormField props are passed to the control component.
* Mutually exclusive with children.
*/
control?: any;
/** Individual fields may be disabled */
disabled?: any;
/** Individual fields may display an error state */
error?: boolean;
/** A field can have its label next to instead of above it */
inline?: boolean;
// Heads Up!
// Do not disallow children with `label` shorthand
// The `control` might accept a `label` prop and `children`
/** Mutually exclusive with children. */
label?: string;
/** A field can show that input is mandatory. Requires a label. */
required?: any;
/** Passed to the control component (i.e. <input type='password' />) */
type?: string;
/** A field can specify its width in grid columns */
width?: SemanticWIDTHS;
}
export const FormField: React.ComponentClass<FormFieldProps>;
interface FormButtonProps extends ButtonProps {
/** An element type to render as (string or function). */
as?: any;
control?: any;
width?: number;
}
export const FormButton: React.ComponentClass<FormButtonProps>;
interface FormCheckboxProps {
/** An element type to render as (string or function). */
as?: any;
control?: any;
label?: string;
name?: string;
placeholder?: string;
value?: string|number|Array<string>|Array<number>;
}
export const FormCheckbox: React.ComponentClass<FormCheckboxProps>;
interface FormDropdownProps extends DropdownProps {
/** An element type to render as (string or function). */
as?: any;
/** A FormField control prop */
control?: any;
label?: string;
name?: string;
placeholder?: string;
}
export const FormDropdown: React.ComponentClass<FormDropdownProps>;
interface FormGroupProps {
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** Fields can show related choices */
grouped?: boolean;
/** Multiple fields may be inline in a row */
inline?: boolean;
/** Fields Groups can specify their width in grid columns or automatically divide fields to be equal width */
widths?: SemanticWIDTHS | 'equal';
}
export const FormGroup: React.ComponentClass<FormGroupProps>;
interface FormInputProps extends InputProps {
}
export const FormInput: React.ComponentClass<FormInputProps>;
interface FormRadioProps {
/** An element type to render as (string or function). */
as?: any;
checked?: boolean;
/** A FormField control prop */
control?: any;
label?: string;
name?: string;
onChange?: SemanticGenericOnClick;
placeholder?: string;
value?: string|number|Array<string>|Array<number>;
}
export const FormRadio: React.ComponentClass<FormRadioProps>;
interface FormSelectProps extends ReactFormEvents<HTMLSelectElement>, ReactFocusEvents<HTMLSelectElement> {
/** An element type to render as (string or function). */
as?: any;
/** A FormField control prop */
control?: any;
label?: string;
multiple?: boolean;
name?: string;
options?: any;
placeholder?: string;
search?: boolean;
width?: number;
compact?: boolean;
}
export const FormSelect: React.ComponentClass<FormSelectProps>;
export interface FormTextAreaProps extends ReactFormEvents<HTMLTextAreaElement>, ReactFocusEvents<HTMLTextAreaElement> {
/** An element type to render as (string or function). */
as?: any;
/** A FormField control prop */
control?: any;
label?: string;
name?: string;
options?: any;
placeholder?: string;
rows?: string|number;
width?: number;
}
export const FormTextArea: React.ComponentClass<FormTextAreaProps>;
|
gurwinderiam/Semantic-UI-React
|
src/modules/Popup/index.d.ts
|
import { SemanticPOSITIONING, SemanticSIZES } from '../..';
import { PortalProps } from '../../addons/Portal';
export type PopupPropOn = 'hover' | 'click' | 'focus';
interface PopupProps extends PortalProps {
/** Display the popup without the pointing arrow */
basic?: boolean;
/** Primary content. */
children?: React.ReactNode;
/** Shorthand for primary content. */
content?: any;
/** A Flowing popup have no maximum width and continue to flow to fit its content */
flowing?: boolean;
/** Header displayed above the content in bold */
header?: string;
/** The node where the popup should mount.. */
hideOnScroll?: boolean;
/** Whether the popup should not close on hover */
hoverable?: boolean;
/** Invert the colors of the popup */
inverted?: boolean;
/** Horizontal offset in pixels to be applied to the popup */
offset?: number;
/** Event triggering the popup */
on?: PopupPropOn;
/** Positioning for the popover */
positioning?: SemanticPOSITIONING;
/** Popup size */
size?: SemanticSIZES;
/** custom popup style */
style?: Object;
/** Popup width */
wide?: boolean | 'very';
}
interface PopupClass extends React.ComponentClass<PopupProps> {
Content: typeof PopupContent;
Header: typeof PopupHeader;
}
export const Popup: PopupClass;
interface PopupContentProps {
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
}
export const PopupContent: React.ComponentClass<PopupContentProps>;
interface PopupHeaderProps {
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
}
export const PopupHeader: React.ComponentClass<PopupHeaderProps>;
|
gurwinderiam/Semantic-UI-React
|
src/elements/Flag/index.d.ts
|
<filename>src/elements/Flag/index.d.ts
import * as React from 'react';
import { SemanticCOUNTRY } from '../..';
interface FlagProps {
[key: string]: any;
/** An element type to render as (string or function). */
as?: any;
/** Additional classes. */
className?: string;
/** Flag name, can use the two digit country code, the full name, or a common alias. */
name: SemanticCOUNTRY;
}
export const Flag : React.StatelessComponent<FlagProps>;
|
gurwinderiam/Semantic-UI-React
|
src/collections/Menu/index.d.ts
|
<reponame>gurwinderiam/Semantic-UI-React
import * as React from 'react';
import { SemanticCOLORS, SemanticWIDTHS } from '../..';
export interface MenuProps {
[key: string]: any;
/** An element type to render as (string or function). */
as?: any;
/** Index of the currently active item. */
activeIndex?: number;
/** A menu may be attached to other content segments. */
attached?: boolean | 'bottom' | 'top';
/** A menu item or menu can have no borders. */
borderless?: boolean;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** Additional colors can be specified. */
color?: SemanticCOLORS;
/** A menu can take up only the space necessary to fit its content. */
compact?: boolean;
/** Initial activeIndex value. */
defaultActiveIndex?: number;
/** A menu can be fixed to a side of its context. */
fixed?: 'left'| 'right'| 'bottom'| 'top';
/** A menu can be floated. */
floated?: boolean | 'right';
/** A vertical menu may take the size of its container. */
fluid?: boolean;
/** A menu may have labeled icons. */
icon?: boolean | 'labeled';
/** A menu may have its colors inverted to show greater contrast. */
inverted?: boolean;
/** Shorthand array of props for Menu. */
items?: Array<any>;
/**
* onClick handler for MenuItem. Mutually exclusive with children.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All item props.
*/
onItemClick?: (event: React.MouseEvent<HTMLAnchorElement>, data: MenuItemProps) => void;
/** A pagination menu is specially formatted to present links to pages of content. */
pagination?: boolean;
/** A menu can point to show its relationship to nearby content. */
pointing?: boolean;
/** A menu can adjust its appearance to de-emphasize its contents. */
secondary?: boolean;
/** A menu can vary in size. */
size?: 'mini' | 'tiny' | 'small' | 'large' | 'huge' | 'massive';
/** A menu can stack at mobile resolutions. */
stackable?: boolean;
/** A menu can be formatted to show tabs of information. */
tabular?: boolean | 'right';
/** A menu can be formatted for text content. */
text?: boolean;
/** A vertical menu displays elements vertically. */
vertical?: boolean;
/** A menu can have its items divided evenly. */
widths?: SemanticWIDTHS;
}
interface MenuComponent extends React.ComponentClass<MenuProps> {
Header: typeof MenuHeader;
Item: typeof MenuItem;
Menu: typeof MenuMenu;
}
export const Menu: MenuComponent;
interface MenuHeaderProps {
[key: string]: any;
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** Shorthand for primary content. */
content?: React.ReactNode;
}
export const MenuHeader: React.ComponentClass<MenuHeaderProps>;
interface MenuItemProps {
[key: string]: any;
/** An element type to render as (string or function). */
as?: any;
/** A menu item can be active. */
active?: boolean;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** Additional colors can be specified. */
color?: SemanticCOLORS;
/** Shorthand for primary content. */
content?: React.ReactNode;
/** A menu item or menu can remove element padding, vertically or horizontally. */
fitted?: boolean | 'horizontally' | 'vertically';
/** A menu item may include a header or may itself be a header. */
header?: boolean;
/** MenuItem can be only icon. */
icon?: any | boolean;
/** MenuItem index inside Menu. */
index?: number;
/** A menu item can be link. */
link?: boolean;
/** Internal name of the MenuItem. */
name?: string;
/**
* Called on click. When passed, the component will render as an `a`
* tag by default instead of a `div`.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClick?: (event: React.MouseEvent<HTMLAnchorElement>, data: MenuItemProps) => void;
/** A menu item can take right position. */
position?: 'right';
}
export const MenuItem: React.ComponentClass<MenuItemProps>;
interface MenuMenuProps {
[key: string]: any;
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** A sub menu can take right position. */
position?: 'right';
}
export const MenuMenu: React.StatelessComponent<MenuMenuProps>;
|
gurwinderiam/Semantic-UI-React
|
src/addons/Confirm/index.d.ts
|
import * as React from 'react';
interface ConfirmProps {
/** The cancel button text */
cancelButton?: string;
/** The OK button text */
confirmButton?: string;
/** The ModalContent text. */
content?: string;
/** The ModalHeader text */
header?: string;
/** Called when the Cancel button is clicked */
onCancel?: () => void;
/** Called when the OK button is clicked */
onConfirm?: () => void;
/** Whether or not the modal is visible */
open?: boolean;
}
export const Confirm: React.ComponentClass<ConfirmProps>;
|
gurwinderiam/Semantic-UI-React
|
src/addons/Select/index.d.ts
|
import * as React from 'react';
import {
DropdownDivider,
DropdownHeader,
DropdownItem,
DropdownMenu,
DropdownProps
} from '../../modules/Dropdown';
interface SelectProps extends DropdownProps {
selection: true;
}
interface SelectComponent extends React.StatelessComponent<SelectProps> {
Divider: typeof DropdownDivider;
Header: typeof DropdownHeader;
Item: typeof DropdownItem;
Menu: typeof DropdownMenu;
}
export const Select: SelectComponent;
|
gurwinderiam/Semantic-UI-React
|
src/views/Card/index.d.ts
|
<reponame>gurwinderiam/Semantic-UI-React
import * as React from 'react';
import { SemanticCOLORS, SemanticWIDTHS } from '../..';
interface CardProps {
[key: string]: any;
/** An element type to render as (string or function). */
as?: any;
/** A Card can center itself inside its container. */
centered?: boolean;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** A Card can be formatted to display different colors. */
color?: SemanticCOLORS;
/** Shorthand for CardDescription. */
description?: any;
/** Shorthand for primary content of CardContent. */
extra?: any;
/** A Card can be formatted to take up the width of its container. */
fluid?: boolean;
/** Shorthand for CardHeader. */
header?: any;
/** Render as an `a` tag instead of a `div` and adds the href attribute. */
href?: string;
/** A card can contain an Image component. */
image?: any;
/** Shorthand for CardMeta. */
meta?: any;
/**
* Called on click. When passed, the component renders as an `a`
* tag by default instead of a `div`.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClick?: (event: React.MouseEvent<HTMLAnchorElement>, data: CardProps) => void;
/** A Card can be formatted to raise above the page. */
raised?: boolean;
}
interface CardComponent extends React.ComponentClass<CardProps> {
Content: typeof CardContent;
Description: typeof CardDescription;
Group: typeof CardGroup;
Header: typeof CardHeader;
Meta: typeof CardMeta;
}
export const Card: CardComponent;
interface CardContentProps {
[key: string]: any;
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** Shorthand for CardDescription. */
description?: string;
/** A card can contain extra content meant to be formatted separately from the main content. */
extra?: boolean;
/** Shorthand for CardHeader. */
header?: any;
/** Shorthand for CardMeta. */
meta?: any;
}
export const CardContent: React.StatelessComponent<CardContentProps>;
interface CardDescriptionProps {
[key: string]: any;
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** Shorthand for primary content. */
content?: React.ReactNode;
}
export const CardDescription: React.StatelessComponent<CardDescriptionProps>;
interface CardGroupProps {
[key: string]: any;
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** A group of cards can double its column width for mobile. */
doubling?: boolean;
/** Shorthand array of props for Card. */
items?: Array<any>;
/** A group of cards can set how many cards should exist in a row. */
itemsPerRow?: SemanticWIDTHS;
/** A group of cards can automatically stack rows to a single columns on mobile devices. */
stackable?: boolean;
}
export const CardGroup: React.StatelessComponent<CardGroupProps>;
interface CardHeaderProps {
[key: string]: any;
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** Shorthand for primary content. */
content?: React.ReactNode;
}
export const CardHeader: React.StatelessComponent<CardHeaderProps>;
interface CardMetaProps {
[key: string]: any;
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** Shorthand for primary content. */
content?: React.ReactNode;
}
export const CardMeta: React.StatelessComponent<CardMetaProps>;
|
wcordewiner/joker-jailbreak
|
src/Stack.tsx
|
import React from "react";
import { Card, Deck } from "./Model";
import { TopCard } from "./TopCard";
import "./Stack.css";
export type StackProps = {
stack: Deck;
onCardClick: (card: Card) => void;
selectedCards: Set<Card>;
};
export const Stack = ({ stack, onCardClick, selectedCards }: StackProps) => {
return (
<div className="Stack">
<TopCard
card={stack.isEmpty() ? undefined : stack.peek()}
onCardClick={onCardClick}
nrOfCards={stack.size()}
selectedCards={selectedCards}
></TopCard>
</div>
);
};
|
wcordewiner/joker-jailbreak
|
src/version.ts
|
<gh_stars>0
export const LIB_VERSION = "1.0.3";
|
wcordewiner/joker-jailbreak
|
src/TopCard.tsx
|
<reponame>wcordewiner/joker-jailbreak<filename>src/TopCard.tsx
import React from "react";
import { Card, SuitColor, SuitKind } from "./Model";
import "./common.css";
import "./TopCard.css";
export type TopCardProps = {
card?: Card;
onCardClick: (card: Card) => void;
nrOfCards: number;
selectedCards: Set<Card>;
};
export const TopCard = ({
card,
onCardClick,
nrOfCards,
selectedCards,
}: TopCardProps) => {
let cardClassNames = "Card";
if (card && selectedCards.has(card)) {
cardClassNames = cardClassNames + " SelectedCard";
}
const symbolClassName = card
? card.suit.kind === SuitKind.Joker
? "Joker"
: card.suit.color === SuitColor.Black
? "Black"
: "Red"
: "";
const handleClick = () => {
if (card) onCardClick(card);
};
const valueOf = (card: Card): String => {
return card.value === 11
? "J"
: card.value === 12
? "Q"
: card.value === 13
? "K"
: card.value.toString();
};
return (
<div className={cardClassNames} onClick={handleClick}>
<div className="CardInfo">
{card && <span className={symbolClassName}>{card.suit.symbol}</span>}
{card && card.suit.kind !== SuitKind.Joker && (
<span>{valueOf(card)}</span>
)}
{!card && <span>X</span>}
</div>
{card && card.suit.kind !== SuitKind.Joker && (
<div className="CardStackSize">
<span>
{nrOfCards} {nrOfCards === 1 ? "card" : "cards"}
</span>
</div>
)}
</div>
);
};
|
wcordewiner/joker-jailbreak
|
src/Controller.tsx
|
import React from "react";
import { Card, Deck, GameState, SuitColor } from './Model';
import Button from "react-bootstrap/Button";
import "./common.css";
import "./Controller.css";
export type ControllerProps = {
gameState: GameState;
onNewGame: () => void;
selectedCards: Set<Card>;
onRemoveSelectedCards: () => void;
jokerDeck: Deck;
remainderDeck: Deck;
onDrawRemainderCard: () => void;
};
export const Controller = ({
gameState,
onNewGame,
selectedCards,
onRemoveSelectedCards,
jokerDeck,
remainderDeck,
onDrawRemainderCard,
}: ControllerProps) => {
const add = (accumulator: number, a: number): number => {
return accumulator + a;
};
const red = Array.from(selectedCards)
.filter((card) => card.suit.color === SuitColor.Red)
.map((card) => card.value)
.reduce(add, 0);
const black = Array.from(selectedCards)
.filter((card) => card.suit.color === SuitColor.Black)
.map((card) => card.value)
.reduce(add, 0);
const removeDisabled: boolean = red === 0 || red !== black;
const removeButtonClassName =
"Button" + (removeDisabled ? " ButtonDisabled" : " ButtonEnabled");
const drawRemainderDisabled =
remainderDeck.isEmpty() || jokerDeck.size() === 4;
const drawRemainderButtonClassName =
"Button" + (drawRemainderDisabled ? " ButtonDisabled" : " ButtonEnabled");
return (
<div>
<div className="CardStrengthRow">
<div className="StrengthRedName">Red</div>
<div className="StrengthRedNumber Red">{red}</div>
<div className="StrengthDivider">{removeDisabled ? "⇎" : "⇔"}</div>
{/* <div className="StrengthDivider"><img src={discardImage} alt="Remove cards"></img></div> */}
<div className="StrengthBlackNumber">{black}</div>
<div className="StrengthBlackName">Black</div>
</div>
<div className="CardStrengthRow">
{gameState === GameState.Playing && <Button
className={removeButtonClassName}
disabled={removeDisabled}
onClick={onRemoveSelectedCards}
>
Remove
</Button>}
{gameState === GameState.Playing && <Button
className={drawRemainderButtonClassName}
disabled={drawRemainderDisabled}
onClick={onDrawRemainderCard}
>
{`Draw remainder (${remainderDeck.size()})`}
</Button>}
{gameState === GameState.Win && <div className="Win"><span>Win!</span></div>}
<Button className={"Button"} onClick={onNewGame}>
New Game
</Button>
</div>
</div>
);
};
|
wcordewiner/joker-jailbreak
|
src/Model.tsx
|
export enum GameState {
Playing,
Win,
}
export enum SuitKind {
Clubs,
Diamonds,
Hearts,
Spades,
Joker,
}
export enum SuitColor {
Red,
Black,
}
export interface Suit {
kind: SuitKind;
color: SuitColor;
symbol: String;
}
export const Clubs: Suit = {
kind: SuitKind.Clubs,
color: SuitColor.Black,
symbol: "♣",
};
export const Diamonds: Suit = {
kind: SuitKind.Diamonds,
color: SuitColor.Red,
symbol: "♦",
};
export const Hearts: Suit = {
kind: SuitKind.Hearts,
color: SuitColor.Red,
symbol: "♥",
};
export const Spades: Suit = {
kind: SuitKind.Spades,
color: SuitColor.Black,
symbol: "♠",
};
const Joker: Suit = {
kind: SuitKind.Joker,
color: SuitColor.Black,
symbol: "Joker",
};
export interface Card {
suit: Suit;
value: number;
}
export const JokerCard: Card = {
suit: Joker,
value: 0,
};
export class Deck {
private cardArray: Array<Card>;
constructor(cards: Array<Card>) {
this.cardArray = cards;
}
size(): number {
return this.cardArray.length;
}
isEmpty(): boolean {
return this.cardArray.length === 0;
}
isNotEmpty(): boolean {
return !this.isEmpty();
}
peek(): Card {
if (this.isEmpty()) {
throw new Error("Deck is empty");
}
return this.cardArray[0];
}
cards(): Array<Card> {
return new Array<Card>(...this.cardArray);
}
draws(nrOfCards: number): [Deck, Deck] {
if (this.size() < nrOfCards) {
throw new Error(`Deck too small to draw ${nrOfCards} cards`);
}
return [
new Deck(this.cardArray.slice(0, nrOfCards)),
new Deck(this.cardArray.slice(nrOfCards)),
];
}
addCardOnTop(card: Card): Deck {
const newCards: Array<Card> = [card, ...this.cards()];
return new Deck(newCards);
}
}
|
wcordewiner/joker-jailbreak
|
src/JokerJailBreak.tsx
|
<filename>src/JokerJailBreak.tsx
import React, { useEffect, useState } from "react";
import { Card, Deck, GameState, SuitKind } from "./Model";
import { Stack } from "./Stack";
import { Controller } from "./Controller";
// import discardImage from './card-discard.svg';
import "./JokerJailBreak.css";
export type JokerJailBreakProps = {
initialTopLeft: Deck;
initialTopCentre: Deck;
initialTopRight: Deck;
initialMiddleLeft: Deck;
initialMiddleCentre: Deck;
initialMiddleRight: Deck;
initialBottomLeft: Deck;
initialBottomCentre: Deck;
initialBottomRight: Deck;
initialRemainder: Deck;
};
export const JokerJailBreak = ({
initialTopLeft,
initialTopCentre,
initialTopRight,
initialMiddleLeft,
initialMiddleCentre,
initialMiddleRight,
initialBottomLeft,
initialBottomCentre,
initialBottomRight,
initialRemainder,
}: JokerJailBreakProps) => {
const [gameState, setGameState] = useState<GameState>(GameState.Playing);
const [topLeft, setTopLeft] = useState<Deck>(initialTopLeft);
const [topCentre, setTopCentre] = useState<Deck>(initialTopCentre);
const [topRight, setTopRight] = useState<Deck>(initialTopRight);
const [middleLeft, setMiddleLeft] = useState<Deck>(initialMiddleLeft);
const [middleCentre, setMiddleCentre] = useState<Deck>(initialMiddleCentre);
const [middleRight, setMiddleRight] = useState<Deck>(initialMiddleRight);
const [bottomLeft, setBottomLeft] = useState<Deck>(initialBottomLeft);
const [bottomCentre, setBottomCentre] = useState<Deck>(initialBottomCentre);
const [bottomRight, setBottomRight] = useState<Deck>(initialBottomRight);
const [remainder, setRemainder] = useState<Deck>(initialRemainder);
const [selectedCards, setSelectedCards] = useState<Set<Card>>(new Set());
const createNewGame = () => {
window.location.reload();
};
const toggleSelectedCard = (card: Card) => {
if (card.suit.kind === SuitKind.Joker) {
return;
}
const newSelectedCards = new Set<Card>(selectedCards);
if (selectedCards.has(card)) {
console.info("Unselect " + card.suit.symbol + " " + card.value);
newSelectedCards.delete(card);
} else {
console.info("Select " + card.suit.symbol + " " + card.value);
newSelectedCards.add(card);
}
setSelectedCards(newSelectedCards);
};
const removeTopCardFromDeck = (
deck: Deck,
setDeck: (newDeck: Deck) => void
): Card => {
const [cardsDrawn, cardsRemaining] = deck.draws(1);
setDeck(cardsRemaining);
return cardsDrawn.peek();
};
const removeTopCardsFromDeck = (
cardsToRemove: Set<Card>,
deck: Deck,
setDeck: (newDeck: Deck) => void
) => {
if (deck.isNotEmpty() && cardsToRemove.has(deck.peek())) {
removeTopCardFromDeck(deck, setDeck);
}
};
const removeAllSelectedCards = () => {
removeTopCardsFromDeck(selectedCards, topLeft, setTopLeft);
removeTopCardsFromDeck(selectedCards, topCentre, setTopCentre);
removeTopCardsFromDeck(selectedCards, topRight, setTopRight);
removeTopCardsFromDeck(selectedCards, middleLeft, setMiddleLeft);
removeTopCardsFromDeck(selectedCards, middleCentre, setMiddleCentre);
removeTopCardsFromDeck(selectedCards, middleRight, setMiddleRight);
removeTopCardsFromDeck(selectedCards, bottomLeft, setBottomLeft);
removeTopCardsFromDeck(selectedCards, bottomCentre, setBottomCentre);
removeTopCardsFromDeck(selectedCards, bottomRight, setBottomRight);
setSelectedCards(new Set());
};
const drawRemainderCard = () => {
const card: Card = removeTopCardFromDeck(remainder, setRemainder);
setMiddleCentre(middleCentre.addCardOnTop(card));
};
useEffect(() => {
if (
(topCentre.isEmpty() ||
middleLeft.isEmpty() ||
middleRight.isEmpty() ||
bottomCentre.isEmpty()) &&
middleCentre.size() === 1
) {
setGameState(GameState.Win);
}
}, [
topCentre,
middleLeft,
middleRight,
bottomCentre,
middleCentre,
setGameState,
]);
return (
<div className="JokerJailBreak">
<div className="Row">
<Stack
stack={topLeft}
onCardClick={toggleSelectedCard}
selectedCards={selectedCards}
/>
<Stack
stack={topCentre}
onCardClick={toggleSelectedCard}
selectedCards={selectedCards}
/>
<Stack
stack={topRight}
onCardClick={toggleSelectedCard}
selectedCards={selectedCards}
/>
</div>
<div className="Row">
<Stack
stack={middleLeft}
onCardClick={toggleSelectedCard}
selectedCards={selectedCards}
/>
<Stack
stack={middleCentre}
onCardClick={toggleSelectedCard}
selectedCards={selectedCards}
/>
<Stack
stack={middleRight}
onCardClick={toggleSelectedCard}
selectedCards={selectedCards}
/>
</div>
<div className="Row">
<Stack
stack={bottomLeft}
onCardClick={toggleSelectedCard}
selectedCards={selectedCards}
/>
<Stack
stack={bottomCentre}
onCardClick={toggleSelectedCard}
selectedCards={selectedCards}
/>
<Stack
stack={bottomRight}
onCardClick={toggleSelectedCard}
selectedCards={selectedCards}
/>
</div>
<Controller
gameState={gameState}
onNewGame={createNewGame}
selectedCards={selectedCards}
onRemoveSelectedCards={removeAllSelectedCards}
jokerDeck={middleCentre}
remainderDeck={remainder}
onDrawRemainderCard={drawRemainderCard}
/>
</div>
);
};
|
wcordewiner/joker-jailbreak
|
src/index.tsx
|
<gh_stars>0
import React from "react";
import ReactDOM from "react-dom";
import { LIB_VERSION } from "./version";
import { Deck, JokerCard } from "./Model";
import { JokerJailBreak } from "./JokerJailBreak";
import { create52CardDeck, shuffleDeck } from "./Utils";
// import reportWebVitals from "./reportWebVitals";
import "./index.css";
const createJokerJailBreak = () => {
let deck: Deck = shuffleDeck(create52CardDeck());
let topLeft: Deck;
let topCentre: Deck;
let topRight: Deck;
let middleLeft: Deck;
let middleCentre: Deck;
let middleRight: Deck;
let bottomLeft: Deck;
let bottomCentre: Deck;
let bottomRight: Deck;
let remainder: Deck;
[topLeft, deck] = deck.draws(3);
[topCentre, deck] = deck.draws(7);
[topRight, deck] = deck.draws(3);
[middleLeft, deck] = deck.draws(7);
middleCentre = new Deck([JokerCard]);
[middleRight, deck] = deck.draws(7);
[bottomLeft, deck] = deck.draws(3);
[bottomCentre, deck] = deck.draws(7);
[bottomRight, deck] = deck.draws(3);
remainder = deck;
return (
<JokerJailBreak
initialTopLeft={topLeft}
initialTopCentre={topCentre}
initialTopRight={topRight}
initialMiddleLeft={middleLeft}
initialMiddleCentre={middleCentre}
initialMiddleRight={middleRight}
initialBottomLeft={bottomLeft}
initialBottomCentre={bottomCentre}
initialBottomRight={bottomRight}
initialRemainder={remainder}
/>
);
};
ReactDOM.render(
<React.StrictMode>
<div className="center">
<h1 className="text-center">Joker Jailbreak</h1>
{createJokerJailBreak()}
<div className="footer">
<span>Game page and rules can be found </span>
<a
href="https://roofkat.itch.io/joker-jailbreak"
target="_blank"
rel="noreferrer"
>
here
</a>
</div>
<div className="footer">
<span>Game created by </span>
<a href="https://roofkat.itch.io/" target="_blank" rel="noreferrer">
<NAME> (roofkat)
</a>
<span>. Web version {LIB_VERSION} by <NAME>. Source code available </span>
<a
href="https://github.com/wcordewiner/joker-jailbreak"
target="_blank"
rel="noreferrer"
>
here
</a>
</div>
</div>
</React.StrictMode>,
document.getElementById("root")
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
// reportWebVitals();
|
wcordewiner/joker-jailbreak
|
src/Utils.tsx
|
import { Card, Clubs, Deck, Diamonds, Hearts, Spades } from "./Model";
export const create52CardDeck = (): Deck => {
let cards: Array<Card> = [];
[Clubs, Diamonds, Hearts, Spades].forEach((cardSuit) => {
for (let cardValue = 1; cardValue <= 13; cardValue++) {
cards.push({ suit: cardSuit, value: cardValue });
}
});
return new Deck(cards);
};
export const shuffleDeck = (deck: Deck): Deck => {
const cards: Array<Card> = deck.cards();
let currentIndex = cards.length,
randomIndex;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[cards[currentIndex], cards[randomIndex]] = [
cards[randomIndex],
cards[currentIndex],
];
}
return new Deck(cards);
};
|
Conrad2134/aws-solutions-constructs
|
source/patterns/@aws-solutions-constructs/aws-lambda-eventbridge/test/aws-lambda-eventbridge.test.ts
|
/**
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
// Imports
import { Stack } from "@aws-cdk/core";
import * as lambda from "@aws-cdk/aws-lambda";
import * as events from "@aws-cdk/aws-events";
import * as ec2 from "@aws-cdk/aws-ec2";
import { LambdaToEventbridge, LambdaToEventbridgeProps } from '../lib';
import '@aws-cdk/assert/jest';
const xrayPolicyStatement = {
Action: [
"xray:PutTraceSegments",
"xray:PutTelemetryRecords"
],
Effect: "Allow",
Resource: "*"
};
const defaultEventBusPolicyStatement = {
Action: "events:PutEvents",
Effect: "Allow",
Resource: {
"Fn::Join": [
"",
[
"arn:",
{
Ref: "AWS::Partition"
},
":events:",
{
Ref: "AWS::Region"
},
":",
{
Ref: "AWS::AccountId"
},
":event-bus/default"
]
]
}
};
const vpcConfig = {
VpcConfig: {
SecurityGroupIds: [
{
"Fn::GetAtt": [
"lambdatoeventbridgestackReplaceDefaultSecurityGroupsecuritygroup59EF0706",
"GroupId",
],
},
],
SubnetIds: [
{
Ref: "VpcisolatedSubnet1SubnetE62B1B9B",
},
{
Ref: "VpcisolatedSubnet2Subnet39217055",
},
],
},
};
// --------------------------------------------------------------
// Tests minimal deployment with new Lambda function
// --------------------------------------------------------------
test('Test minimal deployment with new Lambda function', () => {
// Stack
const stack = new Stack();
// Helper declaration
const construct = new LambdaToEventbridge(stack, 'lambda-to-eventbridge-stack', {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_12_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(`${__dirname}/lambda`)
}
});
// Check Props
const lambdaFunction = construct.lambdaFunction;
const vpc = construct.vpc;
const eventBus = construct.eventBus;
expect(lambdaFunction).toBeDefined();
expect(vpc).toBeUndefined();
expect(eventBus).toBeUndefined();
// Check EVENTBUS_NAME Env variable
expect(stack).toHaveResource("AWS::Lambda::Function", {
Environment: {
Variables: {
AWS_NODEJS_CONNECTION_REUSE_ENABLED: "1",
EVENTBUS_NAME: "default"
}
}
});
// Since using default event bus, there shouldn't be any eventbus
expect(stack).not.toHaveResource('AWS::Events::EventBus');
// Check Lambda Function permissions to access default Event Bridge
expect(stack).toHaveResourceLike("AWS::IAM::Policy", {
PolicyDocument: {
Statement: [
xrayPolicyStatement,
defaultEventBusPolicyStatement
]
}
});
});
// --------------------------------------------------------------
// Test bad call with existingVpc and deployVpc
// --------------------------------------------------------------
test("Test bad call with existingVpc and deployVpc", () => {
// Stack
const stack = new Stack();
const testVpc = new ec2.Vpc(stack, "test-vpc", {});
const app = () => {
// Helper declaration
new LambdaToEventbridge(stack, "lambda-to-eventbridge-stack", {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_10_X,
handler: "index.handler",
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
},
existingVpc: testVpc,
deployVpc: true,
});
};
// Assertion
expect(app).toThrowError();
});
// --------------------------------------------------------------
// Test exception while passing existingEventBus & eventBusProps
// --------------------------------------------------------------
test("Test bad call with existingVpc and deployVpc", () => {
// Stack
const stack = new Stack();
const app = () => {
// Helper declaration
new LambdaToEventbridge(stack, 'lambda-to-eventbridge-stack', {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_12_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(`${__dirname}/lambda`)
},
eventBusProps: { eventBusName: 'test' },
existingEventBusInterface: new events.EventBus(stack, `new-event-bus`, { eventBusName: 'test' })
});
};
// Assertion
expect(app).toThrowError();
});
// --------------------------------------------------------------
// Test deployment w/ existing eventbus
// --------------------------------------------------------------
test('Test deployment w/ existing eventbus', () => {
// Stack
const stack = new Stack();
// Helper declaration
const existingEventBus = new events.EventBus(stack, 'existing-eventbus', {
eventBusName: 'customeventbus'
});
new LambdaToEventbridge(stack, 'lambda-to-eventbridge-stack', {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_12_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(`${__dirname}/lambda`)
},
existingEventBusInterface: existingEventBus
});
// Check Lambda Permissions
expect(stack).toHaveResourceLike("AWS::IAM::Policy", {
PolicyDocument: {
Statement: [
xrayPolicyStatement,
{
Action: "events:PutEvents",
Effect: "Allow",
Resource: {
"Fn::GetAtt": [
"existingeventbus2A99FA49",
"Arn"
]
}
}
]
}
});
expect(stack).toHaveResource('AWS::Events::EventBus', {
Name: `customeventbus`
});
});
// --------------------------------------------------------------
// Test minimal deployment that deploys a VPC without vpcProps
// --------------------------------------------------------------
test("Test minimal deployment that deploys a VPC without vpcProps", () => {
// Stack
const stack = new Stack();
// Helper declaration
new LambdaToEventbridge(stack, "lambda-to-eventbridge-stack", {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_12_X,
handler: "index.handler",
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
},
deployVpc: true,
});
expect(stack).toHaveResource("AWS::Lambda::Function", vpcConfig);
expect(stack).toHaveResource("AWS::EC2::VPC", {
EnableDnsHostnames: true,
EnableDnsSupport: true,
});
expect(stack).toHaveResource("AWS::EC2::VPCEndpoint", {
VpcEndpointType: "Interface",
});
expect(stack).toCountResources("AWS::EC2::Subnet", 2);
expect(stack).toCountResources("AWS::EC2::InternetGateway", 0);
});
// --------------------------------------------------------------
// Test minimal deployment that deploys a VPC w/vpcProps
// --------------------------------------------------------------
test("Test minimal deployment that deploys a VPC w/vpcProps", () => {
// Stack
const stack = new Stack();
// Helper declaration
new LambdaToEventbridge(stack, "lambda-to-eventbridge-stack", {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_12_X,
handler: "index.handler",
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
},
vpcProps: {
enableDnsHostnames: false,
enableDnsSupport: false,
cidr: "192.168.3.11/16",
},
deployVpc: true,
});
expect(stack).toHaveResource("AWS::Lambda::Function", vpcConfig);
expect(stack).toHaveResource("AWS::EC2::VPC", {
CidrBlock: "192.168.3.11/16",
EnableDnsHostnames: true,
EnableDnsSupport: true,
});
expect(stack).toHaveResource("AWS::EC2::VPCEndpoint", {
VpcEndpointType: "Interface",
});
expect(stack).toCountResources("AWS::EC2::Subnet", 2);
expect(stack).toCountResources("AWS::EC2::InternetGateway", 0);
});
// --------------------------------------------------------------
// Test minimal deployment with an existing VPC
// --------------------------------------------------------------
test("Test minimal deployment with an existing VPC", () => {
// Stack
const stack = new Stack();
const testVpc = new ec2.Vpc(stack, "test-vpc", {});
// Helper declaration
new LambdaToEventbridge(stack, "lambda-to-eventbridge-stack", {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_12_X,
handler: "index.handler",
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
},
existingVpc: testVpc,
});
expect(stack).toHaveResource("AWS::Lambda::Function", {
VpcConfig: {
SecurityGroupIds: [
{
"Fn::GetAtt": [
"lambdatoeventbridgestackReplaceDefaultSecurityGroupsecuritygroup59EF0706",
"GroupId",
],
},
],
SubnetIds: [
{
Ref: "testvpcPrivateSubnet1Subnet865FB50A",
},
{
Ref: "testvpcPrivateSubnet2Subnet23D3396F",
},
],
},
});
expect(stack).toHaveResource("AWS::EC2::VPCEndpoint", {
VpcEndpointType: "Interface",
});
// Check Lambda Function permissions to access default Event Bridge
expect(stack).toHaveResourceLike("AWS::IAM::Policy", {
PolicyDocument: {
Statement: [
{
Action: [
"ec2:CreateNetworkInterface",
"ec2:DescribeNetworkInterfaces",
"ec2:DeleteNetworkInterface",
"ec2:AssignPrivateIpAddresses",
"ec2:UnassignPrivateIpAddresses"
],
Effect: "Allow",
Resource: "*"
},
xrayPolicyStatement,
defaultEventBusPolicyStatement
]
}
});
});
// --------------------------------------------------------------
// Test minimal deployment with an existing VPC and existing Lambda function not in a VPC
//
// buildLambdaFunction should throw an error if the Lambda function is not
// attached to a VPC
// --------------------------------------------------------------
test("Test minimal deployment with an existing VPC and existing Lambda function not in a VPC", () => {
// Stack
const stack = new Stack();
const testLambdaFunction = new lambda.Function(stack, 'test-lamba', {
runtime: lambda.Runtime.NODEJS_12_X,
handler: "index.handler",
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
});
const testVpc = new ec2.Vpc(stack, "test-vpc", {});
// Helper declaration
const app = () => {
// Helper declaration
new LambdaToEventbridge(stack, "lambda-to-eventbridge-stack", {
existingLambdaObj: testLambdaFunction,
existingVpc: testVpc,
});
};
// Assertion
expect(app).toThrowError();
});
// ----------------------------------------------------------------------------------
// Test lambda function custom environment variable and custom event bus permissions
// ----------------------------------------------------------------------------------
test('Test lambda function custom environment variable', () => {
// Stack
const stack = new Stack();
// Helper declaration
new LambdaToEventbridge(stack, 'lambda-to-eventbridge-stack', {
lambdaFunctionProps: {
runtime: lambda.Runtime.NODEJS_12_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
},
eventBusProps: {eventBusName: 'customeventbus'},
eventBusEnvironmentVariableName: 'CUSTOM_EVENTBUS_NAME'
});
// Check environment variables
expect(stack).toHaveResource('AWS::Lambda::Function', {
Handler: 'index.handler',
Runtime: 'nodejs12.x',
Environment: {
Variables: {
AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
CUSTOM_EVENTBUS_NAME: {
Ref: "lambdatoeventbridgestackcustomeventbus25825BEF"
}
}
}
});
expect(stack).toHaveResource('AWS::Events::EventBus', {
Name: `customeventbus`
});
// Check lambda permissions to custom event bus
expect(stack).toHaveResourceLike("AWS::IAM::Policy", {
PolicyDocument: {
Statement: [
xrayPolicyStatement,
{
Action: "events:PutEvents",
Effect: "Allow",
Resource: {
"Fn::GetAtt": [
"lambdatoeventbridgestackcustomeventbus25825BEF",
"Arn"
]
}
}
]
}
});
});
test('check multiple constructs in a single stack', () => {
const stack = new Stack();
const props: LambdaToEventbridgeProps = {
lambdaFunctionProps: {
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
runtime: lambda.Runtime.NODEJS_12_X,
handler: 'index.handler'
},
eventBusProps: { eventBusName: 'test' }
};
new LambdaToEventbridge(stack, 'test-new-lambda-eventbridge1', props);
new LambdaToEventbridge(stack, 'test-new-lambda-eventbridge2', props);
expect(stack).toCountResources('AWS::Events::EventBus', 2);
});
test('check multiple lambda functions publishing to single event bus', () => {
const stack = new Stack();
const props1: LambdaToEventbridgeProps = {
lambdaFunctionProps: {
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
runtime: lambda.Runtime.NODEJS_12_X,
handler: 'index.handler'
},
eventBusProps: { eventBusName: 'test' }
};
const construct = new LambdaToEventbridge(stack, 'test-new-lambda-eventbridge1', props1);
const props2: LambdaToEventbridgeProps = {
lambdaFunctionProps: {
code: lambda.Code.fromAsset(`${__dirname}/lambda`),
runtime: lambda.Runtime.NODEJS_12_X,
handler: 'index.handler'
},
existingEventBusInterface: construct.eventBus
};
new LambdaToEventbridge(stack, 'test-new-lambda-eventbridge2', props2);
// Make sure only single event bus exists
expect(stack).toCountResources('AWS::Events::EventBus', 1);
// Make sure 2 lambda functions exist
expect(stack).toCountResources('AWS::Lambda::Function', 2);
// Check whether lambdas have permisison to publish to the event bus
expect(stack).toHaveResourceLike('AWS::IAM::Policy', {
PolicyDocument: {
Statement: [
xrayPolicyStatement,
{
Action: "events:PutEvents",
Effect: "Allow",
Resource: {
"Fn::GetAtt": [
"testnewlambdaeventbridge1test13E0B622",
"Arn"
]
}
}
]
}
});
// Check environment variables
expect(stack).toHaveResource('AWS::Lambda::Function', {
Handler: 'index.handler',
Runtime: 'nodejs12.x',
Environment: {
Variables: {
AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
EVENTBUS_NAME: {
Ref: "testnewlambdaeventbridge1test13E0B622"
}
}
}
});
});
|
Conrad2134/aws-solutions-constructs
|
source/patterns/@aws-solutions-constructs/aws-s3-step-function/lib/index.ts
|
/**
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
import * as sfn from '@aws-cdk/aws-stepfunctions';
import * as s3 from '@aws-cdk/aws-s3';
import { S3ToStepfunctions } from '@aws-solutions-constructs/aws-s3-stepfunctions';
// Note: To ensure CDKv2 compatibility, keep the import statement for Construct separate
import { Construct } from '@aws-cdk/core';
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import * as cloudtrail from '@aws-cdk/aws-cloudtrail';
import * as events from '@aws-cdk/aws-events';
import * as logs from '@aws-cdk/aws-logs';
/**
* @summary The properties for the S3ToStepFunction Construct
*/
export interface S3ToStepFunctionProps {
/**
* Existing instance of S3 Bucket object, providing both this and `bucketProps` will cause an error.
*
* @default - None
*/
readonly existingBucketObj?: s3.IBucket,
/**
* Optional user provided props to override the default props for the S3 Bucket.
*
* @default - Default props are used
*/
readonly bucketProps?: s3.BucketProps,
/**
* User provided StateMachineProps to override the defaults
*
* @default - None
*/
readonly stateMachineProps: sfn.StateMachineProps,
/**
* Optional User provided eventRuleProps to override the defaults
*
* @default - None
*/
readonly eventRuleProps?: events.RuleProps,
/**
* Whether to deploy a Trail in AWS CloudTrail to log API events in Amazon S3
*
* @default - true
*/
readonly deployCloudTrail?: boolean,
/**
* Whether to create recommended CloudWatch alarms
*
* @default - Alarms are created
*/
readonly createCloudWatchAlarms?: boolean,
/**
* User provided props to override the default props for the CloudWatchLogs LogGroup.
*
* @default - Default props are used
*/
readonly logGroupProps?: logs.LogGroupProps,
/**
* Optional user provided props to override the default props for the S3 Logging Bucket.
*
* @default - Default props are used
*/
readonly loggingBucketProps?: s3.BucketProps,
/**
* Whether to turn on Access Logs for the S3 bucket with the associated storage costs.
* Enabling Access Logging is a best practice.
*
* @default - true
*/
readonly logS3AccessLogs?: boolean;
}
export class S3ToStepFunction extends Construct {
public readonly stateMachine: sfn.StateMachine;
public readonly stateMachineLogGroup: logs.ILogGroup;
public readonly s3Bucket?: s3.Bucket;
public readonly s3LoggingBucket?: s3.Bucket;
public readonly cloudwatchAlarms?: cloudwatch.Alarm[];
public readonly cloudtrail?: cloudtrail.Trail;
public readonly cloudtrailBucket?: s3.Bucket;
public readonly cloudtrailLoggingBucket?: s3.Bucket;
public readonly s3BucketInterface: s3.IBucket;
/**
* @summary Constructs a new instance of the S3ToStepFunction class.
* @param {cdk.App} scope - represents the scope for all the resources.
* @param {string} id - this is a a scope-unique id.
* @param {S3ToStepFunctionProps} props - user provided props for the construct
* @access public
*/
constructor(scope: Construct, id: string, props: S3ToStepFunctionProps) {
super(scope, id);
const convertedProps: S3ToStepFunctionProps = { ...props };
// W (for 'wrapped') is added to the id so that the id's of the constructs with the old and new names don't collide
// If this character pushes you beyond the 64 character limit, just import the new named construct and instantiate
// it in place of the older named version. They are functionally identical, aside from the types no other changes
// will be required. (eg - new S3ToStepfunctions instead of S3ToStepFunction)
const wrappedConstruct: S3ToStepFunction = new S3ToStepfunctions(this, `${id}W`, convertedProps);
this.stateMachine = wrappedConstruct.stateMachine;
this.stateMachineLogGroup = wrappedConstruct.stateMachineLogGroup;
this.s3Bucket = wrappedConstruct.s3Bucket;
this.s3LoggingBucket = wrappedConstruct.s3LoggingBucket;
this.cloudwatchAlarms = wrappedConstruct.cloudwatchAlarms;
this.cloudtrail = wrappedConstruct.cloudtrail;
this.cloudtrailBucket = wrappedConstruct.cloudtrailBucket;
this.cloudtrailLoggingBucket = wrappedConstruct.cloudtrailLoggingBucket;
this.s3BucketInterface = wrappedConstruct.s3BucketInterface;
}
}
|
yujin97/nestjs-task-management
|
src/tasks/tasks.controller.ts
|
<filename>src/tasks/tasks.controller.ts
import { Body, Controller, Delete, Get, Param, Patch, Post, Query, UsePipes, ValidationPipe } from '@nestjs/common';
import { Task } from './task.model';
import { TasksService } from './tasks.service';
import { CreateTaskDto } from './dto/create-task-dto';
import { UpdateTaskDto } from './dto/update-task-dto';
import { GetTasksFilterDto } from './dto/get-tasks-filter.dto';
import { TaskStatusValidationPipe } from './pipes/task-status-validation.pipe';
@Controller('tasks')
export class TasksController {
constructor(private tasksService: TasksService) {}
@Get()
getTasks(@Query(ValidationPipe) filterDto: GetTasksFilterDto): Task[] {
if(Object.keys(filterDto).length){
return this.tasksService.getTasksWithFilters(filterDto)
} else {
return this.tasksService.getAllTasks();
}
}
@Get('/:id')
getTaskById(@Param('id') id: string) {
return this.tasksService.getTaskById(id);
}
@Post()
@UsePipes(ValidationPipe)
createTask(@Body()createTaskDto: CreateTaskDto) {
return this.tasksService.createTask(createTaskDto);
}
@Delete('/:id')
deleteTask(@Param('id') id: string):void {
return this.tasksService.deleteTaskById(id);
}
@Patch('/:id/status')
updateTask(@Param('id') id: string, @Body('',TaskStatusValidationPipe)updateDto: UpdateTaskDto) {
return this.tasksService.updateTask(id, updateDto);
}
}
|
yujin97/nestjs-task-management
|
src/tasks/dto/update-task-dto.ts
|
import { TaskStatus } from '../task.model';
export class UpdateTaskDto {
status: TaskStatus;
}
|
pobo380/vscode-proto3
|
src/proto3SyntacticScopeGuesser.ts
|
<gh_stars>100-1000
import { ITokenizerHandle, tokenize } from "protobufjs";
import * as vscode from "vscode";
class position {
constructor(public line: number, public col: number) {}
static from(pos: position): position {
return Object.assign(new position(0, 0), pos);
}
}
class token {
constructor(public tok: string, public pos: position) {}
}
class tokenizer {
private _pos: position = new position(0, 0);
private _token_width: number = 0;
private _handler: ITokenizerHandle;
constructor(public doc: vscode.TextDocument) {
this._handler = tokenize(doc.getText(), false);
}
public peek(): token | null {
const tok = this._handler.peek();
if (tok == null) {
return null;
}
let row = this._handler.line,
col = this._pos.col;
if (row !== this._pos.line) {
col = 0;
}
col = this.doc.lineAt(row).text.indexOf(tok, this._pos.col);
return new token(tok, new position(row, col));
}
public next(): token | null {
const tok = this._handler.next();
if (tok === null) {
return null;
}
const lineno = this._handler.line;
if (lineno !== this._pos.line) {
this._pos = new position(lineno, 0);
this._token_width = 0;
}
// 注意 vscode 的行号是从0开始的,protobufjs 的 tokenize 返回的行号是从 1 开始的
this._pos.col = this.doc.lineAt(lineno - 1).text.indexOf(tok, this._pos.col + this._token_width);
this._token_width = tok.length;
return new token(tok, position.from(this._pos));
}
public peek_expect(regexp: RegExp): token | null {
const t = this.peek();
if (t === null) {
return null;
}
if (regexp.test(t.tok)) {
return t;
}
return null;
}
public expect(regexp: RegExp): token | null {
const t = this.next();
if (t === null) {
return null;
}
if (regexp.test(t.tok)) {
throw new Error("unexpected token");
}
return t;
}
public get position(): position {
return position.from(this._pos);
}
}
class scope {
constructor(
public name: "message" | "enum" | "service" | "rpc" | "returns" | "rpcbody" | "",
public sym: "(" | "{",
public pos: position,
public end: position = null
) {}
}
// check is pos inside range(begin,end)
function isContains(pos: position, begin: position, end: position) {
// scope 起止都在同一行,光标在起止范围内
return (
(begin.line === end.line && begin.line === pos.line && pos.col >= begin.col && pos.col <= end.col) ||
// scope 不在同一行,光标在起始行的起始token后
(begin.line !== end.line && begin.line === pos.line && pos.col >= begin.col) ||
// scope 不在同一行,光标在结束行的结束token前
(begin.line !== end.line && end.line === pos.line && pos.col <= end.col) ||
// scope 不在同一行,光标在起始行和结束行中间
(begin.line !== end.line && pos.line < end.line && pos.line > begin.line)
);
}
// 全局返回 null
// 其他情况返回 scope
export function SyntacticGuessScope(document: vscode.TextDocument, cursorPosition: vscode.Position): scope | null {
const stack: scope[] = [];
const tkn = new tokenizer(document);
for (let tok = tkn.next(); tok !== null; tok = tkn.next()) {
switch (tok.tok) {
case "message": {
// take next token until reach left brace
let t = tkn.next();
for (; t !== null && t.tok !== "{"; t = tkn.next()) {}
stack.push(new scope("message", "{", position.from(t.pos)));
break;
}
case "enum": {
// take next token until reach left brace
let t = tkn.next();
for (; t !== null && t.tok !== "{"; t = tkn.next()) {}
stack.push(new scope("enum", "{", position.from(t.pos)));
break;
}
case "rpc": {
// take next token until reach left paren
let t = tkn.next();
for (; t !== null && t.tok !== "("; t = tkn.next()) {}
stack.push(new scope("rpc", "(", position.from(t.pos)));
break;
}
case "returns": {
// take next token until reach left paren
let t = tkn.next();
for (; t !== null && t.tok !== "("; t = tkn.next()) {}
stack.push(new scope("returns", "(", position.from(t.pos)));
break;
}
case "service": {
// take next token until reach left brace
let t = tkn.next();
for (; t !== null && t.tok !== "{"; t = tkn.next()) {}
stack.push(new scope("service", "{", position.from(t.pos)));
break;
}
case "(":
stack.push(new scope("", "(", position.from(tok.pos)));
break;
case "{":
stack.push(new scope("", "{", position.from(tok.pos)));
break;
case "}": {
// 匹配栈顶的符号并且是我们关注的 scope 类型 (name!==''),此时才开始检查光标位置是不是在 scope 区间内
const lastScope = stack[stack.length - 1];
if (lastScope.sym === "{") {
stack.pop();
if (lastScope.name !== "") {
// 光标在范围内直接返回
// 注意 vscode 的行号是从0开始的,protobufjs 的 tokenize 返回的行号是从 1 开始的
if (isContains(new position(cursorPosition.line + 1, cursorPosition.character), lastScope.pos, tok.pos)) {
lastScope.end = position.from(tok.pos);
return lastScope;
}
}
} else {
// mismatch!
return null;
}
break;
}
case ")": {
// 匹配栈顶的符号并且是我们关注的 scope 类型 (name!==''),此时才开始检查光标位置是不是在 scope 区间内
const lastScope = stack[stack.length - 1];
if (lastScope.sym === "(") {
stack.pop();
if (lastScope.name !== "") {
// 光标在范围内直接返回
// 注意 vscode 的行号是从0开始的,protobufjs 的 tokenize 返回的行号是从 1 开始的
const cursor = new position(cursorPosition.line + 1, cursorPosition.character);
if (isContains(cursor, lastScope.pos, tok.pos)) {
lastScope.end = position.from(tok.pos);
return lastScope;
}
// 针对rpc 的 option
if (lastScope.name === "returns") {
if (tkn.peek().tok === "{") {
const t = tkn.next();
stack.push(new scope("rpcbody", "{", position.from(t.pos)));
}
}
}
} else {
// mismatch!
return null;
}
break;
}
}
}
while (stack.length > 0) {
const lastScope = stack.pop();
if (lastScope.name !== "") {
return lastScope;
}
}
return null;
}
|
pobo380/vscode-proto3
|
src/proto3Configuration.ts
|
'use strict';
import vscode = require('vscode');
import path = require('path');
import fs = require('fs');
import os = require('os');
export class Proto3Configuration {
private readonly _configSection: string = 'protoc';
private _config: vscode.WorkspaceConfiguration;
private _configResolver: ConfigurationResolver;
public static Instance(workspaceFolder?: vscode.WorkspaceFolder): Proto3Configuration {
return new Proto3Configuration(workspaceFolder);
}
private constructor(workspaceFolder?: vscode.WorkspaceFolder) {
this._config = vscode.workspace.getConfiguration(this._configSection, workspaceFolder);
this._configResolver = new ConfigurationResolver(workspaceFolder);
}
public getProtocPath(protocInPath: boolean): string {
let protoc = protocInPath ? 'protoc' : '?';
return this._configResolver.resolve(
this._config.get<string>('path', protoc));
}
public getProtoSourcePath(): string {
let activeEditor = vscode.window.activeTextEditor;
let activeEditorUri = activeEditor.document.uri;
let activeWorkspaceFolder = vscode.workspace.getWorkspaceFolder(activeEditorUri);
return this._configResolver.resolve(
this._config.get<string>('compile_all_path', activeWorkspaceFolder.uri.path));
}
public getProtocArgs(): string[] {
return this._configResolver.resolve(
this._config.get<string[]>('options', []));
}
public getProtocArgFiles(): string[] {
return this.getProtocArgs().filter(arg => !arg.startsWith('-'));
}
public getProtocOptions(): string[] {
return this.getProtocArgs();
}
public getProtoPathOptions(): string[] {
return this.getProtocOptions()
.filter(opt => opt.startsWith('--proto_path') || opt.startsWith('-I'));
}
public getAllProtoPaths(): string[] {
return this.useAbsolutePath() ?
ProtoFinder.fromDirAbsolute(this.getProtoSourcePath()) :
this.getProtocArgFiles().concat(ProtoFinder.fromDir(this.getProtoSourcePath()));
}
public getTmpJavaOutOption(): string {
return '--java_out=' + os.tmpdir();
}
public compileOnSave(): boolean {
return this._config.get<boolean>('compile_on_save', false);
}
public useAbsolutePath(): boolean {
return this._config.get<boolean>('use_absolute_path', false);
}
}
class ProtoFinder {
static fromDir(root: string): string[] {
let search = function(dir: string): string[] {
let files = fs.readdirSync(dir);
let protos = files.filter(file => file.endsWith('.proto'))
.map(file => path.join(path.relative(root, dir), file));
files.map(file => path.join(dir, file))
.filter(file => fs.statSync(file).isDirectory())
.forEach(subDir => {
protos = protos.concat(search(subDir))
});
return protos;
}
return search(root);
}
static fromDirAbsolute(root: string): string[] {
let files : string[] = [];
const getFilesRecursively = (directory) => {
const filesInDirectory = fs.readdirSync(directory);
for (const file of filesInDirectory) {
const absolute = path.join(directory, file);
if (fs.statSync(absolute).isDirectory()) getFilesRecursively(absolute);
else files.push(absolute);
}
};
getFilesRecursively(root);
return files;
}
}
// Workaround to substitute variable keywords in the configuration value until
// workbench/services/configurationResolver is available on Extention API.
//
//
// Some codes are copied from:
// src/vs/workbench/services/configurationResolver/node/configurationResolverService.ts
class ConfigurationResolver {
constructor(private readonly workspaceFolder?: vscode.WorkspaceFolder) {
Object.keys(process.env).forEach(key => {
this[`env.${key}`] = process.env[key];
});
}
public resolve(value: string): string;
public resolve(value: string[]): string[];
public resolve(value: any): any {
if (typeof value === 'string') {
return this.resolveString(value);
} else if (this.isArray(value)) {
return this.resolveArray(value);
}
return value;
}
private isArray(array: any): array is any[] {
if (Array.isArray) {
return Array.isArray(array);
}
if (array && typeof (array.length) === 'number' && array.constructor === Array) {
return true;
}
return false;
}
private resolveArray(value: string[]): string[] {
return value.map(s => this.resolveString(s));
}
private resolveString(value: string): string {
let regexp = /\$\{(.*?)\}/g;
const originalValue = value;
const resolvedString = value.replace(regexp, (match: string, name: string) => {
let newValue = (<any>this)[name];
if (typeof newValue === 'string') {
return newValue;
} else {
return match && match.indexOf('env.') > 0 ? '' : match;
}
});
return this.resolveConfigVariable(resolvedString, originalValue);
}
private resolveConfigVariable(value: string, originalValue: string): string {
let regexp = /\$\{config\.(.+?)\}/g;
return value.replace(regexp, (match: string, name: string) => {
let config = vscode.workspace.getConfiguration(undefined, this.workspaceFolder);
let newValue: any;
try {
const keys: string[] = name.split('.');
if (!keys || keys.length <= 0) {
return '';
}
while (keys.length > 1) {
const key = keys.shift();
if (!config || !config.hasOwnProperty(key)) {
return '';
}
config = config[key];
}
newValue = config && config.hasOwnProperty(keys[0]) ? config[keys[0]] : '';
} catch (e) {
return '';
}
if (typeof newValue === 'string') {
// Prevent infinite recursion and also support nested references (or tokens)
return newValue === originalValue ? '' : this.resolveString(newValue);
} else {
return this.resolve(newValue) + '';
}
});
}
private get workspaceRoot(): string {
return vscode.workspace.rootPath;
}
}
|
BogdanMihaiciuc/ThingTransformer
|
src/transformer/ThingTransformer.ts
|
<gh_stars>1-10
import * as ts from 'typescript';
import { TWEntityKind, TWPropertyDefinition, TWServiceDefinition, TWEventDefinition, TWSubscriptionDefinition, TWBaseTypes, TWPropertyDataChangeKind, TWFieldBase, TWPropertyRemoteBinding, TWPropertyRemoteFoldKind, TWPropertyRemotePushKind, TWPropertyRemoteStartKind, TWPropertyBinding, TWSubscriptionSourceKind, TWServiceParameter, TWDataShapeField, TWConfigurationTable, TWRuntimePermissionsList, TWVisibility, TWExtractedPermissionLists, TWRuntimePermissionDeclaration, TWPrincipal, TWPermission, TWUser, TWUserGroup, TWPrincipalBase, TWOrganizationalUnit, TWConnection, TWDataThings, TWInfoTable } from './TWCoreTypes';
import { Breakpoint } from './DebugTypes';
import {Builder} from 'xml2js';
import * as fs from 'fs';
declare global {
namespace NodeJS {
interface Global {
_TWEntities: any;
}
}
}
/**
* The primitive type keywords that can be used in function returns.
*/
const TypeScriptReturnPrimitiveTypes = [ts.SyntaxKind.StringKeyword, ts.SyntaxKind.NumberKeyword, ts.SyntaxKind.VoidKeyword, ts.SyntaxKind.BooleanKeyword];
/**
* The primitive type keywords that can be used anywhere.
*/
const TypeScriptPrimitiveTypes = [ts.SyntaxKind.StringKeyword, ts.SyntaxKind.NumberKeyword, ts.SyntaxKind.BooleanKeyword];
/**
* The kinds of nodes that are permitted to express Thingworx types.
*/
const PermittedTypeNodeKinds = [...TypeScriptPrimitiveTypes, ts.SyntaxKind.TypeReference];
/**
* An array of decorator names that are used to specify permissions.
*/
const PermissionDecorators = ['allow', 'deny', 'allowInstance', 'denyInstance'];
/**
* If set to `true`, the transformer will create a configuration table containing the debug information
* for each entity.
*/
const USE_DEBUG_CONFIGURATION_TABLE = false;
/**
* The thing transformer is applied to Thingworx source files to convert them into Thingworx XML entities.
* It can also be used with global files to export symbols into the shared global scope.
*/
export class TWThingTransformer {
program: ts.Program;
context: ts.TransformationContext;
/**
* Set to `true` when experimental support for global code is enabled.
*/
experimentalGlobals?: boolean = false;
/**
* Set to `true` when the file parsed by this transformer is global code that should not be evaluated using
* thingworx rules.
*/
isGlobalCode?: boolean;
/**
* For global files, this is an array of global symbols that should be exported.
*/
globalSymbols: string[] = [];
/**
* Set to `true` after the first root node has been visited.
*/
anyNodeVisited: boolean = false;
/**
* The filename.
*/
filename?: string;
/**
* The source file being processed.
*/
sourceFile?: ts.SourceFile;
/**
* The JSDoc description for this entity.
*/
description?: string;
/**
* The name of the entity to create. For global code, this is the name of the
* thing to which the global code will be attached.
*/
className?: string;
/**
* The exported name of the entity to use.
*/
exportedName?: string;
/**
* When set to a string, this project will be assigned to the entity.
*/
projectName?: string;
/**
* For things and thing templates, this represents the name of the template from which
* this entity inherits.
*/
thingTemplateName?: string;
/**
* An array of thing shapes to apply to things and thing templates.
*/
thingShapes: string[] = [];
/**
* The generic argument specified for the thing template, if any.
*/
genericArgument?: string;
/**
* For things, this represents the identifier if it has been set.
*/
identifier?: string;
/**
* For things and thing templates, this represents the assigned value stream, if it has been set.
*/
valueStream?: string;
/**
* For things, this represents the published flag if it has been set.
*/
published: boolean = false;
/**
* Controls whether the class represents an editable extension object.
*/
editable: boolean = false;
/**
* Set to `true` when this transformer first encounters a class.
* In Thingworx files, only a single class may be declared per file.
*/
hasClassDefinition = false;
/**
* The kind of entity.
*/
entityKind!: TWEntityKind;
/**
* The class node for this entity.
*/
classNode?: ts.ClassDeclaration;
/**
* For model entities, an array of discovered properties.
*/
properties: TWPropertyDefinition[] = [];
/**
* For model entities, an array of discovered services.
*/
services: TWServiceDefinition[] = [];
/**
* For model entities, an array of discovered events.
*/
events: TWEventDefinition[] = [];
/**
* For model entities, an array of discovered subscription.
*/
subscriptions: TWSubscriptionDefinition[] = [];
/**
* An array of global blocks associated with this entity.
*/
globalBlocks: TWThingTransformer[] = [];
/**
* For global code transformers processed in the `after` phase, this is the compiled global code.
*/
compiledGlobalCode?: string;
/**
* For model entities, an array of discovered configuration table definitions.
*/
configurationTableDefinitions: TWConfigurationTable[] = [];
/**
* For model entities, a map of discovered configuration table values.
*/
configuration?: Record<string, TWInfoTable>;
/**
* For data shapes, an array of field definitions.
*/
fields: TWDataShapeField[] = [];
/**
* A dictionary of runtime permissions to apply to this entity.
*/
runtimePermissions: TWExtractedPermissionLists = {};
/**
* An array of visibility permissions to apply to this entity.
*/
visibilityPermissions: TWVisibility[] = [];
/**
* An array of visibility permissions to apply to instances of this entity.
*/
instanceVisibilityPermissions: TWVisibility[] = [];
/**
* A dictionary of users declared in this entity.
*/
users: { [key: string]: TWUser } = {};
/**
* A dictionary of user groups declared in this entity.
*/
userGroups: { [key: string]: TWUserGroup } = {};
/**
* An array of discovered organizational units in this entity.
*/
orgUnits: TWOrganizationalUnit[] = [];
/**
* An array of discovered organizational unit connections in this entity..
*/
orgConnections: TWConnection[] = [];
/**
* When enabled, ordinal values will be generated for data shape fields, in the order in which they
* appear, starting from 0.
*
* This will not override ordinal values that are explicitly specified via decorators.
*/
autoGenerateDataShapeOrdinals: boolean = false;
/**
* The project root path, to which files are written by default.
*/
root: string;
/**
* Set to `true` if this transformer is applied in the after phase. When set to `true`,
* this transformer will only extract the transpiled service bodies.
*/
after: boolean;
/**
* Set to `true` if this transformer is used during a watch process. When set to `true`,
* this transformer will only emit declarations.
*/
watch: boolean;
/**
* An object containing instances of the transformer.
*/
store?: {[key: string]: TWThingTransformer};
/**
* An array of endpoints that should be invoked after deployment.
*/
deploymentEndpoints: string[] = [];
/**
* A weak map that contains a mapping between nodes that have been marked for replacement before
* having been visited.
*/
nodeReplacementMap: WeakMap<ts.Node, ts.Node> = new WeakMap;
/**
* A weak set of the methods that should be visited for adding debug information.
*/
debugMethodNodes: WeakSet<ts.Node> = new WeakSet;
/**
* Set to `true` if this transformer should generate debugging information.
*/
debug?: boolean;
/**
* An array of breakpoint locations that have been added in a debug build.
*/
breakpoints: Breakpoint[] = [];
/**
* A map of existing breakpoint locations.
*/
breakpointLocations: { [key: number]: { [key:number]: boolean } } = {};
constructor(program: ts.Program, context: ts.TransformationContext, root: string, after: boolean, watch: boolean) {
this.program = program;
this.context = context;
this.root = root;
this.after = after;
this.watch = watch;
}
/**
* Throws a formatted error message for the given AST node.
* @param node The node which caused an error.
* @param error The error message to display.
*/
throwErrorForNode(node: ts.Node, error: string): never {
const limit = Error.stackTraceLimit;
try {
Error.stackTraceLimit = 0;
const {line, character} = node.getSourceFile().getLineAndCharacterOfPosition(node.getStart());
throw new Error(`Error in file ${node.getSourceFile().fileName}:${line},${character}\n\n${error}\n
Failed parsing at: \n${node.getText()}\n\n`);
}
finally {
Error.stackTraceLimit = limit;
}
}
/**
* Returns the TW specific entity kind for the given class declaration based on the applied
* decorators.
* @param classNode The class node.
* @return The entity kind.
*/
entityKindOfClassNode(classNode: ts.ClassDeclaration): TWEntityKind {
// Determine the kind based on the decorators
if (!classNode.decorators || !classNode.decorators.length) {
this.throwErrorForNode(classNode, `Ambiguous class kind ${classNode.name}. Thingworx classes must extend from DataShape, ThingShape or have an entity kind decorator.`);
}
let isThing = classNode.decorators.some(decorator => decorator.expression.kind == ts.SyntaxKind.Identifier && decorator.expression.getText() == 'ThingDefinition');
let isThingTemplate = classNode.decorators.some(decorator => decorator.expression.kind == ts.SyntaxKind.Identifier && decorator.expression.getText() == 'ThingTemplateDefinition');
let isDataShape = classNode.decorators.some(decorator => decorator.expression.kind == ts.SyntaxKind.Identifier && decorator.expression.getText() == 'DataShapeDefinition');
const kinds = [isThing, isThingTemplate, isDataShape].filter(b => b);
// Ensure that there is exactly a single kind specified
if (kinds.length != 1) {
this.throwErrorForNode(classNode, `Class ${classNode.name} must have a single entity kind annotation.`);
}
if (isThing) {
return TWEntityKind.Thing;
} else if (isThingTemplate) {
return TWEntityKind.ThingTemplate;
} else if (isDataShape) {
this.throwErrorForNode(classNode, `Data shape inheritance is not yet supported.`);
return TWEntityKind.DataShape;
}
this.throwErrorForNode(classNode, `Unknown entity kind for class ${classNode.name}`);
}
/**
* Returns the constant value of the given property access expression so that it can be inlined.
* A constant value that must be inlined can occur because of a const enum member or because of
* an environment variable.
* @param expression The expression whose constant value should be evaluated.
* @returns The constant value if it could be resolved, `undefined` otherwise.
*/
constantValueOfExpression(expression: ts.Expression): unknown {
if (expression.kind != ts.SyntaxKind.PropertyAccessExpression) return undefined;
const propertyAccess = expression as ts.PropertyAccessExpression
const sourceObject = propertyAccess.expression;
const value = propertyAccess.name.text;
if (sourceObject.kind == ts.SyntaxKind.PropertyAccessExpression) {
// If the source object is itself a property acess expression, it may refer to an env variable
const sourceExpression = sourceObject as ts.PropertyAccessExpression;
const sourceExpressionSource = sourceExpression.expression.getText();
const sourceExpressionValue = sourceExpression.name.text;
if (sourceExpressionSource == 'process' && sourceExpressionValue == 'env') {
// If this is an environment variable, inline it
return process.env[value];
}
} else {
// Otherwise it may just be a const enum
return ((this.context as any).getEmitResolver() as ts.TypeChecker).getConstantValue(expression as ts.PropertyAccessExpression);
}
return undefined;
}
/**
* Checks whether the given node has a decorator with the given name.
* @param name The name of the decorator to find.
* @param node The node in which to search.
* @return `true` if the decorator was found, `false` otherwise.
*/
hasDecoratorNamed(name: string, node: ts.Node): boolean {
if (!node.decorators) return false;
// Getting the decorator name depends on whether the decorator is applied directly or via a
// decorator factory
for (const decorator of node.decorators) {
if (decorator.expression.kind == ts.SyntaxKind.CallExpression) {
const callExpression = decorator.expression as ts.CallExpression;
if (callExpression.expression.getText() == name) {
return true;
}
}
else if (decorator.expression.kind == ts.SyntaxKind.Identifier) {
const identifierExpression = decorator.expression as ts.Identifier;
if (identifierExpression.text == name) {
return true;
}
}
}
return false;
}
/**
* Retrieves the arguments of the decorator with the given name, if the decorator exists and is a applied
* via a decorator factory.
* @param name The name of the decorator to find.
* @param node The node in which to search.
* @return An array of expressions representing the arguments, or `undefined` if they could not be retrieved.
*/
argumentsOfDecoratorNamed(name: string, node: ts.Node): ts.NodeArray<ts.Expression> | undefined {
if (!node.decorators) return;
for (const decorator of node.decorators) {
if (decorator.expression.kind == ts.SyntaxKind.CallExpression) {
const callExpression = decorator.expression as ts.CallExpression;
if (callExpression.expression.getText() == name) {
return callExpression.arguments;
}
}
}
}
/**
* Retrieves the text of the single literal argument of the given decorator. This method will throw if the given
* decorator factory has no arguments, more than one argument or a non-literal argument.
* @param name The name of the decorator to find.
* @param node The node in which to search.
* @return The text of the literal argument, or `undefined` if the decorator does not exist.
*/
literalArgumentOfDecoratorNamed(name: string, node: ts.Node): string | undefined {
if (!this.hasDecoratorNamed(name, node)) return;
const args = this.argumentsOfDecoratorNamed(name, node);
if (!args || args.length != 1) {
this.throwErrorForNode(node, `The @${name} decorator must take a single parameter.`);
}
else {
const argument = args[0];
if (argument.kind != ts.SyntaxKind.StringLiteral) {
this.throwErrorForNode(node, `The argument for the @${name} decorator must be a string literal.`);
}
const literalArgument = argument as ts.StringLiteral;
return literalArgument.text;
}
}
/**
* Retrieves the text of the single numeric argument of the given decorator. This method will throw if the given
* decorator factory has no arguments, more than one argument or a non-numeric argument.
* @param name The name of the decorator to find.
* @param node The node in which to search.
* @return The text of the numeric argument, or `undefined` if the decorator does not exist.
*/
numericArgumentOfDecoratorNamed(name: string, node: ts.Node): string | undefined {
if (!this.hasDecoratorNamed(name, node)) return;
const args = this.argumentsOfDecoratorNamed(name, node);
if (!args || args.length != 1) {
this.throwErrorForNode(node, `The @${name} decorator must take a single parameter.`);
}
else {
const argument = args[0];
if (ts.isNumericLiteral(argument)) {
return (argument as ts.NumericLiteral).text;
}
else if (ts.isPrefixUnaryExpression(argument) && ts.isNumericLiteral(argument.operand) && argument.operator == ts.SyntaxKind.MinusToken) {// check for negative number
return '-' + (argument.operand as ts.NumericLiteral).text;
}
else {
this.throwErrorForNode(node, `The argument for the @${name} decorator must be a number.`);
}
}
}
/**
* Compiles the global code and sets the `compiledGlobalCode` property.
* @param node The source file node.
*/
compileGlobalCode(node: ts.SourceFile) {
const compiledCode = ts.createPrinter().printNode(ts.EmitHint.Unspecified, node, node);
// Note that the exported symbol names are javascript identifiers, so it is safe to use them with dot notation
this.compiledGlobalCode = compiledCode + '\n\n' + this.globalSymbols.map(symbol => `Object.getPrototypeOf(this).${symbol} = ${symbol};`).join('\n');
}
/**
* Visits the given node.
* @param node The node to visit.
* @return The visited node, or a new node that will replace it.
*/
visit(node: ts.Node): ts.Node | undefined {
if (this.after) {
if (node.kind == ts.SyntaxKind.SourceFile) {
(this as any).source = node;
// Check if this file is global code
const globalClass = this.getGlobalFileClass(node as ts.SourceFile);
if (globalClass) {
this.isGlobalCode = true;
// Find the matching before transformer and replace it by this one
const store = this.store || global._TWEntities;
let targetArray;
if (store[globalClass]) {
targetArray = (store[globalClass] as TWThingTransformer).globalBlocks;
}
else if (store['@globalBlocks'][globalClass]) {
targetArray = store['@globalBlocks'][globalClass];
}
if (targetArray) {
const filename = (node as ts.SourceFile).fileName;
this.filename = filename;
for (let i = 0; i < targetArray.length; i++) {
// Find the pre-compilation block and replace it by this one, while copying
// the exported symbol names
const globalTransformer = targetArray[i];
if (globalTransformer.filename == filename) {
this.globalSymbols = globalTransformer.globalSymbols;
targetArray[i] = this;
// Compile the global code so that it can be used directly when creating the XML files
this.compileGlobalCode(node as ts.SourceFile);
break;
}
}
}
}
}
// This doesn't seem properly documented in typescript.d.ts?
const transpiledNode = node as any;
if (!this.isGlobalCode) {
// After transpilation, methods get turned into function declarations
// that are assigned to properties
if (node.kind == ts.SyntaxKind.FunctionExpression && transpiledNode.original && transpiledNode.original.kind == ts.SyntaxKind.MethodDeclaration) {
this.visitTranspiledMethod(transpiledNode);
}
}
}
else {
if (node.kind == ts.SyntaxKind.SourceFile) {
this.filename = (node as ts.SourceFile).fileName;
this.sourceFile = node as ts.SourceFile;
}
if (node.parent && node.parent.kind == ts.SyntaxKind.SourceFile) {
if (this.isGlobalCode) {
this.visitGlobalRootNode(node);
}
else {
this.visitRootNode(node);
}
}
// The following transformations only make sense for non-global code
if (!this.isGlobalCode) {
// Async is only included for metadata but cannot be used on the result
if (node.kind == ts.SyntaxKind.AsyncKeyword) {
return undefined;
}
// Decorators are only included for metadata but cannot be used on the result
if (node.kind == ts.SyntaxKind.Decorator) {
return undefined;
}
// All enum constants and environment variables should be inlined at this step as the printer is not able to inline them later on
if (node.kind == ts.SyntaxKind.PropertyAccessExpression) {
const constantValue = this.constantValueOfExpression(node as ts.PropertyAccessExpression);
if (typeof constantValue == 'string') {
return ts.factory.createStringLiteral(constantValue);
}
else if (typeof constantValue == 'number') {
return ts.factory.createNumericLiteral(constantValue.toString());
}
}
if (node.kind == ts.SyntaxKind.ThisKeyword) {
return this.visitThisNode(node as ts.ThisExpression);
}
if (this.nodeReplacementMap.get(node)) {
// If the node was already processed and marked for replacement, return its replacement
return this.nodeReplacementMap.get(node);
}
// Upon reaching a method declaration that has been marked for debugging
// start processing in reverse.
if (this.debugMethodNodes.has(node)) {
return this.visitMethodNode(node);
}
}
}
const result = ts.visitEachChild(node, node => this.visit(node), this.context);
return result;
}
/**
* Visits a `this` node and decides whether to replace with `me` or leave it as is. The node will be replaced by
* `me` if its scope - the closest parent non-arrow function - is a thingworx service.
* @param node The node to visit.
* @return A node.
*/
visitThisNode(node: ts.ThisExpression) {
// Replace the node with "me" if the closest function declaration is the class method
let parent = node.parent;
if (parent) do {
// Nodes within functions don't need replacing
if (parent.kind == ts.SyntaxKind.FunctionDeclaration || parent.kind == ts.SyntaxKind.FunctionExpression) {
break;
}
// Nodes within the main class methods directly need replacing
if (parent.kind == ts.SyntaxKind.MethodDeclaration) {
const method = parent as ts.MethodDeclaration;
if (method.parent == this.classNode) {
return ts.factory.createIdentifier('me');
}
}
parent = parent.parent;
} while (parent);
return ts.visitEachChild(node, node => this.visit(node), this.context);
}
/**
* Returns the documentation for the given node, if it exists.
* @param node The node whose documentation to get.
* @return The documentation, or an empty string if it doesn't exist.
*/
documentationOfNode(node: ts.Node): string {
// This method appears to not be included in the type definition
const documentation = (ts as any).getJSDocCommentsAndTags(node, true) as ts.Node[];
// Get the first documentation node and use it as the description
if (documentation.length) {
for (const documentationNode of documentation) {
if (documentationNode.kind == ts.SyntaxKind.JSDocComment) {
const comment = (documentationNode as ts.JSDoc).comment || '';
if (typeof comment != 'string') {
return comment.reduce((acc, val) => acc + (val.text), "");
}
else {
return comment;
}
}
}
}
return '';
}
/**
* Constructs and returns a permission declaration object.
* @returns A permission declaration object.
*/
static createPermissionList(): TWRuntimePermissionDeclaration {
return {
PropertyRead: [],
PropertyWrite: [],
ServiceInvoke: [],
EventInvoke: [],
EventSubscribe: []
} as TWRuntimePermissionDeclaration;
}
/**
* Extracts and returns the visibility permissions of the given kind for the given node.
* @param kind The name of the decorator containing the visibility permissions.
* @param node The node to which the decorator may be applied.
* @returns An array of visibility permissions if any were found, or an empty array otherwise.
*/
visibilityPermissionsOfKindForNode(kind: string, node: ts.Node): TWVisibility[] {
const result: TWVisibility[] = [];
if (this.hasDecoratorNamed(kind, node)) {
const organizations = this.argumentsOfDecoratorNamed(kind, node);
if (!organizations || !organizations.length) {
this.throwErrorForNode(node, `The @${kind} decorator must specify at least one organization.`);
}
for (const arg of organizations) {
if (arg.kind == ts.SyntaxKind.PropertyAccessExpression) {
const expression = arg as ts.PropertyAccessExpression;
const organization = expression.name.text;
if (expression.expression.getText() != 'Organizations') {
this.throwErrorForNode(arg, `Organizations specified in the @${kind} decorator must be accessed from the Organizations collection or via the "Unit" function.`);
}
result.push({isPermitted: true, name: organization, type: 'Organization'});
}
else if (arg.kind == ts.SyntaxKind.CallExpression) {
const callExpression = arg as ts.CallExpression;
if (callExpression.expression.getText() != 'Unit') {
this.throwErrorForNode(arg, `Organization units in the @${kind} decorator must be specified via the "Unit" function.`);
}
const unitArguments = callExpression.arguments;
if (unitArguments.length != 2) {
this.throwErrorForNode(arg, `The "Unit" function must take exactly two parameters.`);
}
const organizationArg = unitArguments[0];
const unitArg = unitArguments[1] as ts.StringLiteral;
if (unitArg.kind != ts.SyntaxKind.StringLiteral) {
this.throwErrorForNode(arg, `The organization unit must be specified as a string literal.`);
}
const organizationExpression = organizationArg as ts.PropertyAccessExpression;
if (organizationArg.kind != ts.SyntaxKind.PropertyAccessExpression || organizationExpression.expression.getText() != 'Organizations') {
this.throwErrorForNode(arg, `Organizations specified in the "Unit" function must be accessed from the Organizations collection.`);
}
const organizationName = organizationExpression.name.text;
result.push({isPermitted: true, name: `${organizationName}:${unitArg.text}`, type: 'OrganizationalUnit'})
}
else {
this.throwErrorForNode(arg, `Organizations specified in the @${kind} decorator must be accessed from the Organizations collection or via the "Unit" function.`);
}
}
}
return result;
}
/**
* Returns a list of permissions for the given node.
* @param node The node whose permissions should be retrieved.
* @param resource The resource to which the permissions should refer. If specified and any decorator
* refers to a different resource, this method will throw.
* @returns A list of permissions
*/
permissionsOfNode(node: ts.Node, resource: string = '*'): TWExtractedPermissionLists {
// Filter out the list of decorators to exclude any non-permission decorators
const decorators = node.decorators?.filter(d => d.expression.kind == ts.SyntaxKind.CallExpression && PermissionDecorators.includes((d.expression as ts.CallExpression).expression.getText()));
const result: TWExtractedPermissionLists = {};
if (!decorators?.length) return result;
const permissionLists: TWExtractedPermissionLists[] = [];
for (const decorator of decorators) {
const text = (decorator.expression as ts.CallExpression).expression.getText();
// Determine the kind of permission based on the decorator name
let permissionKind: keyof TWExtractedPermissionLists = 'runtime';
let permitted = false;
let targetResource = resource;
switch (text) {
case 'allow':
permitted = true;
permissionKind = 'runtime';
break;
case 'deny':
permitted = false;
permissionKind = 'runtime';
break;
case 'allowInstance':
permitted = true;
permissionKind = 'runtimeInstance';
break;
case 'denyInstance':
permitted = false;
permissionKind = 'runtimeInstance';
break;
default:
this.throwErrorForNode(node, `Unkown permission decorator '${text}' specified.`)
}
// Determine if this decorator applies to a specific property or to the entire node
// and extract the specified permissions and users.
const callExpression = decorator.expression as ts.CallExpression;
if (!callExpression.arguments.length) this.throwErrorForNode(node, `A permission decorator must have at least one user or group and at least one permission`);
// The index at which to start looking for users and permissions
let argumentsIndex = 0;
// if this decorator refers to a specific field, set it as the resource and look for users and permissions starting at index 1
const firstArgument = callExpression.arguments[0];
if (firstArgument.kind == ts.SyntaxKind.StringLiteral) {
targetResource = (firstArgument as ts.StringLiteral).text;
argumentsIndex = 1;
// If the specified resource is not a wildcard and this refers to a different resource, throw
if (resource != '*' && targetResource != resource) {
this.throwErrorForNode(node, `A permission decorator applied to a member cannot refer to a different member.`);
}
}
const permissions: (keyof TWRuntimePermissionDeclaration)[] = [];
const principals: TWPrincipal[] = [];
// Extract the users, groups and permissions referenced by this decorator
for (let i = argumentsIndex; i < callExpression.arguments.length; i++) {
const argument = callExpression.arguments[i];
if (argument.kind != ts.SyntaxKind.PropertyAccessExpression) this.throwErrorForNode(node, `Invalid argument '${argument.getText()}' supplied to ${decorator.getText()}`);
const expression = argument as ts.PropertyAccessExpression;
const kind = expression.expression.getText();
const value = expression.name;
switch (kind) {
case 'Permission':
permissions.push(value.text as keyof TWRuntimePermissionDeclaration);
break;
case 'Users':
case 'Groups':
principals.push({ name: value.text, type: kind.substring(0, kind.length - 1) });
break;
default:
this.throwErrorForNode(node, `Invalid argument '${argument.getText()}' supplied to ${decorator.getText()}`);
}
}
// Convert the lists of permissions and principals into an extracted permissions list
const permissionList: TWExtractedPermissionLists = {
[permissionKind]: {
[targetResource]: TWThingTransformer.createPermissionList()
}
}
for (const permission of permissions) {
permissionList[permissionKind]![targetResource][permission] = principals.map(p => ({principal: p.name, type: p.type, isPermitted: permitted}));
}
permissionLists.push(permissionList);
}
// Merge the lists together
return this.mergePermissionListsForNode(permissionLists, node);
}
/**
* Merges the given permission lists into a single permission list.
* @param lists The lists to merge.
* @param node A node to be included in the error message if a validation failure occurs.
* @returns The merged list.
*/
mergePermissionListsForNode(permissionLists: TWExtractedPermissionLists[], node: ts.Node): TWExtractedPermissionLists {
return permissionLists.reduce((acc, val) => {
for (const kind in val) {
// If the given kind isn't specified at all, just copy over from the value
if (!acc[kind]) {
if (!val[kind]) continue;
acc[kind] = val[kind];
continue;
}
// Otherwise merge the lists
for (const resource in val[kind]!) {
// If the given resource isn't specified at all, just copy over from the value
if (!acc[kind]![resource]) {
acc[kind]![resource] = val[kind]![resource];
continue;
}
// If the resource is specified, merge the list of principals
for (const key of Object.keys(val[kind]![resource])) {
const value: TWPermission[] = acc[kind]![resource][key].concat(val[kind]![resource][key]);
// Throw if any duplicates are found
if (value.filter((p, i) => value.find((p2, i2) => i != i2 && p2.type == p.type && p2.principal == p.principal)).length) {
this.throwErrorForNode(node, `Each user or group may only appear a single time per permission in a permissions decorator.`);
}
acc[kind]![resource][key] = value;
}
}
}
return acc;
}, {});
}
/**
* Checks whether the source file processed by this transformer is global code. If it is, this returns
* the name of the entity to which the global code will be attached.
* @param node The source file node.
* @return `true` if this file represents global code, `false` otherwise.
*/
getGlobalFileClass(node: ts.SourceFile): string | undefined {
// TODO: merge into visitRootNode below
if (!node.statements.length) return undefined;
const firstStatement = node.statements[0];
if (firstStatement.kind != ts.SyntaxKind.ExpressionStatement || (firstStatement as ts.ExpressionStatement).expression.kind != ts.SyntaxKind.StringLiteral) return undefined;
const literalNode = (firstStatement as ts.ExpressionStatement).expression as ts.StringLiteral;
let literal = literalNode.text;
// Depending on tsconfig.json, the first statement in the transpiled file may be "use strict"
if (literal == 'use strict') {
const secondStatement = node.statements[1];
if (secondStatement.kind != ts.SyntaxKind.ExpressionStatement || (secondStatement as ts.ExpressionStatement).expression.kind != ts.SyntaxKind.StringLiteral) return undefined;
const literalNode = (secondStatement as ts.ExpressionStatement).expression as ts.StringLiteral;
literal = literalNode.text;
}
const literalComponents = literal.split(' ');
if (literalComponents.length == 2 && literalComponents[0] == 'use' && literalComponents[1] != 'strict') {
return literalComponents[1];
}
return undefined;
}
/**
* Visits a node whose parent is the source file.
* @param node The node to visit.
*/
visitRootNode(node: ts.Node) {
// Check if this file is global code
if (!this.anyNodeVisited) {
// A file is considered global code if the first node it contains is a string literal node in the form of
// 'use <name>', where <name> is any string except 'strict'
if (node.kind == ts.SyntaxKind.ExpressionStatement && (node as ts.ExpressionStatement).expression.kind == ts.SyntaxKind.StringLiteral) {
const literal = ((node as ts.ExpressionStatement).expression as ts.StringLiteral).text;
const literalComponents = literal.split(' ');
if (literalComponents.length == 2 && literalComponents[0] == 'use' && literalComponents[1] != 'strict') {
this.isGlobalCode = true;
this.anyNodeVisited = true;
this.className = literalComponents[1];
// Throw when using global code without the flag
if (!this.experimentalGlobals) {
this.throwErrorForNode(node, 'Experimental support for global code must be enabled in order to declare global symbols.');
}
// Throw when a local store is not specified - this likely indicates an old build script that cannot handle the @globalBlocks key
if (!this.store) {
this.throwErrorForNode(node, 'Experimental support for global code is not compatible with your build script. Ensure the gulpfile is up to date.');
}
const store = this.store || (global._TWEntities = global._TWEntities || {});
store['@globalBlocks'] = store['@globalBlocks'] || {};
store['@globalBlocks'][this.className] = store['@globalBlocks'][this.className] || [];
store['@globalBlocks'][this.className].push(this);
if (store[this.className]) {
if ((store[this.className] as TWThingTransformer).entityKind != TWEntityKind.Thing) {
this.throwErrorForNode(node, `Blocks of global code can only be attached to thing entities.`);
}
store[this.className].globalBlocks.push(this);
}
return;
}
}
}
this.anyNodeVisited = true;
// The only permitted entries at the source level are class declarations, interface declarations, const enums and import statements
if (![ts.SyntaxKind.ClassDeclaration, ts.SyntaxKind.InterfaceDeclaration, ts.SyntaxKind.EnumDeclaration, ts.SyntaxKind.ImportClause, ts.SyntaxKind.SingleLineCommentTrivia, ts.SyntaxKind.JSDocComment, ts.SyntaxKind.MultiLineCommentTrivia].includes(node.kind)) {
this.throwErrorForNode(node, `Only classes, interfaces, const enums and import statements are permitted at the root level.`);
}
// Enums are permitted, but only if they are const
if (node.kind == ts.SyntaxKind.EnumDeclaration) {
const enumNode = node as ts.EnumDeclaration;
if (!enumNode.modifiers || !enumNode.modifiers.some(modifier => modifier.kind == ts.SyntaxKind.ConstKeyword)) {
this.throwErrorForNode(node, `Enums are only permitted if they are declared const.`);
}
}
// Interface declarations are erased, so they don't need any special handling
// Import statements are only used for type inference so they are not handled
if (node.kind == ts.SyntaxKind.ClassDeclaration) {
const classNode = node as ts.ClassDeclaration;
if (this.hasClassDefinition) {
this.throwErrorForNode(node, `Only a single class may be declared in Thingworx files.`);
}
this.classNode = classNode;
if (!classNode.name) {
this.throwErrorForNode(node, `Thingworx model classes cannot be anonymous.`);
}
this.className = classNode.name.text;
this.exportedName = this.className;
this.description = this.documentationOfNode(classNode);
if (this.hasDecoratorNamed('exportName', classNode)) {
const exportName = this.literalArgumentOfDecoratorNamed('exportName', classNode);
this.exportedName = exportName;
}
// All Thingworx classes are required to inherit from some kind of base class
if (!classNode.heritageClauses || !classNode.heritageClauses.length) {
this.throwErrorForNode(node, `Thingworx model classes must inherit from a Thingworx base class.`);
}
// Determine the kind of entity this is based on the base class
const heritage = classNode.heritageClauses[0].types[0];
// The kind must be either an identifier or a call expression
if (heritage.expression.kind == ts.SyntaxKind.Identifier) {
const baseClass = heritage.expression as ts.Identifier;
if (baseClass.escapedText == 'ThingShapeBase') {
this.entityKind = TWEntityKind.ThingShape;
}
else if (baseClass.escapedText == 'DataShapeBase') {
this.entityKind = TWEntityKind.DataShape;
}
else if (baseClass.escapedText == 'UserList') {
this.entityKind = TWEntityKind.UserList;
}
else if (baseClass.escapedText == 'OrganizationBase') {
this.entityKind = TWEntityKind.Organization;
}
else {
this.entityKind = this.entityKindOfClassNode(classNode);
this.thingTemplateName = baseClass.text;
// Extract the generic argument in case it needs to be used, if the template is
// a data storage type that needs a data shape configuration
// In the future this may be expanded to other use cases
const genericArguments = heritage.typeArguments;
if (genericArguments && genericArguments.length) {
const firstArgument = genericArguments[0];
if (firstArgument) {
this.genericArgument = firstArgument.getText();
}
}
}
}
else if (heritage.expression.kind == ts.SyntaxKind.CallExpression) {
// Call expression base classes can only be things or thing templates
this.entityKind = this.entityKindOfClassNode(classNode);
if (this.entityKind != TWEntityKind.Thing && this.entityKind != TWEntityKind.ThingTemplate) {
this.throwErrorForNode(node, `Extending from expressions is only supported on Things and ThingTemplates.`);
}
const callNode = heritage.expression as ts.CallExpression;
// Ensure that the call signature is of the correct type
if (callNode.expression.getText() != 'ThingTemplateWithShapes' && callNode.expression.getText() != 'ThingTemplateReference' && callNode.expression.getText() != 'ThingTemplateWithShapesReference') {
this.throwErrorForNode(node, `Unknown base class for ${classNode.name}. Thing and ThingTemplate classes must extend from a ThingTemplateWithShapes(...) expression, a ThingTemplateWithShapesReference(...) expression, a ThingTemplateReference(...) expression or a base ThingTemplate class.`);
}
if (callNode.expression.getText() == 'ThingTemplateWithShapes' || callNode.expression.getText() == 'ThingTemplateWithShapesReference') {
// Ensure that each parameter is of the correct type
if (!callNode.arguments.length) {
this.throwErrorForNode(node, `The ThingTemplateWithShapes(...) expression must have at least one ThingTemplate parameter.`);
}
const thingTemplateNode = callNode.arguments[0];
if (thingTemplateNode.kind == ts.SyntaxKind.CallExpression) {
// A particular case is a data thing that needs a generic which can't be specified directly,
// in this case a utility `DataThing` function can be used to obtain a reference to the correct type
const callExpression = thingTemplateNode as ts.CallExpression;
switch (callExpression.expression.getText()) {
case 'DataThing':
const args = callExpression.arguments;
if (args.length != 2) {
this.throwErrorForNode(heritage, `The "DataThing" function must take two arguments.`);
}
const templateName = args[0];
const dataShapeName = args[1];
if (templateName.kind != ts.SyntaxKind.Identifier || dataShapeName.kind != ts.SyntaxKind.Identifier) {
this.throwErrorForNode(heritage, `The "DataThing" function arguments must be identifiers.`);
}
this.thingTemplateName = templateName.getText();
this.genericArgument = dataShapeName.getText();
break;
default:
this.throwErrorForNode(heritage, `Unknown thing template expression "${callExpression.expression.getText()}" used in ThingTemplateWithShapes(...)`);
}
}
else {
this.thingTemplateName = callNode.arguments[0].kind == ts.SyntaxKind.StringLiteral ?
(callNode.arguments[0] as ts.StringLiteral).text :
callNode.arguments[0].getText();
}
this.thingShapes = callNode.arguments.slice(1, callNode.arguments.length).map(node => {
if (node.kind == ts.SyntaxKind.StringLiteral) {
return (node as ts.StringLiteral).text;
}
else {
return node.getText();
}
});
}
else {
if (callNode.arguments.length != 1) this.throwErrorForNode(node, `The ThingTemplateReference(...) expression must have a single string literal parameter.`);
if (callNode.arguments[0].kind != ts.SyntaxKind.StringLiteral) this.throwErrorForNode(node, `The ThingTemplateReference(...) expression must have a single string literal parameter.`);
this.thingTemplateName = (callNode.arguments[0] as ts.StringLiteral).text;
// NOTE: The ThingTemplateReference syntax can't use generics yet
}
}
this.valueStream = this.literalArgumentOfDecoratorNamed('valueStream', classNode);
this.identifier = this.literalArgumentOfDecoratorNamed('identifier', classNode);
if (this.valueStream && (this.entityKind != TWEntityKind.Thing && this.entityKind != TWEntityKind.ThingTemplate)) {
this.throwErrorForNode(node, `The valueStream decorator can only be applied to Things and ThingTemplates.`);
}
this.published = !!classNode.decorators && classNode.decorators.some(decorator => decorator.expression.kind == ts.SyntaxKind.Identifier && decorator.expression.getText() == 'published');
if (this.published && this.entityKind != TWEntityKind.Thing) {
this.throwErrorForNode(node, `Only Things may be published.`);
}
this.editable = !!classNode.decorators && classNode.decorators.some(decorator => decorator.expression.kind == ts.SyntaxKind.Identifier && decorator.expression.getText() == 'editable');
if (!this.watch) {
if (this.hasDecoratorNamed('ConfigurationTables', classNode)) {
const configurationArgument = this.argumentsOfDecoratorNamed('ConfigurationTables', classNode)!;
if (configurationArgument.length != 1) {
this.throwErrorForNode(classNode, `The @ConfigurationTables decorator must take a single class parameter.`);
}
const argument = configurationArgument[0];
if (argument.kind != ts.SyntaxKind.ClassExpression) {
this.throwErrorForNode(classNode, `The @ConfigurationTables decorator must take a single class parameter.`);
}
this.visitConfigurationTablesDefinition(argument as ts.ClassExpression);
}
if (this.hasDecoratorNamed('config', classNode)) {
const configurationArgument = this.argumentsOfDecoratorNamed('config', classNode)!;
if (configurationArgument.length != 1) {
this.throwErrorForNode(classNode, `The @config decorator must take a single object literal parameter.`);
}
const argument = configurationArgument[0];
if (argument.kind != ts.SyntaxKind.ObjectLiteralExpression) {
this.throwErrorForNode(classNode, `The @config decorator must take a single object literal parameter.`);
}
this.visitConfiguration(argument as ts.ObjectLiteralExpression);
}
this.runtimePermissions = this.mergePermissionListsForNode([this.runtimePermissions].concat(this.permissionsOfNode(classNode)), node);
this.visibilityPermissions = this.visibilityPermissionsOfKindForNode('visible', classNode);
this.instanceVisibilityPermissions = this.visibilityPermissionsOfKindForNode('visibleInstance', classNode);
// Instance visibility permissions may only be provided on templates and shapes
if (this.instanceVisibilityPermissions.length && this.entityKind != TWEntityKind.ThingShape && this.entityKind != TWEntityKind.ThingTemplate) {
this.throwErrorForNode(classNode, `Instance permissions may only be set on thing templates and thing shapes.`);
}
}
// In watch mode, it is not needed to visit class members since they are not needed for the declaration files,
// except for user lists whose members each correspond to an entity and organizations whose units must be specified
// as type arguments
if (!this.watch || this.entityKind == TWEntityKind.UserList || this.entityKind == TWEntityKind.Organization) {
for (const member of classNode.members) {
this.visitClassMember(member);
}
}
const store = this.store || (global._TWEntities = global._TWEntities || {});
store[this.className] = this;
if (store['@globalBlocks'] && store['@globalBlocks'][this.className]) {
for (const block of store['@globalBlocks'][this.className]) {
this.globalBlocks.push(block);
}
}
}
}
/**
* Visits a node whose parent is the source file. This method is only called
* on global code files.
* @param node The node to visit.
*/
visitGlobalRootNode(node: ts.Node) {
// The only permitted entries at the source level are declarations; other kinds of executables can only be included as initializers for those declarations
if (![
ts.SyntaxKind.ClassDeclaration,
ts.SyntaxKind.InterfaceDeclaration,
ts.SyntaxKind.VariableStatement,
ts.SyntaxKind.VariableDeclarationList,
ts.SyntaxKind.VariableDeclaration,
ts.SyntaxKind.FunctionDeclaration,
ts.SyntaxKind.EnumDeclaration,
ts.SyntaxKind.SingleLineCommentTrivia,
ts.SyntaxKind.JSDocComment,
ts.SyntaxKind.MultiLineCommentTrivia
].includes(node.kind)) {
this.throwErrorForNode(node, `Only declarations are permitted at the root level.`);
}
// Store the symbol name so it can be exported, depending on the syntax kind
switch (node.kind) {
case ts.SyntaxKind.ClassDeclaration:
case ts.SyntaxKind.FunctionDeclaration:
case ts.SyntaxKind.VariableDeclaration:
case ts.SyntaxKind.EnumDeclaration:
const declarationNode = node as ts.ClassDeclaration | ts.FunctionDeclaration | ts.EnumDeclaration | ts.FunctionDeclaration;
if (declarationNode.name) this.globalSymbols.push(declarationNode.name!.text);
break;
case ts.SyntaxKind.VariableStatement:
const variableNode = node as ts.VariableStatement;
const statementList = variableNode.declarationList;
for (const declaration of statementList.declarations) {
// Binding patterns aren't supported yet
if (ts.SyntaxKind.Identifier != declaration.name.kind) continue;
this.globalSymbols.push((declaration.name as ts.Identifier).text);
}
break;
case ts.SyntaxKind.VariableDeclarationList:
const declarationList = node as ts.VariableDeclarationList;
for (const declaration of declarationList.declarations) {
// Binding patterns aren't supported yet
if (ts.SyntaxKind.Identifier != declaration.name.kind) continue;
this.globalSymbols.push((declaration.name as ts.Identifier).text);
}
break;
// Other kinds don't export anything
default: break;
}
}
/**
* Visits a class member. This will invoke one of the specialized visit method depending on the
* kind of node and class.
* @param node The node to visit.
*/
visitClassMember(node: ts.ClassElement) {
if (node.kind == ts.SyntaxKind.Constructor) {
this.throwErrorForNode(node, `Constructors are not supported in Thingworx classes.`);
}
if (node.kind == ts.SyntaxKind.PropertyDeclaration) {
const propertyDeclarationNode = node as ts.PropertyDeclaration;
if (this.entityKind == TWEntityKind.DataShape) {
this.visitDataShapeField(propertyDeclarationNode);
}
else if (this.entityKind == TWEntityKind.UserList) {
this.visitUserListField(propertyDeclarationNode);
}
else if (this.entityKind == TWEntityKind.Organization) {
if (node.name?.kind != ts.SyntaxKind.Identifier || (node.name as ts.Identifier)?.text != 'units') {
this.throwErrorForNode(node, `Organization classes may only have a single property called "units".`);
}
if (!(node as ts.PropertyDeclaration).initializer) {
this.throwErrorForNode(node, `The units property must have an initializer.`);
}
this.visitOrganizationalUnit((node as ts.PropertyDeclaration).initializer!);
}
else {
this.visitProperty(propertyDeclarationNode);
}
}
if (node.kind == ts.SyntaxKind.MethodDeclaration) {
if (this.entityKind == TWEntityKind.DataShape) {
this.throwErrorForNode(node, `Data Shapes cannot contain methods.`);
}
if (this.entityKind == TWEntityKind.UserList) {
this.throwErrorForNode(node, `User lists cannot contain methods.`);
}
if (this.entityKind == TWEntityKind.Organization) {
this.throwErrorForNode(node, `Organizations cannot contain methods.`);
}
this.visitMethod(node as ts.MethodDeclaration);
}
}
/**
* Visits the given organizational unit expression.
* @param unit The unit to visit.
* @param parent If specified, the parent organizational unit, used to create the required
* connections.
*/
visitOrganizationalUnit(unit: ts.Expression, parentName?: string) {
if (unit.kind != ts.SyntaxKind.ObjectLiteralExpression) {
this.throwErrorForNode(unit, `Organizational units must be specified as object literals.`);
}
const unitLiteral = unit as ts.ObjectLiteralExpression;
const orgUnit = {} as TWOrganizationalUnit;
for (const member of unitLiteral.properties) {
if (!member.name || member.name.kind != ts.SyntaxKind.Identifier) {
this.throwErrorForNode(unit, `Organizational unit properties must be identifiers.`);
}
const name = (member.name as ts.Identifier).text;
if (member.kind != ts.SyntaxKind.PropertyAssignment) {
this.throwErrorForNode(unit, `Organizational unit properties cannot be setters, getters or methods.`);
}
const prop = member as ts.PropertyAssignment;
switch (name) {
case 'name':
if (prop.initializer.kind != ts.SyntaxKind.StringLiteral) {
this.throwErrorForNode(unit, `Organizational unit names must be string literals.`);
}
orgUnit.name = (prop.initializer as ts.StringLiteral).text;
if (orgUnit.name.indexOf(':') != -1) {
this.throwErrorForNode(unit, `Organizational unit names cannot contain the ":" character.`);
}
const description = this.documentationOfNode(prop);
if (description) {
orgUnit.description = description;
}
break;
case 'units':
if (!orgUnit.name) {
this.throwErrorForNode(unit, `Subunits must be specified after an organizational unit's name.`);
}
if (prop.initializer.kind != ts.SyntaxKind.ArrayLiteralExpression) {
this.throwErrorForNode(unit, `Organizational unit subunits must be specified in an array literal.`);
}
const subunits = prop.initializer as ts.ArrayLiteralExpression;
for (const subunit of subunits.elements) {
this.visitOrganizationalUnit(subunit, orgUnit.name);
}
break;
case 'members':
if (prop.initializer.kind != ts.SyntaxKind.ArrayLiteralExpression) {
this.throwErrorForNode(unit, `Organizational unit members must be specified in an array literal.`);
}
const members = prop.initializer as ts.ArrayLiteralExpression;
orgUnit.members = members.elements.map(m => {
if (m.kind != ts.SyntaxKind.PropertyAccessExpression) {
this.throwErrorForNode(members, `Organizational unit members must be specified via the "Users" and "Groups" collections.`);
}
const expression = m as ts.PropertyAccessExpression;
const kind = expression.expression.getText();
const value = expression.name.text;
switch (kind) {
case 'Users':
return {type: 'User', name: value};
case 'Groups':
return {type: 'Group', name: value};
default:
this.throwErrorForNode(members, `Organizational unit members must be specified via the "Users" and "Groups" collections.`);
}
});
break;
}
}
if (!orgUnit.name) {
this.throwErrorForNode(unit, `Organizational units must have a name.`);
}
this.orgUnits.push(orgUnit);
this.orgConnections.push({from: parentName || '', to: orgUnit.name});
}
/**
* Visits a data shape property declaration.
* @param node The node to visit.
*/
visitUserListField(node: ts.PropertyDeclaration) {
const principal = {} as TWPrincipalBase;
if (node.name.kind != ts.SyntaxKind.Identifier) {
this.throwErrorForNode(node, `Computed property names are not supported in Thingwrox classes.`);
}
// First obtain the name of the property
principal.name = node.name.text;
principal.description = this.documentationOfNode(node);
if (node.initializer) {
// Only two types of initializers are permitted in user lists
// - object literals which describe users
if (node.initializer.kind == ts.SyntaxKind.ObjectLiteralExpression) {
const user = principal as TWUser;
user.extensions = {};
// Enumerate the members and create the extensions object
const objectLiteral = node.initializer as ts.ObjectLiteralExpression;
for (const member of objectLiteral.properties) {
if (member.kind == ts.SyntaxKind.MethodDeclaration) {
this.throwErrorForNode(node, `User extensions cannot contain methods`);
}
if (member.kind != ts.SyntaxKind.PropertyAssignment) {
this.throwErrorForNode(node, `User extensions keys cannot be setters, getters or shorthand assignments.`);
}
if (member.name.kind != ts.SyntaxKind.Identifier) {
this.throwErrorForNode(node, `User extension property names must be identifiers.`);
}
const assignment = member as ts.PropertyAssignment;
if (assignment.initializer.kind == ts.SyntaxKind.PropertyAccessExpression) {
// Const enums need to be resolved early on
user.extensions[member.name.text] = this.constantValueOfExpression(assignment.initializer as ts.PropertyAccessExpression);
// If the value is not a compile time constant, it is not a valid initializer
if (user.extensions[member.name.text] === undefined) {
this.throwErrorForNode(node, `Unknown initializer for property.`);
}
}
else {
user.extensions[member.name.text] = (assignment.initializer as ts.LiteralExpression).text || assignment.initializer.getText();
}
}
this.users[user.name] = user;
}
// - array literals which describe groups
else if (node.initializer.kind == ts.SyntaxKind.ArrayLiteralExpression) {
const group = principal as TWUserGroup;
group.members = [];
const arrayLiteral = node.initializer as ts.ArrayLiteralExpression;
for (const member of arrayLiteral.elements) {
if (member.kind != ts.SyntaxKind.PropertyAccessExpression) {
this.throwErrorForNode(node, `User group members must be user or group references.`);
}
const expression = member as ts.PropertyAccessExpression;
const type = expression.expression.getText();
const name = expression.name;
if (type != 'Users' && type != 'Groups') {
this.throwErrorForNode(node, `User group members must be user or group references.`);
}
if (name.kind != ts.SyntaxKind.Identifier) {
this.throwErrorForNode(node, `User group member names must be identifiers.`);
}
group.members.push({name: name.text, type})
}
this.userGroups[group.name] = group;
}
} else {
// Properties without an initializer default to being treated as users with no extensions
const user = principal as TWUser;
user.extensions = {};
this.users[user.name] = user;
}
// Extract the permissions to be applied per user
this.runtimePermissions = this.mergePermissionListsForNode([this.runtimePermissions].concat(this.permissionsOfNode(node, node.name.text)), node);
}
/**
* Visits a user list property declaration.
* @param node The node to visit.
*/
visitDataShapeField(node: ts.PropertyDeclaration) {
// Ensure that the property has a type annotation
if (!node.type) {
this.throwErrorForNode(node, `Properties must have type annotation in Thingworx classes.`);
}
if (!PermittedTypeNodeKinds.includes(node.type.kind)) {
this.throwErrorForNode(node, `Unknown baseType for property ${node.name.getText()}: ${node.type.getText()}`);
}
// Extract the type name
const typeNode = node.type as ts.TypeReferenceNode;
const baseType = TypeScriptPrimitiveTypes.includes(typeNode.kind) ? typeNode.getText() : typeNode.typeName.getText();
const property = {} as TWDataShapeField;
if (node.name.kind != ts.SyntaxKind.Identifier) {
this.throwErrorForNode(node, `Computed property names are not supported in Thingwrox classes.`);
}
// First obtain the name of the property
property.name = node.name.text;
property.description = this.documentationOfNode(node);
// Create the generic aspects, required for all properties
property.aspects = {};
if (this.hasDecoratorNamed('primaryKey', node)) {
property.aspects.isPrimaryKey = true;
}
const ordinal = this.numericArgumentOfDecoratorNamed('ordinal', node);
if (ordinal) {
if (!parseInt(ordinal)) this.throwErrorForNode(node, `Non numeric value specified in ordinal decorator for property ${property.name}: ${property.baseType}`);
property.ordinal = parseInt(ordinal);
}
// Ensure that the base type is one of the Thingworx Base Types
if (!(baseType in TWBaseTypes)) {
this.throwErrorForNode(node, `Unknown baseType for property ${property.name}: ${property.baseType}`);
}
property.baseType = TWBaseTypes[baseType];
// INFOTABLE can optionally take the data shape as a type argument
if (TWBaseTypes[baseType] == 'INFOTABLE') {
const typeArguments = typeNode.typeArguments;
if (typeArguments) {
if (typeArguments.length != 1) this.throwErrorForNode(node, `Unknown generics specified for property ${property.name}: ${property.baseType}`);
if (typeArguments[0].kind == ts.SyntaxKind.LiteralType) {
property.aspects.dataShape = ((typeArguments[0] as ts.LiteralTypeNode).literal as ts.StringLiteral).text;
}
else {
property.aspects.dataShape = typeArguments[0].getText();
}
}
}
// THINGNAME can optionally take the thing template name and/or thing shape name as a type argument
else if (TWBaseTypes[baseType] == 'THINGNAME') {
const typeArguments = typeNode.typeArguments;
if (typeArguments && typeArguments.length) {
if (typeArguments.length > 2) this.throwErrorForNode(node, `Unknown generics specified for property ${property.name}: ${property.baseType}`);
const thingTemplate = typeArguments[0];
if (thingTemplate.kind == ts.SyntaxKind.LiteralType) {
property.aspects.thingTemplate = ((thingTemplate as ts.LiteralTypeNode).literal as ts.StringLiteral).text;
}
const thingShape = typeArguments[1];
if (thingShape && thingShape.kind == ts.SyntaxKind.LiteralType) {
property.aspects.thingShape = ((thingShape as ts.LiteralTypeNode).literal as ts.StringLiteral).text;
}
}
}
if (node.initializer) {
if (node.initializer.kind == ts.SyntaxKind.PropertyAccessExpression) {
// Const enums need to be resolved early on
property.aspects.defaultValue = this.constantValueOfExpression(node.initializer as ts.PropertyAccessExpression);
// If the value is not a compile time constant, it is not a valod initializer
if (property.aspects.defaultValue === undefined) {
this.throwErrorForNode(node, `Unknown initializer for property.`);
}
}
else if (ts.isNewExpression(node.initializer) && ts.isIdentifier(node.initializer.expression) && node.initializer.expression.escapedText == 'Date') {
if (node.initializer.arguments && node.initializer.arguments.length == 1 && ts.isStringLiteral(node.initializer.arguments[0])) {
property.aspects.defaultValue = new Date(node.initializer.arguments[0].text).toISOString();
}
else {
this.throwErrorForNode(node, 'Exactly one string literal argument is required when setting Date as default value.');
}
}
else {
property.aspects.defaultValue = (node.initializer as ts.LiteralExpression).text || node.initializer.getText();
}
}
const permissions = this.permissionsOfNode(node);
if (Object.keys(permissions).length) {
this.throwErrorForNode(node, `Permission decorators are not allowed for data shape members.`);
}
this.fields.push(property);
}
/**
* Visits a thing, thing template or thing shape property or event.
* @param node The node to visit.
*/
visitProperty(node: ts.PropertyDeclaration) {
// Ensure that the property has a type annotation
if (!node.type) {
this.throwErrorForNode(node, `Properties must have type annotation in Thingworx classes.`);
}
if (!PermittedTypeNodeKinds.includes(node.type.kind)) {
this.throwErrorForNode(node, `Unknown baseType for property ${node.name.getText()}: ${node.type.getText()}`);
}
// Extract the type name
const typeNode = node.type as ts.TypeReferenceNode;
const baseType = TypeScriptPrimitiveTypes.includes(typeNode.kind) ? typeNode.getText() : typeNode.typeName.getText();
// The special base type "EVENT" identifies properties that will be converted into events.
if (baseType == 'EVENT') {
return this.visitEvent(node);
}
const property = {} as TWPropertyDefinition;
if (node.name.kind != ts.SyntaxKind.Identifier) {
this.throwErrorForNode(node, `Computed property names are not supported in Thingwrox classes.`);
}
// First obtain the name of the property
property.name = node.name.text;
property.description = this.documentationOfNode(node);
// Create the generic aspects, required for all properties
property.aspects = {
cacheTime: 0,
dataChangeType: TWPropertyDataChangeKind.Value,
dataChangeThreshold: 0
};
// Ensure that the base type is one of the Thingworx Base Types
if (!(baseType in TWBaseTypes)) {
this.throwErrorForNode(node, `Unknown baseType for property ${property.name}: ${property.baseType}`);
}
property.baseType = TWBaseTypes[baseType];
// INFOTABLE can optionally take the data shape as a type argument
if (TWBaseTypes[baseType] == 'INFOTABLE') {
const typeArguments = typeNode.typeArguments;
if (typeArguments) {
if (typeArguments.length != 1) this.throwErrorForNode(node, `Unknown generics specified for property ${property.name}: ${property.baseType}`);
if (typeArguments[0].kind == ts.SyntaxKind.LiteralType) {
property.aspects.dataShape = ((typeArguments[0] as ts.LiteralTypeNode).literal as ts.StringLiteral).text;
}
else {
property.aspects.dataShape = typeArguments[0].getText();
}
}
}
// THINGNAME can optionally take the thing template name and/or thing shape name as a type argument
else if (TWBaseTypes[baseType] == 'THINGNAME') {
const typeArguments = typeNode.typeArguments;
if (typeArguments && typeArguments.length) {
if (typeArguments.length > 2) this.throwErrorForNode(node, `Unknown generics specified for property ${property.name}: ${property.baseType}`);
const thingTemplate = typeArguments[0];
if (thingTemplate.kind == ts.SyntaxKind.LiteralType) {
property.aspects.thingTemplate = ((thingTemplate as ts.LiteralTypeNode).literal as ts.StringLiteral).text;
}
const thingShape = typeArguments[1];
if (thingShape && thingShape.kind == ts.SyntaxKind.LiteralType) {
property.aspects.thingShape = ((thingShape as ts.LiteralTypeNode).literal as ts.StringLiteral).text;
}
}
}
if (node.initializer) {
if (node.initializer.kind == ts.SyntaxKind.PropertyAccessExpression) {
// Const enums need to be resolved early on
property.aspects.defaultValue = this.constantValueOfExpression(node.initializer as ts.PropertyAccessExpression);
// If the value is not a compile time constant, it is not a valid initializer
if (property.aspects.defaultValue === undefined) {
this.throwErrorForNode(node, `Unknown initializer for property.`);
}
}
else if (ts.isNewExpression(node.initializer) && ts.isIdentifier(node.initializer.expression) && node.initializer.expression.escapedText == 'Date') {
if (node.initializer.arguments && node.initializer.arguments.length == 1 && ts.isStringLiteral(node.initializer.arguments[0])) {
property.aspects.defaultValue = new Date(node.initializer.arguments[0].text).toISOString();
}
else {
this.throwErrorForNode(node, 'Exactly one string literal argument is required when setting Date as default value.');
}
}
else {
property.aspects.defaultValue = (node.initializer as ts.LiteralExpression).text || node.initializer.getText();
}
}
// Aspects are specified as decorators
if (node.decorators) {
if (this.hasDecoratorNamed('persistent', node)) property.aspects.isPersistent = true;
if (this.hasDecoratorNamed('logged', node)) property.aspects.isLogged = true;
}
// The readonly aspect uses the typescript built-in readonly keyword
if (node.modifiers) {
if (node.modifiers.some(modifier => modifier.kind == ts.SyntaxKind.ReadonlyKeyword)) property.aspects.isReadOnly = true;
}
// Create a remote binding if it has been specified
if (this.hasDecoratorNamed('remote', node)) {
const remoteArguments = this.argumentsOfDecoratorNamed('remote', node)!;
property.aspects.isRemote = true;
property.remoteBinding = {} as TWPropertyRemoteBinding;
property.remoteBinding.name = property.name;
if (remoteArguments[0].kind != ts.SyntaxKind.StringLiteral) {
this.throwErrorForNode(node, 'The remote binding source name must be a string literal.');
}
property.remoteBinding.sourceName = (remoteArguments[0] as ts.StringLiteral).text;
// Set up the default values
property.remoteBinding.timeout = 0;
property.remoteBinding.foldType = TWPropertyRemoteFoldKind.None;
property.remoteBinding.pushType = TWPropertyRemotePushKind.Value;
property.remoteBinding.pushThreshold = '0.0';
property.remoteBinding.aspects = {
startType: TWPropertyRemoteStartKind.DefaultValue
}
// These exist in exported files, but are not allowed to be in extension files
/*
if (this.entityKind == TWEntityKind.Thing) {
property.remoteBinding.aspects.source = '';
property.remoteBinding.aspects.tagAddress = '';
}
*/
if (remoteArguments.length == 2) {
if (remoteArguments[1].kind != ts.SyntaxKind.ObjectLiteralExpression) {
this.throwErrorForNode(node, 'The aspects of a remote binding decorator must be specified as an object literal.');
}
const bindingAspects = remoteArguments[1] as ts.ObjectLiteralExpression;
for (const bindingAspect of bindingAspects.properties) {
if (bindingAspect.kind != ts.SyntaxKind.PropertyAssignment) {
this.throwErrorForNode(node, 'The aspects of a remote binding decorator must be literals.');
}
if (bindingAspect.name.kind != ts.SyntaxKind.Identifier) {
this.throwErrorForNode(node, 'Computed property names cannot be used in decorator parameters.');
}
const name = (bindingAspect.name as ts.Identifier).text;
// Undefined aspect values should continue to use the default values
if (bindingAspect.initializer.kind == ts.SyntaxKind.UndefinedKeyword) continue;
switch (name) {
case 'pushType':
property.remoteBinding.pushType = (bindingAspect.initializer as ts.StringLiteral).text as TWPropertyRemotePushKind;
break;
case 'pushThreshold':
property.remoteBinding.pushThreshold = bindingAspect.initializer.getText();
break;
case 'startType':
property.remoteBinding.aspects.startType = (bindingAspect.initializer as ts.StringLiteral).text as TWPropertyRemoteStartKind;
break;
case 'foldType':
property.remoteBinding.foldType = (bindingAspect.initializer as ts.StringLiteral).text as TWPropertyRemoteFoldKind;
break;
case 'cacheTime':
property.aspects.cacheTime = parseFloat((bindingAspect.initializer as ts.NumericLiteral).text);
break;
case 'timeout':
property.remoteBinding.timeout = parseFloat((bindingAspect.initializer as ts.NumericLiteral).text);
break;
}
}
}
}
// Create a local binding if it has been specified
if (this.hasDecoratorNamed('local', node)) {
if (property.remoteBinding) this.throwErrorForNode(node, 'A property cannot be both locally and remotely bound.');
property.localBinding = {aspects: {}, name: property.name} as TWPropertyBinding;
const localArguments = this.argumentsOfDecoratorNamed('local', node)!;
if (localArguments.length != 2) {
this.throwErrorForNode(node, 'The local binding decorator must have two arguments.');
}
for (const argument of localArguments) {
if (argument.kind != ts.SyntaxKind.StringLiteral) this.throwErrorForNode(node, 'The local binding decorator arguments must be string literals.');
}
property.localBinding.sourceThingName = (localArguments[0] as ts.StringLiteral).text;
property.localBinding.sourceName = (localArguments[1] as ts.StringLiteral).text;
}
// Minimum value aspect
const minimumValue = this.numericArgumentOfDecoratorNamed('minimumValue', node);
if (minimumValue) {
if (![TWBaseTypes.INTEGER, TWBaseTypes.LONG, TWBaseTypes.NUMBER, TWBaseTypes.integer, TWBaseTypes.long, TWBaseTypes.number].includes(property.baseType)) {
this.throwErrorForNode(node, 'The minimum value decorator can only be used with numerical type properties.');
}
const minimumValueNum = parseFloat(minimumValue);
if (isNaN(minimumValueNum)) {
this.throwErrorForNode(node, `The minimum value decorator argument must be a number.`);
}
if (property.aspects.defaultValue && property.aspects.defaultValue < minimumValueNum) {
this.throwErrorForNode(node, 'The minimum value decorator argument must be less than the default value.');
}
property.aspects.minimumValue = minimumValueNum;
}
// Maximum value aspect
const maximumValue = this.numericArgumentOfDecoratorNamed('maximumValue', node);
if (maximumValue) {
if (![TWBaseTypes.INTEGER, TWBaseTypes.LONG, TWBaseTypes.NUMBER, TWBaseTypes.integer, TWBaseTypes.long, TWBaseTypes.number].includes(property.baseType)) {
this.throwErrorForNode(node, 'The minimum value decorator can only be used with numerical type properties.');
}
const maximumValueNum = parseFloat(maximumValue);
if (isNaN(maximumValueNum)) {
this.throwErrorForNode(node, 'The maximum value decorator argument must be a number.');
}
if (property.aspects.defaultValue && property.aspects.defaultValue > maximumValueNum) {
this.throwErrorForNode(node, 'The maximum value decorator argument must be greater than the default value.');
}
if (property.aspects.minimumValue && property.aspects.minimumValue > maximumValueNum) {
this.throwErrorForNode(node, 'The maximum value for the property must be greater than its minimum value.');
}
property.aspects.maximumValue = maximumValueNum;
}
// Units aspect
if (this.hasDecoratorNamed('unit', node)) {
const argument = this.literalArgumentOfDecoratorNamed('unit', node);
if (!argument) {
this.throwErrorForNode(node, 'The unit decorator must have a string literal as its argument');
}
if (![TWBaseTypes.INTEGER, TWBaseTypes.LONG, TWBaseTypes.NUMBER].includes(property.baseType)) {
this.throwErrorForNode(node, 'The minimum value decorator can only be used with numeric properties.');
}
property.aspects.units = argument;
}
// Set up the data change aspects if specified
if (this.hasDecoratorNamed('dataChangeType', node)) {
const dataChangeArguments = this.argumentsOfDecoratorNamed('dataChangeType', node)!;
if (dataChangeArguments[0].kind != ts.SyntaxKind.StringLiteral) {
this.throwErrorForNode(node, 'Data change decorator arguments must be string literals.');
}
const dataChangeType = dataChangeArguments[0] as ts.StringLiteral;
property.aspects.dataChangeType = dataChangeType.text as TWPropertyDataChangeKind;
if (dataChangeArguments[1]) {
property.aspects.dataChangeThreshold = dataChangeArguments[1].getText();
}
}
this.runtimePermissions = this.mergePermissionListsForNode([this.runtimePermissions].concat(this.permissionsOfNode(node, node.name.text)), node);
this.properties.push(property);
}
/**
* Visits a property node that represents an event definition.
* @param node The node to visit.
*/
visitEvent(node: ts.PropertyDeclaration) {
const event = {} as TWEventDefinition;
if (node.name.kind != ts.SyntaxKind.Identifier) this.throwErrorForNode(node, 'Event names cannot be computed names.');
event.name = (node.name as ts.Identifier).text;
event.description = this.documentationOfNode(node);
const typeNode = node.type as ts.TypeReferenceNode;
if (typeNode.typeArguments && typeNode.typeArguments.length) {
if (typeNode.typeArguments[0].kind == ts.SyntaxKind.LiteralType) {
event.dataShape = ((typeNode.typeArguments[0] as ts.LiteralTypeNode).literal as ts.StringLiteral).text;
}
else {
event.dataShape = typeNode.typeArguments[0].getText();
}
}
if (this.hasDecoratorNamed('remoteEvent', node)) {
event.remoteBinding = {
name: event.name,
sourceName: ''
}
const args = this.argumentsOfDecoratorNamed('remoteEvent', node)!;
if (!args.length || !args) this.throwErrorForNode(node, 'The remote event decorator must have a single argument.');
const arg = args[0];
if (arg.kind != ts.SyntaxKind.StringLiteral) this.throwErrorForNode(node, 'The argument for the remoteEvent decorator must be a string literal');
event.remoteBinding.sourceName = (arg as ts.StringLiteral).text;
}
this.runtimePermissions = this.mergePermissionListsForNode([this.runtimePermissions].concat(this.permissionsOfNode(node, node.name.text)), node);
this.events.push(event);
}
getDescription(node?: ts.JSDoc | ts.JSDocTag): string | undefined {
if (typeof node?.comment != 'string') {
return node?.comment?.reduce((acc, val) => acc + val.text, "");
}
return node?.comment as string;
}
/**
* Visits a service or subscription definition.
* @param node The node to visit.
*/
visitMethod(node: ts.MethodDeclaration): ts.MethodDeclaration {
if (this.hasDecoratorNamed('subscription', node) || this.hasDecoratorNamed('localSubscription', node)) {
return this.visitSubscription(node);
}
const service = {aspects: {}} as TWServiceDefinition;
if (node.modifiers) for (const modifier of node.modifiers) {
if (modifier.kind == ts.SyntaxKind.AsyncKeyword) {
service.aspects = {isAsync: true};
}
}
const originalNode = node;
if (node.name.kind != ts.SyntaxKind.Identifier) this.throwErrorForNode(node, 'Service names cannot be computed property names.');
service.name = (node.name as ts.Identifier).text;
service.isAllowOverride = !this.hasDecoratorNamed('final', node);
service.isOverriden = this.hasDecoratorNamed('override', node);
service.isLocalOnly = false;
service.isPrivate = false;
service.isOpen = false;
if (this.hasDecoratorNamed('remoteService', node)) {
// Decorators can't be applied to abstract methods, instead, by convention, the body of the remote
// service will be ignored
//if (!node.modifiers) this.throwErrorForNode(node, 'Remote services must be declared abstract.');
/*const isAbstract = node.modifiers.some(modifier => modifier.kind == ts.SyntaxKind.AbstractKeyword);
if (!isAbstract) this.throwErrorForNode(node, 'Remote services must be declared abstract.');*/
const args = this.argumentsOfDecoratorNamed('remoteService', node)!;
service.remoteBinding = {
name: service.name,
sourceName: (args[0] as ts.StringLiteral).text,
timeout: 0,
enableQueue: false
}
if (args.length == 2) {
if (args[1].kind != ts.SyntaxKind.ObjectLiteralExpression) {
this.throwErrorForNode(node, 'Remote service binding aspects must be specified as an object literal.');
}
const aspects = args[1] as ts.ObjectLiteralExpression;
for (const bindingAspect of aspects.properties) {
if (bindingAspect.kind != ts.SyntaxKind.PropertyAssignment) {
this.throwErrorForNode(node, 'The aspects of a remote binding decorator must be literals.');
}
if (bindingAspect.name.kind != ts.SyntaxKind.Identifier) {
this.throwErrorForNode(node, 'Computed property names cannot be used in decorator parameters.');
}
const name = (bindingAspect.name as ts.Identifier).text;
// Undefined aspect values should continue to use the default values
if (bindingAspect.initializer.kind == ts.SyntaxKind.UndefinedKeyword) continue;
switch (name) {
case 'enableQueue':
service.remoteBinding.enableQueue = bindingAspect.initializer.getText() == 'true';
break;
case 'timeout':
service.remoteBinding.timeout = parseFloat(bindingAspect.initializer.getText());
break;
}
}
}
}
else {
service.code = node.body!.getText();
if (this.debug) {
this.debugMethodNodes.add(node);
}
}
// Services must always have a single destructured object argument
if (node.parameters.length > 1) {
this.throwErrorForNode(node, 'Services an only have a single destructured parameter.');
}
else if (node.parameters.length) {
service.parameterDefinitions = [];
const argList = node.parameters[0];
if (argList.name.kind != ts.SyntaxKind.ObjectBindingPattern) {
this.throwErrorForNode(node, 'The parameter of a service must be a destructured object.');
}
if (!argList.type) {
this.throwErrorForNode(node, 'The parameter of a service must be typed.');
}
if (argList.type.kind != ts.SyntaxKind.TypeLiteral && argList.type.kind != ts.SyntaxKind.TypeReference) {
this.throwErrorForNode(node, 'The type of a service parameter must be a literal or an interface.');
}
let type: ts.TypeLiteralNode;
if (argList.type.kind == ts.SyntaxKind.TypeReference) {
const typeChecker = this.program.getTypeChecker();
const symbol = typeChecker.getTypeAtLocation(argList.type);
if (symbol) {
const literalType = symbol;
if (!literalType.isClassOrInterface()) {
this.throwErrorForNode(node, 'The type of the service parameter list must be a literal or interface.');
}
const declarations = literalType.getProperties().flatMap(p => p.declarations).filter(d => !!d) as ts.Declaration[];
const typeElements = declarations.filter(d => ts.isTypeElement(d)) as ts.TypeElement[];
type = ts.factory.createTypeLiteralNode(typeElements);
}
else {
this.throwErrorForNode(node, 'The type of the service parameter list cannot be resolved.');
}
} else {
type = argList.type as ts.TypeLiteralNode;
}
const args = argList.name as ts.ObjectBindingPattern;
const argTypes = type;
if (args.elements.length != argTypes.members.length) {
this.throwErrorForNode(node, 'All service parameters must be destructured.');
}
for (const arg of args.elements) {
const parameter = {aspects: {}} as TWServiceParameter;
if (arg.name.kind != ts.SyntaxKind.Identifier) this.throwErrorForNode(node, 'Service parameter names cannot be computed property names.');
parameter.name = arg.name.getText();
// Find the accompanying type for this parameter
const type = argTypes.members.find(t => t.name!.getText() == parameter.name) as ts.PropertySignature;
if (!type) this.throwErrorForNode(node, `Parameter ${parameter.name} is untyped.`);
const typeNode = type.type as ts.TypeReferenceNode;
parameter.aspects.isRequired = !type.questionToken;
const baseType = TypeScriptPrimitiveTypes.includes(typeNode.kind) ? typeNode.getText() : typeNode.typeName.getText();
if (!(baseType in TWBaseTypes)) {
this.throwErrorForNode(node, `Unknown base type ${baseType} specified for parameter ${parameter.name}.`);
}
parameter.baseType = TWBaseTypes[baseType];
if (arg.initializer) {
if (arg.initializer.kind == ts.SyntaxKind.PropertyAccessExpression) {
// Const enums need to be resolved early on
parameter.aspects.defaultValue = this.constantValueOfExpression(arg.initializer as ts.PropertyAccessExpression);
// If the value is not a compile time constant, it is not a valid initializer
if (parameter.aspects.defaultValue === undefined) {
this.throwErrorForNode(arg, `Unknown initializer for argument.`);
}
}
else if (ts.isNewExpression(arg.initializer) && ts.isIdentifier(arg.initializer.expression) && arg.initializer.expression.escapedText == 'Date') {
if (arg.initializer.arguments && arg.initializer.arguments.length == 1 && ts.isStringLiteral(arg.initializer.arguments[0])) {
parameter.aspects.defaultValue = new Date(arg.initializer.arguments[0].text).toISOString();
}
else {
this.throwErrorForNode(node, 'Exactly one string literal argument is required when setting Date as default value.');
}
}
else {
parameter.aspects.defaultValue = (arg.initializer as ts.LiteralExpression).text || arg.initializer.getText();
}
}
// INFOTABLE can optionally take the data shape as a type argument
if (TWBaseTypes[baseType] == 'INFOTABLE') {
const typeNode = type.type! as ts.NodeWithTypeArguments;
const typeArguments = typeNode.typeArguments;
if (typeArguments) {
if (typeArguments.length != 1) this.throwErrorForNode(node, `Unknown generics specified for parameter ${parameter.name}: ${parameter.baseType}`);
if (typeArguments[0].kind == ts.SyntaxKind.LiteralType) {
parameter.aspects.dataShape = ((typeArguments[0] as ts.LiteralTypeNode).literal as ts.StringLiteral).text;
}
else {
parameter.aspects.dataShape = typeArguments[0].getText();
}
}
}
// THINGNAME can optionally take the thing template name and/or thing shape name as a type argument
else if (TWBaseTypes[baseType] == 'THINGNAME') {
const typeNode = type.type! as ts.NodeWithTypeArguments;
const typeArguments = typeNode.typeArguments;
if (typeArguments && typeArguments.length) {
if (typeArguments.length > 2) this.throwErrorForNode(node, `Unknown generics specified for parameter ${parameter.name}: ${parameter.baseType}`);
const thingTemplate = typeArguments[0];
if (thingTemplate.kind == ts.SyntaxKind.LiteralType) {
parameter.aspects.thingTemplate = ((thingTemplate as ts.LiteralTypeNode).literal as ts.StringLiteral).text;
}
const thingShape = typeArguments[1];
if (thingShape && thingShape.kind == ts.SyntaxKind.LiteralType) {
parameter.aspects.thingShape = ((thingShape as ts.LiteralTypeNode).literal as ts.StringLiteral).text;
}
}
}
service.parameterDefinitions.push(parameter);
}
// Mark this node for replacement
this.nodeReplacementMap.set(originalNode.parameters[0], ts.factory.createParameterDeclaration(
undefined,
undefined,
undefined,
ts.factory.createObjectBindingPattern([]),
undefined,
undefined,
undefined
));
}
else {
service.parameterDefinitions = [];
}
if (!node.type) {
if (!service.aspects.isAsync) {
this.throwErrorForNode(originalNode, 'The return type of non-async services must be specified.');
}
else {
service.resultType = {} as TWServiceParameter;
service.resultType.name = 'result';
service.resultType.baseType = 'NOTHING';
}
}
else {
service.resultType = {} as TWServiceParameter;
service.resultType.name = 'result';
// Don't care about the return type of async services
if (service.aspects.isAsync) {
service.resultType.baseType = 'NOTHING';
if (node.type) {
this.throwErrorForNode(originalNode, 'Async services must not have a return type annotation.');
}
}
else {
const typeNode = node.type as ts.TypeReferenceNode;
const baseType = TypeScriptReturnPrimitiveTypes.includes(typeNode.kind) ? typeNode.getText() : typeNode.typeName.getText();
if (!(baseType in TWBaseTypes)) {
this.throwErrorForNode(originalNode, `Unknown base type ${baseType} specified for service return type.`);
}
// INFOTABLE can optionally take the data shape as a type argument
if (TWBaseTypes[baseType] == 'INFOTABLE') {
const typeNode = node.type! as ts.NodeWithTypeArguments;
service.resultType.aspects = service.resultType.aspects || {};
const typeArguments = typeNode.typeArguments;
if (typeArguments) {
if (typeArguments.length != 1) this.throwErrorForNode(originalNode, `Unknown generics specified for service result: ${service.resultType.baseType}`);
if (typeArguments[0].kind == ts.SyntaxKind.LiteralType) {
service.resultType.aspects.dataShape = ((typeArguments[0] as ts.LiteralTypeNode).literal as ts.StringLiteral).text;
}
else {
service.resultType.aspects.dataShape = typeArguments[0].getText();
}
}
}
// THINGNAME can optionally take the thing template name and/or thing shape name as a type argument, however
// this is not supported by Thingworx in service results, so it is ignored
else if (TWBaseTypes[baseType] == 'THINGNAME') {
const typeNode = node.type! as ts.NodeWithTypeArguments;
service.resultType.aspects = service.resultType.aspects || {};
}
service.resultType.baseType = TWBaseTypes[baseType];
}
}
const documentation = (ts as any).getJSDocCommentsAndTags(node) as ts.Node[];
if (documentation && documentation.length) for (const documentationNode of documentation) {
// Get the first JSDocComment
if (documentationNode.kind == ts.SyntaxKind.JSDocComment) {
// Its text represents the service description
const JSDocComment = documentationNode as ts.JSDoc;
service.description = this.getDescription(JSDocComment) || '';
// The various tags represent the parameter and result type descriptions
if (JSDocComment.tags) for (const tag of JSDocComment.tags) {
// The return tag can be applied directly to the result type
if (tag.kind == ts.SyntaxKind.JSDocReturnTag) {
service.resultType.description = this.getDescription(tag) || '';
}
// For parameters it is necessary to match each parameter to its corresponding tag
else if (tag.kind == ts.SyntaxKind.JSDocParameterTag) {
const parameterTag = tag as ts.JSDocParameterTag;
for (const parameter of service.parameterDefinitions) {
if (parameterTag.name.getText() == parameter.name) {
parameter.description = this.getDescription(parameterTag) || '';
break;
}
}
}
}
}
}
// If this service should be used for deployment, add its endpoint
if (this.hasDecoratorNamed('deploy', originalNode)) {
if (this.entityKind != TWEntityKind.Thing) {
this.throwErrorForNode(originalNode, `The @deploy decorator can only be used on thing services.`);
}
this.deploymentEndpoints.push(`Things/${this.exportedName}/Services/${service.name}`);
}
this.runtimePermissions = this.mergePermissionListsForNode([this.runtimePermissions].concat(this.permissionsOfNode(node, service.name)), node);
this.services.push(service);
return node;
}
/**
* Visits a method declaration that represents a subscription definition.
* @param node The node to visit.
*/
visitSubscription(node: ts.MethodDeclaration): ts.MethodDeclaration {
const subscription = {
source: '',
sourceProperty: ''
} as TWSubscriptionDefinition;
subscription.enabled = true;
if (this.hasDecoratorNamed('subscription', node) && this.hasDecoratorNamed('localSubscription', node)) {
this.throwErrorForNode(node, 'A method cannot have both the "subscription" and "localSubscription" decorators applied.');
}
subscription.name = node.name.getText();
subscription.description = this.documentationOfNode(node);
if (this.hasDecoratorNamed('localSubscription', node)) {
subscription.sourceType = this.entityKind as unknown as TWSubscriptionSourceKind;
const localArguments = this.argumentsOfDecoratorNamed('localSubscription', node)!;
for (const arg of localArguments) {
if (arg.kind != ts.SyntaxKind.StringLiteral) this.throwErrorForNode(node, 'The arguments of the localSubscription decorator must be string literals.');
}
subscription.eventName = (localArguments[0] as ts.StringLiteral).text;
if (subscription.eventName == 'DataChange') {
subscription.sourceProperty = (localArguments[1] as ts.StringLiteral).text;
}
}
else {
subscription.sourceType = TWSubscriptionSourceKind.Thing;
const localArguments = this.argumentsOfDecoratorNamed('subscription', node)!;
for (const arg of localArguments) {
if (arg.kind != ts.SyntaxKind.StringLiteral) this.throwErrorForNode(node, 'The arguments of the subscription decorator must be string literals.');
}
subscription.source = (localArguments[0] as ts.StringLiteral).text;
subscription.eventName = (localArguments[1] as ts.StringLiteral).text;
if (subscription.eventName == 'DataChange') {
subscription.sourceProperty = (localArguments[2] as ts.StringLiteral).text;
}
}
subscription.code = node.body!.getText();
const permissions = this.permissionsOfNode(node);
if (Object.keys(permissions).length) {
this.throwErrorForNode(node, `Permission decorators are not allowed for subscriptions.`);
}
if (this.hasDecoratorNamed('deploy', node)) {
this.throwErrorForNode(node, `The @deploy decorator cannot be used on subscriptions.`);
}
if (this.debug) {
this.debugMethodNodes.add(node);
}
this.subscriptions.push(subscription);
return node;
}
visitMethodNode(node: ts.Node): ts.Node | undefined {
node = ts.visitEachChild(node, n => this.visitMethodNode(n), this.context);
// If the node has been marked for replacement, return its replacement directly
if (this.nodeReplacementMap.get(node)) {
return this.nodeReplacementMap.get(node)!;
}
switch (node.kind) {
case ts.SyntaxKind.AsyncKeyword:
return;
case ts.SyntaxKind.PropertyAssignment:
const n1 = node as ts.PropertyAssignment;
//return n1;
return ts.factory.createPropertyAssignment(n1.name, this.commaCheckpointExpression(n1.initializer));
case ts.SyntaxKind.VariableDeclaration:
const n2 = node as ts.VariableDeclaration;
if (n2.initializer) {
return ts.factory.createVariableDeclaration(n2.name, n2.exclamationToken, n2.type, this.commaCheckpointExpression(n2.initializer));
}
break;
case ts.SyntaxKind.IfStatement:
const n4 = node as ts.IfStatement;
return ts.factory.createIfStatement(this.commaCheckpointExpression(n4.expression), n4.thenStatement, n4.elseStatement);
case ts.SyntaxKind.ExpressionStatement:
const n5 = node as ts.ExpressionStatement;
return ts.factory.createExpressionStatement(this.commaCheckpointExpression(n5.expression, n5));
case ts.SyntaxKind.WhileStatement:
const n6 = node as ts.WhileStatement;
return ts.factory.createWhileStatement(this.commaCheckpointExpression(n6.expression), n6.statement);
case ts.SyntaxKind.ForStatement:
const n7 = node as ts.ForStatement;
return ts.factory.createForStatement(
n7.initializer,
n7.condition ? this.commaCheckpointExpression(n7.condition) : n7.condition,
n7.incrementor ? this.commaCheckpointExpression(n7.incrementor) : n7.incrementor,
n7.statement
);
case ts.SyntaxKind.DoStatement:
const n8 = node as ts.DoStatement;
return ts.factory.createDoStatement(n8.statement, this.commaCheckpointExpression(n8.expression));
case ts.SyntaxKind.BinaryExpression:
const n9 = node as ts.BinaryExpression;
if (n9.operatorToken.kind == ts.SyntaxKind.EqualsToken) {
return ts.factory.createBinaryExpression(n9.left, n9.operatorToken, this.commaCheckpointExpression(n9.right));
}
break;
case ts.SyntaxKind.ReturnStatement:
const n10 = node as ts.ReturnStatement;
return ts.factory.createReturnStatement(n10.expression ? this.commaCheckpointExpression(n10.expression) : this.commaCheckpointExpression(undefined, n10));
case ts.SyntaxKind.CallExpression:
const n11 = node as ts.CallExpression;
if (n11.parent) {
switch (n11.parent.kind) {
case ts.SyntaxKind.PropertyDeclaration:
case ts.SyntaxKind.VariableDeclaration:
case ts.SyntaxKind.ExpressionStatement:
return n11;
case ts.SyntaxKind.BinaryExpression:
const parent = n11.parent as ts.BinaryExpression;
if (parent.right == n11 && parent.operatorToken.kind == ts.SyntaxKind.EqualsToken) {
return n11;
}
}
}
return this.commaCheckpointExpression(n11);
case ts.SyntaxKind.PropertyAccessExpression:
// Inline constant values where possible. In debug builds this will skip the regular visit method
// TODO: These should be combined into one
const constantValue = this.constantValueOfExpression(node as ts.PropertyAccessExpression);
if (typeof constantValue == 'string') {
return ts.factory.createStringLiteral(constantValue);
}
else if (typeof constantValue == 'number') {
return ts.factory.createNumericLiteral(constantValue.toString());
}
break;
case ts.SyntaxKind.Identifier:
const n12 = node as ts.Identifier;
if (n12.text == '__d') {
this.throwErrorForNode(node, `The "__d" identifier is reserved for the debugger in debug builds.`);
}
}
return node;
}
/**
* A counter that keeps track of each breakpoint location that was added.
*/
private _debugBreakpointCounter = 0;
/**
* Returns an expression that represents a debug checkpoint.
* @param ID A unique ID that identifies this expression.
* @returns A typescript expression.
*/
debugCheckpointExpression(ID: string): ts.Expression {
// Essentially returns __d.checkpoint(ID)
return ts.factory.createCallExpression(
ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier('__d'), 'checkpoint'),
[],
[ts.factory.createStringLiteral(ID, true)]
);
}
/**
* Creates a comma expression that adds a debug checkpoint to the given expression.
* Also stores information about the breakpoint location that was just added.
* @param expression The expression to modify. If `undefined`, a new expression will be returned.
* @param targetNode When `expression` is `undefined`, the node from which to get the position information.
* @returns A typescript expression.
*/
commaCheckpointExpression(expression: ts.Expression | undefined, targetNode?: ts.Node): ts.Expression {
this.initDebugConfiguration();
this._debugBreakpointCounter++;
if (!expression && !targetNode) {
throw new Error('Unable to create a breakpoint location without a context');
}
let positionNode: ts.Node | undefined = expression;
if (!positionNode || positionNode.pos == -1 || positionNode.end == -1) {
// If the expression is a synthetic node, attempt to use the target node instead
if (targetNode) {
positionNode = targetNode;
}
}
// If the node is a synthetic node, try to position the breakpoint at the closest non-synthetic parent
while (positionNode) {
if (positionNode.pos == -1 || positionNode.end == -1) {
positionNode = positionNode.parent;
}
else {
break;
}
}
// Create an ID for this breakpoint location
const ID = this.filename + '-' + this._debugBreakpointCounter;
if (!positionNode) {
// If position information cannot be determined, don't add a breakpoint
if (expression) {
return expression;
}
else {
return ts.factory.createOmittedExpression();
}
}
// Store information about the breakpoint's location
const startPosition = positionNode.getStart(this.sourceFile, false);
const endPosition = positionNode.getEnd();
const start = ts.getLineAndCharacterOfPosition(this.sourceFile!, startPosition);
const end = ts.getLineAndCharacterOfPosition(this.sourceFile!, endPosition);
// NOTE: Lines and characters are 0-indexed by the compiler, but 1-indexed by the debugger
const breakpoint: Breakpoint = {
line: start.line + 1,
column: start.character + 1,
endLine: end.line + 1,
endColumn: end.character + 1,
locationID: ID
};
// If a breakpoint at this location already exists, don't add a new one
if (this.breakpointLocations[breakpoint.line]) {
if (this.breakpointLocations[breakpoint.line][breakpoint.column!]) {
if (expression) {
return expression;
}
else {
return ts.factory.createOmittedExpression();
}
}
}
this.breakpointLocations[breakpoint.line] = this.breakpointLocations[breakpoint.line] || {};
this.breakpointLocations[breakpoint.line][breakpoint.column!] = true;
this.breakpoints.push(breakpoint);
if (expression) {
return ts.factory.createCommaListExpression([this.debugCheckpointExpression(ID), expression]);
}
else {
return this.debugCheckpointExpression(ID);
}
}
/**
* Returns the emit result of the body of the specified function declaration. This will strip
* out the surrounding braces.
* @param node The function declaration.
* @return The emit result.
*/
transpiledBodyOfFunctionDelcaration(node: ts.FunctionDeclaration): string {
const result = ts.createPrinter().printNode(ts.EmitHint.Unspecified, node.body!, (this as any).source);
return result.substring(1, result.length - 1);
}
/**
* Returns the emit result of the body of the specified function declaration and inlines any helpers necessary
* for the method to function.
* @param node The function declaration.
* @return The emit result, with added helpers as necessary.
*/
transpiledBodyOfThingworxMethod(node: ts.FunctionDeclaration): string {
// If no helpers are used, just return the compiled method
const helpers = ts.getEmitHelpers((this as any).source);
// Note that the __extends helper is always included to implement classes; if it is the only one used, skip searching
if (!helpers || !helpers.length || (helpers.length == 1 && helpers[0].name == 'typescript:extends')) {
return this.transpiledBodyOfFunctionDelcaration(node);
}
// Some helpers depend on others only via their body text and not via the
// generated js code
// This is something I may need to keep up to date.
// TODO: Need a way to automate this.
const dependencies = {
'typescript:read': ['typescrript:values'],
'typescript:spread': ['typescript:read'],
'typescript:asyncGenerator': ['typescript:await'],
'typescript:asyncDelegator': ['typescript:await'],
'typescript:asyncValues': ['typescript:values']
}
// Some helpers can use a little help to work better with thingworx
// This contains a few replacements for some of the helpers
const codeMap = {
// The read helper requires symbol support, but it can work for thingworx with just
// the __values helper replacing symbols
'typescript:read': `var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
var i = (m ? m.call(o) : __values(o)), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};`
}
// Otherwise need to look up usages for each helper and inline it
const helpersToInline = new Set<ts.EmitHelper>();
const visitor = (node: ts.Node) => {
// All helpers so far are global functions, so need to look for function invocations
if (node.kind == ts.SyntaxKind.CallExpression) {
const callNode = node as ts.CallExpression;
if (callNode.expression.kind == ts.SyntaxKind.Identifier) {
// A helper is considered to be used if the call expression is an identifier
// whose text matches the "import name" of the helper
const callIdentifier = (callNode.expression as ts.Identifier).text;
for (const helper of helpers) {
if ((helper as any).importName == callIdentifier) {
// If found, add the helper to a set that will be added to the method body directly
helpersToInline.add(helper);
}
}
}
}
node.forEachChild(visitor);
}
node.forEachChild(visitor);
// Need to ensure that all helper dependencies exist in the set
let size;
do {
size = helpersToInline.size;
if (helpersToInline.size) for (const helper of [...helpersToInline]) {
if (dependencies[helper.name]) for (const dependency of dependencies[helper.name]) {
for (const rootHelper of helpers) {
if (rootHelper.name == dependency) helpersToInline.add(rootHelper);
}
}
}
} while (helpersToInline.size != size)
// After identifying the helpers, join their text and add them to the transpiled method body
return [...helpersToInline].map(helper => codeMap[helper.name] || helper.text).join('\n\n') + this.transpiledBodyOfFunctionDelcaration(node);
}
/**
* Invoked during the after phase. Visits function definitions and identifies which represent service
* implementations.
* @param node The node to visit.
*/
visitTranspiledMethod(node: any) {
// Ensure that this is a top-level method
// Find the original node
let originalNode = node.original;
while (originalNode.original) {
originalNode = originalNode.original;
}
const methodNode = originalNode as ts.MethodDeclaration;
const name = (methodNode.name as ts.Identifier).text;
if (name) {
// The parent node should be the classNode whose parent should be the source file
if (!methodNode.parent) return;
if (methodNode.parent.kind != ts.SyntaxKind.ClassDeclaration) return;
const classDeclaration = methodNode.parent;
if (!classDeclaration.parent) return;
if (classDeclaration.parent.kind != ts.SyntaxKind.SourceFile) return;
if (!classDeclaration.name) return;
const className = classDeclaration.name!.text;
if (!className) return;
const store = this.store || global._TWEntities;
const entity = store[className];
if (!entity) return;
for (const service of entity.services) {
if (service.name == name) {
//const body = ts.createPrinter().printNode(ts.EmitHint.Unspecified, node.body, (this as any).source);
service.code = this.transpiledBodyOfThingworxMethod(node);
// In debug mode, additional code is added to activate and deactivate the debugger
if (this.debug) {
service.code = `
const __d = BMDebuggerRuntime.localDebugger();
const __dLogger = __d.getLogger();
__d.retainForService({name: ${JSON.stringify(service.name)}, filename: ${JSON.stringify(entity.sourceFile?.fileName)}, scopeStack: []});
try {
var result = (function (logger) {${service.code}}).apply(me, [__dLogger]);
}
finally {
__d.release();
}`;
}
else {
service.code = `var result = (function () {${service.code}}).apply(me)`;
}
}
}
for (const subscription of entity.subscriptions) {
if (subscription.name == name) {
if (this.debug) {
// In debug builds, an applied anonymous function is used because this is no longer transformed to me
subscription.code = this.transpiledBodyOfThingworxMethod(node);
subscription.code = `
const __d = BMDebuggerRuntime.localDebugger();
const __dLogger = __d.getLogger();
__d.retainForService({name: ${JSON.stringify(subscription.name)}, filename: ${JSON.stringify(entity.sourceFile?.fileName)}, scopeStack: []});
try {
(function (logger) {${subscription.code}}).apply(me, [__dLogger]);
}
finally {
__d.release();
}`;
}
else {
//const body = ts.createPrinter().printNode(ts.EmitHint.Unspecified, node.body, (this as any).source);
subscription.code = this.transpiledBodyOfThingworxMethod(node);
}
}
}
}
}
/**
* Visits a class expression that represents a configuration table definition.
* @param node The node to visit.
*/
visitConfigurationTablesDefinition(node: ts.ClassExpression) {
if (node.name) this.throwErrorForNode(node, `The argument for the @ConfigurationTables decorator must be an anonymous class.`);
if (node.heritageClauses) this.throwErrorForNode(node, `The argument for the @ConfigurationTables decorator must be a root class.`);
for (const member of node.members) {
if (member.kind == ts.SyntaxKind.MethodDeclaration) this.throwErrorForNode(node, `The @ConfigurationTables class cannot contain methods.`);
if (!member.name || member.name.kind != ts.SyntaxKind.Identifier) this.throwErrorForNode(member, `Configuration table names cannot be computed.`);
const table: TWConfigurationTable = {
category: '',
description: '',
'isHidden': false,
name: member.name.text,
dataShapeName: '',
isMultiRow: false
};
const property = member as ts.PropertyDeclaration;
const type = property.type as ts.TypeReferenceNode;
if (!type) this.throwErrorForNode(member, `Configuration table properties must be typed as either "Table" or "MultiRowTable".`);
if (property.type!.kind != ts.SyntaxKind.TypeReference) {
this.throwErrorForNode(member, `Configuration table properties must be typed as either "Table" or "MultiRowTable".`);
}
if (type.typeName.getText() == 'Table') {
table.isMultiRow = false;
}
else if (type.typeName.getText() == 'MultiRowTable') {
table.isMultiRow = true;
}
else {
this.throwErrorForNode(member, `Configuration table properties must be typed as either "Table" or "MultiRowTable".`);
}
if (!type.typeArguments || type.typeArguments.length != 1) this.throwErrorForNode(member, `Configuration table properties must have one type parameter representing the data shape name.`);
const typeArgument = type.typeArguments[0];
if (typeArgument.kind == ts.SyntaxKind.TypeReference) {
table.dataShapeName = (typeArgument as ts.TypeReferenceNode).typeName.getText();
}
else if (typeArgument.kind == ts.SyntaxKind.LiteralType) {
table.dataShapeName = ((typeArgument as ts.LiteralTypeNode).literal as ts.StringLiteral).text;
}
else {
this.throwErrorForNode(member, `The configuration table type argument must be a data shape class reference or exported name.`);
}
this.configurationTableDefinitions.push(table);
}
}
/**
* Set to `true` when the debug configuration table is created.
*/
_debugConfigurationInitialized = false;
/**
* For debug builds with at least one breakpoint location, creates a configuration table
* that stores various debug information.
*/
initDebugConfiguration() {
if (!USE_DEBUG_CONFIGURATION_TABLE) return;
if (this._debugConfigurationInitialized) return;
this._debugConfigurationInitialized = true;
// Add a configuration table for the breakpoint locations
this.configurationTableDefinitions.push({
isHidden: true,
dataShapeName: 'BMDebuggerBreakpointLocation',
isMultiRow: true,
category: 'debug',
description: 'Contains information about the available breakpoint locations in this entity\'s source file',
name: '_BMDebuggerBreakpointLocations'
});
// Add a configuration table for additional metadata
this.configurationTableDefinitions.push({
isHidden: true,
dataShapeName: 'BMDebugMetadata',
isMultiRow: false,
category: 'debug',
description: 'Contains information that is useful for debugging',
name: '_BMDebugMetadata'
})
}
/**
* Visits an object literal expression that represents a configuration table.
* @param node The node to visit.
*/
visitConfiguration(node: ts.ObjectLiteralExpression) {
this.configuration = {};
for (const member of node.properties) {
if (member.kind == ts.SyntaxKind.MethodDeclaration) this.throwErrorForNode(node, `The @config object cannot contain methods.`);
if (member.kind != ts.SyntaxKind.PropertyAssignment) this.throwErrorForNode(node, `The @config object must contain only property assignments.`);
if (!member.name || member.name.kind != ts.SyntaxKind.Identifier) this.throwErrorForNode(member, `Configuration table names cannot be computed.`);
const name = member.name.text;
const property = member as ts.PropertyAssignment;
const table: TWInfoTable = {
dataShape: {
fieldDefinitions: {}
},
rows: []
};
switch (property.initializer.kind) {
case ts.SyntaxKind.ObjectLiteralExpression:
table.rows.push(this.extractObjectLiteral(property.initializer as ts.ObjectLiteralExpression));
break;
case ts.SyntaxKind.ArrayLiteralExpression:
const array = property.initializer as ts.ArrayLiteralExpression;
for (const element of array.elements) {
if (element.kind != ts.SyntaxKind.ObjectLiteralExpression) {
this.throwErrorForNode(array, 'Configuration rows must be object literals.');
}
table.rows.push(this.extractObjectLiteral(element as ts.ObjectLiteralExpression));
}
break;
default:
this.throwErrorForNode(property, 'Configuration properties must be array or object literals.');
}
// Extract the data shape from the first row
const row = table.rows[0];
for (const key of Object.keys(row)) {
table.dataShape.fieldDefinitions[key] = {
name: key,
description: '',
aspects: {},
baseType: TWBaseTypes[typeof row[key]],
ordinal: 0
}
}
this.configuration[name] = table;
}
}
/**
* Extracts the given object literal expression to an equivalent object literal.
* @param literal The literal to extract.
* @returns An object.
*/
private extractObjectLiteral(literal: ts.ObjectLiteralExpression): Record<string, unknown> {
const result: Record<string, unknown> = {};
for (const member of literal.properties) {
if (member.kind != ts.SyntaxKind.PropertyAssignment) {
this.throwErrorForNode(literal, 'Configuration fields must be property assignments');
}
if (!member.name || member.name.kind != ts.SyntaxKind.Identifier) this.throwErrorForNode(member, `Configuration field names cannot be computed.`);
const name = member.name.text;
switch (member.initializer.kind) {
case ts.SyntaxKind.TrueKeyword:
result[name] = true;
break;
case ts.SyntaxKind.FalseKeyword:
result[name] = false;
break;
case ts.SyntaxKind.StringLiteral:
result[name] = (member.initializer as ts.StringLiteral).text;
break;
case ts.SyntaxKind.NumericLiteral:
result[name] = parseFloat((member.initializer as ts.NumericLiteral).text);
break;
default:
this.throwErrorForNode(member, `Configuration field values can only be literal primitives`);
}
}
return result;
}
private XMLRepresentationOfInfotable(infotable: TWInfoTable, withOrdinals = false) {
return {
$: {} as Record<string, string>,
DataShape: [
{
FieldDefinitions: [
{
FieldDefinition: Object.values(infotable.dataShape.fieldDefinitions).map(f => {
const fieldDefinition: any = {
$: {
baseType: f.baseType,
description: f.description,
name: f.name
}
};
if (withOrdinals) {
fieldDefinition.$.ordinal = f.ordinal
}
return fieldDefinition;
})
}
]
}
],
Rows: [
{
Row: infotable.rows
}
]
};
}
/**
* Returns the XML entity representation of a thing that is used to initialize the project's
* debug information when the project is deployed.
* @param entityName The name to use for the entity.
* @param transformers The transformers from which to obtain debug information.
* @param projectName The name of the project to add to the entity.
*/
static projectDebugThingXML(entityName: string, transformers: TWThingTransformer[], projectName: string = ''): string {
// Filter the list to only include transformers with debug information
const debugTransformers = transformers.filter(t => t.filename && t.breakpoints.length);
const debugData: {[key: string]: Breakpoint[]} = {};
// Merge the list of breakpoints into a map organized per file
debugTransformers.forEach(t => {
debugData[t.filename!] = t.breakpoints;
});
// Return the entity
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Entities>
<Things>
<Thing name="${entityName}" projectName="${projectName}" tags="Debugger:DebugInfo" enabled="true" identifier="" published="false" thingTemplate="GenericThing" valueStream="">
<Owner name="Administrator" type="User"/>
<ThingShape>
<PropertyDefinitions>
<PropertyDefinition
aspect.cacheTime="0.0"
aspect.dataChangeThreshold="0.0"
aspect.dataChangeType="VALUE"
aspect.defaultValue=""
aspect.isLogged="false"
aspect.isPersistent="true"
baseType="STRING"
category=""
description="Contains debug information for the '${projectName}' project."
isLocalOnly="false"
name="debugInformation"
ordinal="0"></PropertyDefinition>
</PropertyDefinitions>
<ServiceDefinitions/>
<ServiceImplementations/>
<EventDefinitions/>
<Subscriptions>
<Subscription name="__globalBlock__0" description="Global code block generated by TypeScript." enabled="true" eventName="ThingStart" sourceType="Thing">
<ServiceImplementation description="" handlerName="Script" name="__globalBlock__0">
<ConfigurationTables>
<ConfigurationTable description="Script" isMultiRow="false" name="Script" ordinal="0">
<DataShape>
<FieldDefinitions>
<FieldDefinition baseType="STRING" description="code" name="code" ordinal="0"/>
</FieldDefinitions>
</DataShape>
<Rows>
<Row>
<code>
BMDebuggerRuntime.registerExtensionPackage(${JSON.stringify(entityName)});
</code>
</Row>
</Rows>
</ConfigurationTable>
</ConfigurationTables>
</ServiceImplementation>
</Subscription>
</Subscriptions>
</ThingShape>
<ThingProperties>
<debugInformation>
<Value>
<![CDATA[${JSON.stringify(debugData)}]]>
</Value>
<Timestamp>1970-01-01T02:00:00.000+02:00</Timestamp>
<Quality>UNKNOWN</Quality>
</debugInformation>
</ThingProperties>
<PropertyBindings/>
<RemotePropertyBindings/>
<RemoteServiceBindings/>
<RemoteEventBindings/>
</Thing>
</Things>
</Entities>`;
}
/**
* Returns the XML entity representation of the file processed by this transformer.
* @return An XML.
*/
toXML(): string {
const XML = {} as any;
if (this.entityKind == TWEntityKind.DataShape) return this.toDataShapeXML();
if (this.entityKind == TWEntityKind.UserList) return this.toUserListXML();
if (this.entityKind == TWEntityKind.Organization) return this.toOrganizationXML();
const collectionKind = this.entityKind + 's';
const entityKind = this.entityKind;
XML.Entities = {};
XML.Entities[collectionKind] = [];
XML.Entities[collectionKind][0] = {};
XML.Entities[collectionKind][0][entityKind] = [{$:{}}];
const entity = XML.Entities[collectionKind][0][entityKind][0];
entity.$.name = this.exportedName;
if (this.projectName) entity.$.projectName = this.projectName;
// Tags are yet unsupported
entity.$.tags = '';
if (this.editable) entity.$['aspect.isEditableExtensionObject'] = this.editable;
if (this.description) entity.$.description = this.description;
if (this.entityKind == TWEntityKind.Thing) {
entity.$.enabled = true;
entity.$.identifier = this.identifier || '';
entity.$.published = this.published || false;
}
if (this.entityKind != TWEntityKind.ThingShape) {
entity.$[this.entityKind == TWEntityKind.Thing ? 'thingTemplate' : 'baseThingTemplate'] = this.thingTemplateName || 'GenericThing';
entity.$.valueStream = this.valueStream || '';
}
entity.Owner = [{$: {name: 'Administrator', type: 'User'}}];
// This level of indirection is only applicable for non-thing shapes
if (this.entityKind != TWEntityKind.ThingShape) {
entity.ThingShape = [{}];
}
const shape = this.entityKind == TWEntityKind.ThingShape ? entity : entity.ThingShape[0];
// ********************************** PROPERTY DEFINITIONS **********************************
shape.PropertyDefinitions = [{}];
shape.PropertyDefinitions[0].PropertyDefinition = [];
const propertyDefinitions = shape.PropertyDefinitions[0].PropertyDefinition as any[];
entity.PropertyBindings = [{PropertyBinding: []}];
const propertyBindings = entity.PropertyBindings[0].PropertyBinding as any[];
entity.RemotePropertyBindings = [{RemotePropertyBinding: []}];
const remotePropertyBindings = entity.RemotePropertyBindings[0].RemotePropertyBinding as any[];
for (const property of this.properties) {
const propertyDefinition = {$:{}} as any;
for (const key in property) {
if (key == 'aspects' || key == 'remoteBinding' || key == 'localBinding') continue;
propertyDefinition.$[key] = property[key]
}
if (property.aspects) {
for (const key in property.aspects) {
propertyDefinition.$['aspect.' + key] = property.aspects[key];
}
}
propertyDefinitions.push(propertyDefinition);
if (property.remoteBinding) {
const remoteBinding = {$:{}} as any;
for (const key in property.remoteBinding) {
if (key == 'aspects') continue;
remoteBinding.$[key] = property.remoteBinding[key];
}
if (property.remoteBinding.aspects) for (const key in property.remoteBinding.aspects) {
remoteBinding.$['aspect.' + key] = property.remoteBinding.aspects[key];
}
remotePropertyBindings.push(remoteBinding);
}
if (property.localBinding) {
const localBinding = {$:{}} as any;
for (const key in property.localBinding) {
if (key == 'aspects') continue;
localBinding.$[key] = property.localBinding[key];
}
if (property.localBinding.aspects) for (const key in property.localBinding.aspects) {
localBinding.$['aspect.' + key] = property.localBinding.aspects[key];
}
propertyBindings.push(localBinding);
}
}
// ********************************** SERVICE DEFINITIONS **********************************
shape.ServiceDefinitions = [{ServiceDefinition: []}];
const serviceDefinitions = shape.ServiceDefinitions[0].ServiceDefinition as any[];
shape.ServiceImplementations = [{ServiceImplementation: []}];
const serviceImplementations = shape.ServiceImplementations[0].ServiceImplementation as any[];
entity.RemoteServiceBindings = [{RemoteServiceBinding: []}];
const remoteServiceBindings = entity.RemoteServiceBindings[0].RemoteServiceBinding as any[];
for (const service of this.services) {
// Overriden services only have an implementation
if (!service.isOverriden) {
// ********************************** SERVICE DETAILS **********************************
const serviceDefinition = {$:{}} as any;
for (const key in service) {
if (key == 'aspects' || key == 'remoteBinding' || key == 'code' || key == 'parameterDefinitions' || key == 'resultType' || key == 'isOverriden') continue;
serviceDefinition.$[key] = service[key];
}
if (service.aspects) {
for (const key in service.aspects) {
serviceDefinition.$['aspect.' + key] = service.aspects[key];
}
}
// ********************************** SERVICE RESULT **********************************
serviceDefinition.ResultType = [{$:{}}];
const resultType = serviceDefinition.ResultType[0];
for (const key in service.resultType) {
if (key == 'aspects') continue;
resultType.$[key] = service.resultType[key];
}
if (service.resultType.aspects) for (const key in service.resultType.aspects) {
resultType.$['aspect.' + key] = service.resultType.aspects[key];
}
// ********************************** SERVICE PARAMETERS **********************************
serviceDefinition.ParameterDefinitions = [{FieldDefinition: []}];
const parameterDefinitions = serviceDefinition.ParameterDefinitions[0].FieldDefinition as any[];
for (const parameter of service.parameterDefinitions) {
const parameterDefinition = {$:{}};
for (const key in parameter) {
if (key == 'aspects') continue;
parameterDefinition.$[key] = parameter[key];
}
if (parameter.aspects) for (const key in parameter.aspects) {
parameterDefinition.$['aspect.' + key] = parameter.aspects[key];
}
parameterDefinitions.push(parameterDefinition);
}
serviceDefinitions.push(serviceDefinition);
}
// ********************************** SERVICE IMPLEMENTATION **********************************
if (service.remoteBinding) {
const remoteBinding = {$:{}} as any;
for (const key in service.remoteBinding) {
if (key == 'aspects') continue;
remoteBinding.$[key] = service.remoteBinding[key];
}
// Service remote bindings don't have aspects
remoteServiceBindings.push(remoteBinding);
}
else {
// This JSON is just how an infotable appears after conversion from an XML format - copy-pasted from an export
const implementation = {
$: {
description: "",
handlerName: "Script",
name: service.name
},
ConfigurationTables: [
{
ConfigurationTable: [
{
$: {
description: "Script",
isMultiRow: "false",
name: "Script",
ordinal: "0"
},
DataShape: [
{
FieldDefinitions: [
{
FieldDefinition: [
{
$: {
baseType: "STRING",
description: "code",
name: "code",
ordinal: "0"
}
}
]
}
]
}
],
Rows: [
{
Row: [
{
code: [service.code]
}
]
}
]
}
]
}
]
};
serviceImplementations.push(implementation);
}
}
// ********************************** EVENT DEFINITIONS **********************************
shape.EventDefinitions = [{EventDefinition: []}];
const eventDefinitions = shape.EventDefinitions[0].EventDefinition as any[];
entity.RemoteEventBindings = [{RemoteEventBinding: []}];
const remoteEventBindings = entity.RemoteEventBindings[0].RemoteEventBinding as any[];
for (const event of this.events) {
const eventDefinition = {$:{}} as any;
for (const key in event) {
if (key == 'remoteBinding') continue;
eventDefinition.$[key] = event[key];
}
eventDefinitions.push(eventDefinition);
if (event.remoteBinding) {
const remoteBinding = {$:{}} as any;
for (const key in event.remoteBinding) {
if (key == 'aspects') continue;
remoteBinding.$[key] = event.remoteBinding[key];
}
remoteEventBindings.push(remoteBinding);
}
}
// ********************************** SUBSCRIPTIONS **********************************
shape.Subscriptions = [{Subscription: []}];
const subscriptions = shape.Subscriptions[0].Subscription;
for (const subscription of this.subscriptions) {
const subscriptionDefinition = {$:{}} as any;
for (const key in subscription) {
if (key == 'code') continue;
subscriptionDefinition.$[key] = subscription[key];
}
subscriptionDefinition.ServiceImplementation = [];
subscriptionDefinition.ServiceImplementation[0] = {
$: {
description: "",
handlerName: "Script",
name: subscription.name
},
ConfigurationTables: [
{
ConfigurationTable: [
{
$: {
description: "Script",
isMultiRow: "false",
name: "Script",
ordinal: "0"
},
DataShape: [
{
FieldDefinitions: [
{
FieldDefinition: [
{
$: {
baseType: "STRING",
description: "code",
name: "code",
ordinal: "0"
}
}
]
}
]
}
],
Rows: [
{
Row: [
{
code: [subscription.code]
}
]
}
]
}
]
}
]
};
subscriptions.push(subscriptionDefinition);
}
// ********************************** PERMISSIONS **********************************
if (this.runtimePermissions.runtime) {
entity.RunTimePermissions = [{Permissions: []}];
for (const resource in this.runtimePermissions.runtime) {
const permissionDefinition = {$: {resourceName: resource}};
for (const permission in this.runtimePermissions.runtime[resource]) {
const principals = this.runtimePermissions.runtime[resource][permission].map(p => ({$: {name: p.principal, type: p.type, isPermitted: p.isPermitted}}));
permissionDefinition[permission] = [{Principal: principals}];
}
entity.RunTimePermissions[0].Permissions.push(permissionDefinition);
}
}
if (this.runtimePermissions.runtimeInstance) {
entity.InstanceRunTimePermissions = [{Permissions: []}];
for (const resource in this.runtimePermissions.runtimeInstance) {
const permissionDefinition = {$: {resourceName: resource}};
for (const permission in this.runtimePermissions.runtimeInstance[resource]) {
const principals = this.runtimePermissions.runtimeInstance[resource][permission].map(p => ({$: {name: p.principal, type: p.type, isPermitted: p.isPermitted}}));
permissionDefinition[permission] = [{Principal: principals}];
}
entity.InstanceRunTimePermissions[0].Permissions.push(permissionDefinition);
}
}
// ********************************** VISIBILITY **********************************
if (this.visibilityPermissions.length) {
entity.VisibilityPermissions = [{Visibility: []}];
entity.VisibilityPermissions[0].Visibility[0] = {Principal: this.visibilityPermissions.map(p => ({$: p}))};
}
if (this.instanceVisibilityPermissions.length) {
entity.InstanceVisibilityPermissions = [{Visibility: []}];
entity.InstanceVisibilityPermissions[0].Visibility[0] = {Principal: this.instanceVisibilityPermissions.map(p => ({$: p}))};
}
// ********************************** GLOBAL CODE *************************************
for (let i = 0; i < this.globalBlocks.length; i++) {
const globalBlock = this.globalBlocks[i];
const subscriptionDefinition = {$:{
name: `__globalBlock__` + i,
description: 'Global code block generated by TypeScript.',
enabled: true,
eventName: 'ThingStart',
sourceType: TWSubscriptionSourceKind.Thing
}} as any;
subscriptionDefinition.ServiceImplementation = [];
subscriptionDefinition.ServiceImplementation[0] = {
$: {
description: "",
handlerName: "Script",
name: `__globalBlock__` + i
},
ConfigurationTables: [
{
ConfigurationTable: [
{
$: {
description: "Script",
isMultiRow: "false",
name: "Script",
ordinal: "0"
},
DataShape: [
{
FieldDefinitions: [
{
FieldDefinition: [
{
$: {
baseType: "STRING",
description: "code",
name: "code",
ordinal: "0"
}
}
]
}
]
}
],
Rows: [
{
Row: [
{
code: [globalBlock.compiledGlobalCode!]
}
]
}
]
}
]
}
]
};
subscriptions.push(subscriptionDefinition);
}
// ********************************** THING SHAPES *************************************
if (this.thingShapes.length) {
entity.ImplementedShapes = [{ImplementedShape: []}];
const implementedShapes = entity.ImplementedShapes[0].ImplementedShape;
for (const shape of this.thingShapes) {
implementedShapes.push({$:{name: shape, type: 'ThingShape'}});
}
}
// ********************************** CONFIGURATION TABLES *************************************
if (this.configurationTableDefinitions.length) {
entity.ConfigurationTableDefinitions = [{ConfigurationTableDefinition: []}];
const configurationTableDefinitions = entity.ConfigurationTableDefinitions[0].ConfigurationTableDefinition;
for (const table of this.configurationTableDefinitions) {
const configurationTable = {$:{}};
for (const key in table) {
configurationTable.$[key] = table[key];
}
configurationTableDefinitions.push(configurationTable);
}
}
// If a generic argument is specified for a data thing, set up a configuration table specifying it
if (this.entityKind == TWEntityKind.Thing && TWDataThings.includes(this.thingTemplateName!)) {
entity.ConfigurationTables = [
{
ConfigurationTable: [
{
$: {
description: "Data Shape Configuration",
isMultiRow: "false",
name: "Settings",
ordinal: "0"
},
DataShape: [
{
FieldDefinitions: [
{
FieldDefinition: [
{
$: {
'aspect.friendlyName': 'Data Shape',
baseType: "DATASHAPENAME",
description: "Data shape",
name: "dataShape",
ordinal: "0"
}
}
]
}
]
}
],
Rows: [
{
Row: [
{
dataShape: this.genericArgument
}
]
}
]
}
]
}
];
}
// If this is a debug build and the debug tables have been initialized, add the appropriate rows
if (this._debugConfigurationInitialized && USE_DEBUG_CONFIGURATION_TABLE) {
this.configuration = this.configuration || {};
this.configuration._BMDebuggerBreakpointLocations = {
dataShape: {
fieldDefinitions: {
line: {name: 'line', baseType: 'NUMBER', aspects: {}, description: '', ordinal: 0},
column: {name: 'column', baseType: 'NUMBER', aspects: {}, description: '', ordinal: 1},
endLine: {name: 'endLine', baseType: 'NUMBER', aspects: {}, description: '', ordinal: 2},
endColumn: {name: 'endColumn', baseType: 'NUMBER', aspects: {}, description: '', ordinal: 3},
locationID: {name: 'locationID', baseType: 'STRING', aspects: {}, description: '', ordinal: 4},
}
},
rows: this.breakpoints as any
};
this.configuration._BMDebugMetadata = {
dataShape: {
fieldDefinitions: {
fileName: {name: 'fileName', baseType: 'STRING', aspects: {}, description: '', ordinal: 0},
}
},
rows: [{fileName: this.filename}]
}
}
// If any configuration is specified, set up a configuration table for it
if (this.configuration) {
entity.ConfigurationTables = entity.ConfigurationTables || [
{
ConfigurationTable: []
}
];
const configurationTable = entity.ConfigurationTables[0].ConfigurationTable as any[];
for (const tableName of Object.keys(this.configuration)) {
const table = this.XMLRepresentationOfInfotable(this.configuration[tableName]);
table.$.name = tableName;
table.$.description = '';
table.$.isMultiRow = String(this.configuration[tableName].rows.length > 1);
configurationTable.push(table);
}
}
return (new Builder()).buildObject(XML);
}
/**
* Returns the XML data shape entity representation of the file processed by this transformer.
* @return An XML.
*/
private toDataShapeXML(): string {
const XML = {} as any;
const collectionKind = this.entityKind + 's';
const entityKind = this.entityKind;
XML.Entities = {};
XML.Entities[collectionKind] = [];
XML.Entities[collectionKind][0] = {};
XML.Entities[collectionKind][0][entityKind] = [{$:{baseDataShape: this.thingTemplateName || ''}}];
const entity = XML.Entities[collectionKind][0][entityKind][0];
entity.$.name = this.exportedName;
if (this.projectName) entity.$.projectName = this.projectName;
if (this.editable) entity.$['aspect.isEditableExtensionObject'] = this.editable;
// Tags are yet unsupported
entity.$.tags = '';
if (this.description) entity.$.description = this.description;
entity.FieldDefinitions = [{FieldDefinition: []}];
const fieldDefinitions = entity.FieldDefinitions[0].FieldDefinition as any[];
let ordinal = 0;
for (const field of this.fields) {
const fieldDefinition = {$:{}} as any;
if (this.autoGenerateDataShapeOrdinals && !('ordinal' in <any>field)) {
field.ordinal = ordinal;
}
ordinal++;
for (const key in field) {
if (key == 'aspects') continue;
fieldDefinition.$[key] = field[key]
}
if (field.aspects) {
for (const key in field.aspects) {
fieldDefinition.$['aspect.' + key] = field.aspects[key];
}
}
fieldDefinitions.push(fieldDefinition);
}
if (this.runtimePermissions.runtime) {
entity.RunTimePermissions = [{Permissions: []}];
for (const resource in this.runtimePermissions.runtime) {
const permissionDefinition = {$: {resourceName: resource}};
for (const permission in this.runtimePermissions.runtime[resource]) {
const principals = this.runtimePermissions.runtime[resource][permission].map(p => ({$: {name: p.principal, type: p.type, isPermitted: p.isPermitted}}));
permissionDefinition[permission] = [{Principal: principals}];
}
entity.RunTimePermissions[0].Permissions.push(permissionDefinition);
}
}
if (this.visibilityPermissions.length) {
entity.VisibilityPermissions = [{Visibility: []}];
entity.VisibilityPermissions[0].Visibility[0] = {Principal: this.visibilityPermissions.map(p => ({$: p}))};
}
return (new Builder()).buildObject(XML);
}
/**
* Returns an array of XML entities containing the users and groups in the file processed by this transformer.
*/
private toUserListXML(): string {
const XML = {} as any;
XML.Entities = {};
XML.Entities.Users = [{}];
XML.Entities.Users[0].User = [];
XML.Entities.Groups = [{}];
XML.Entities.Groups[0].Group = [];
for (const user in this.users) {
const collectionKind = 'Users';
const entityKind = 'User';
const entity: any = {$: {}};
entity.$.name = user;
entity.$.locked = 'false';
entity.$.enabled = 'true';
if (this.projectName) entity.$.projectName = this.projectName;
if (this.editable) entity.$['aspect.isEditableExtensionObject'] = this.editable;
// Tags are yet unsupported
entity.$.tags = '';
if (this.users[user].description) entity.$.description = this.users[user].description;
// Get the user extensions, if specified and convert
// them into infotable rows
const extensions = this.users[user].extensions;
const extensionsRows: unknown[] = [];
const updateTime = (new Date).toISOString();
for (const key in extensions) {
extensionsRows.push({
lastUpdateTime: updateTime,
name: key,
value: String(extensions[key])
});
}
entity.ConfigurationTables = [
{
ConfigurationTable: [
{
$: {
description: "UserExtensions",
isMultiRow: "true",
name: "UserExtensions",
ordinal: "1",
dataShapeName: ''
},
DataShape: [
{
FieldDefinitions: [
{
FieldDefinition: [
{
$: {
baseType: "DATETIME",
description: "Last update time",
name: "lastUpdateTime",
ordinal: "3"
}
},
{
$: {
'aspect.isPrimaryKey': 'true',
baseType: "STRING",
description: "Name",
name: "name",
ordinal: "1"
}
},
{
$: {
baseType: "STRING",
description: "Value",
name: "value",
ordinal: "2"
}
}
]
}
]
}
],
Rows: [
{
Row: extensionsRows
}
]
}
]
}
];
if (this.runtimePermissions.runtime) {
entity.RunTimePermissions = [{Permissions: []}];
for (const resource in this.runtimePermissions.runtime) {
// For user lists, the resource name represents the entity to which the permissions apply
if (resource != user) continue;
const permissionDefinition = {$: {resourceName: '*'}};
for (const permission in this.runtimePermissions.runtime[resource]) {
const principals = this.runtimePermissions.runtime[resource][permission].map(p => ({$: {name: p.principal, type: p.type, isPermitted: p.isPermitted}}));
permissionDefinition[permission] = [{Principal: principals}];
}
entity.RunTimePermissions[0].Permissions.push(permissionDefinition);
}
}
if (this.visibilityPermissions.length) {
entity.VisibilityPermissions = [{Visibility: []}];
entity.VisibilityPermissions[0].Visibility[0] = {Principal: this.visibilityPermissions.map(p => ({$: p}))};
}
XML.Entities[collectionKind][0][entityKind].push(entity);
}
for (const group in this.userGroups) {
const collectionKind = 'Groups';
const entityKind = 'Group';
const entity: any = {$:{}};
entity.$.name = group;
if (this.projectName) entity.$.projectName = this.projectName;
if (this.editable) entity.$['aspect.isEditableExtensionObject'] = this.editable;
// Tags are yet unsupported
entity.$.tags = '';
if (this.userGroups[group].description) entity.$.description = this.userGroups[group].description;
// Create the memeber list
const members: unknown[] = [];
for (const member of this.userGroups[group].members) {
// Because of the way collections are accessed, the group types will have an extra 's' at the end which must be removed
members.push({$: {name: member.name, type: member.type.substring(0, member.type.length - 1)}});
}
entity.Members = [{}];
entity.Members[0].Members = [{}];
entity.Members[0].Members[0].Member = members;
if (this.runtimePermissions.runtime) {
entity.RunTimePermissions = [{Permissions: []}];
for (const resource in this.runtimePermissions.runtime) {
// For user lists, the resource name represents the entity to which the permissions apply
if (resource != group) continue;
const permissionDefinition = {$: {resourceName: '*'}};
for (const permission in this.runtimePermissions.runtime[resource]) {
const principals = this.runtimePermissions.runtime[resource][permission].map(p => ({$: {name: p.principal, type: p.type, isPermitted: p.isPermitted}}));
permissionDefinition[permission] = [{Principal: principals}];
}
entity.RunTimePermissions[0].Permissions.push(permissionDefinition);
}
}
if (this.visibilityPermissions.length) {
entity.VisibilityPermissions = [{Visibility: []}];
entity.VisibilityPermissions[0].Visibility[0] = {Principal: this.visibilityPermissions.map(p => ({$: p}))};
}
XML.Entities[collectionKind][0][entityKind].push(entity);
}
return (new Builder).buildObject(XML);
}
/**
* Returns the XML organization entity representation of the file processed by this transformer.
* @return An XML.
*/
private toOrganizationXML(): string {
const XML = {} as any;
const collectionKind = this.entityKind + 's';
const entityKind = this.entityKind;
XML.Entities = {};
XML.Entities[collectionKind] = [];
XML.Entities[collectionKind][0] = {};
XML.Entities[collectionKind][0][entityKind] = [{$:{}}];
const entity = XML.Entities[collectionKind][0][entityKind][0];
entity.$.name = this.exportedName;
if (this.projectName) entity.$.projectName = this.projectName;
if (this.editable) entity.$['aspect.isEditableExtensionObject'] = this.editable;
// Tags are yet unsupported
entity.$.tags = '';
if (this.description) entity.$.description = this.description;
entity.Connections = [{Connection: this.orgConnections.map(c => ({$: c}))}];
entity.OrganizationalUnits = [{OrganizationalUnit: []}];
for (const unit of this.orgUnits) {
const orgUnit = {$: {name: unit.name}, Members: [] as unknown[]} as any;
if (unit.description) orgUnit.$.description = unit.description;
orgUnit.Members = [{ Members: [{ Member: unit.members?.map(m => ({$: m})) || [] }] }];
entity.OrganizationalUnits[0].OrganizationalUnit.push(orgUnit);
}
if (this.runtimePermissions.runtime) {
entity.RunTimePermissions = [{Permissions: []}];
for (const resource in this.runtimePermissions.runtime) {
const permissionDefinition = {$: {resourceName: resource}};
for (const permission in this.runtimePermissions.runtime[resource]) {
const principals = this.runtimePermissions.runtime[resource][permission].map(p => ({$: {name: p.principal, type: p.type, isPermitted: p.isPermitted}}));
permissionDefinition[permission] = [{Principal: principals}];
}
entity.RunTimePermissions[0].Permissions.push(permissionDefinition);
}
}
if (this.visibilityPermissions.length) {
entity.VisibilityPermissions = [{Visibility: []}];
entity.VisibilityPermissions[0].Visibility[0] = {Principal: this.visibilityPermissions.map(p => ({$: p}))};
}
return (new Builder()).buildObject(XML);
}
/**
* @deprecated - Use `toDeclaration` instead.
*
* Returns the Thingworx collection declaration of the entity within the file processed by this transformer.
* @return The typescript declaration.
*/
toDefinition(): string {
return this.toDeclaration();
}
/**
* Returns the Thingworx collection declaration of the entity within the file processed by this transformer.
* @return The typescript declaration.
*/
toDeclaration(): string {
if (this.entityKind && this.className) {
if (this.entityKind == TWEntityKind.Thing) {
return `declare interface ${this.entityKind}s { ${JSON.stringify(this.exportedName)}: ${this.className} }\n\n`;
}
else if (this.entityKind == TWEntityKind.UserList) {
const users = `declare interface Users { ${Object.values(this.users).map(u => `${u.name}: UserEntity;`).join(' ')} }\n\n`;
const groups = `declare interface Groups { ${Object.values(this.userGroups).map(u => `${u.name}: GroupEntity;`).join(' ')} }\n\n`;
return users + groups;
}
else if (this.entityKind == TWEntityKind.Organization) {
return `declare interface ${this.entityKind}s { ${JSON.stringify(this.exportedName)}: ${this.entityKind}Entity<${this.orgUnits.map(u => JSON.stringify(u.name)).join(' | ') || 'string'}>}`;
}
else {
return `declare interface ${this.entityKind}s { ${JSON.stringify(this.exportedName)}: ${this.entityKind}Entity<${this.className}>}`;
}
}
else {
return '';
}
}
/**
* Writes the XML entity representation of the file processed by this transformer to an appropriate file
* and path based on the entity kind and its name. The path will use the given path as a root.
* @param path Defaults the `root` property. The root path.
*/
write(path: string = this.root): void {
if (!fs.existsSync(`${path}/build`)) fs.mkdirSync(`${path}/build`);
if (!fs.existsSync(`${path}/build/Entities`)) fs.mkdirSync(`${path}/build/Entities`);
let entityKind: string = this.entityKind;
// User lists are to be saved under a "Users" subfolder.
if (this.entityKind == TWEntityKind.UserList) {
entityKind = 'User';
}
if (!fs.existsSync(`${path}/build/Entities/${entityKind}s`)) fs.mkdirSync(`${path}/build/Entities/${entityKind}s`);
fs.writeFileSync(`${path}/build/Entities/${entityKind}s/${this.exportedName}.xml`, this.toXML());
}
}
/**
* An interface containing the configuration options that may be used to initialize a transformer.
*/
interface TWConfig {
/**
* The name of the project to use for the entitiy.
*/
projectName: string;
/**
* Whether experimental support for global code is enabled.
*/
experimentalGlobals: boolean;
/**
* When enabled, ordinal values will be generated for data shape fields, in the order in which they
* appear, starting from 0.
*
* This will not override ordinal values that are explicitly specified via decorators.
*/
autoGenerateDataShapeOrdinals: boolean;
/**
* When enabled, the transformer will generate a debug build used for debugging.
*/
debug?: boolean;
/**
* An object holding transformer instances.
*/
store: {[key: string]: TWThingTransformer};
}
export function TWThingTransformerFactory(program: ts.Program, root: string, after: boolean = false, watch: boolean = false, project?: string | TWConfig) {
return function TWThingTransformerFunction(context: ts.TransformationContext) {
const transformer = new TWThingTransformer(program, context, root, after, watch);
if (project) {
if (typeof project == 'string') {
transformer.projectName = project;
}
else {
transformer.projectName = project.projectName;
transformer.experimentalGlobals = project.experimentalGlobals;
transformer.autoGenerateDataShapeOrdinals = project.autoGenerateDataShapeOrdinals;
transformer.store = project.store;
transformer.debug = project.debug;
}
}
return (node: ts.Node) => ts.visitNode(node, node => transformer.visit(node));
}
}
|
BogdanMihaiciuc/ThingTransformer
|
src/transformer/DebugTypes.ts
|
/**
* Describes a breakpoint locationr.
*/
export interface Breakpoint {
/**
* Start line of breakpoint location.
*/
line: number;
/**
* Optional start column of breakpoint location.
*/
column?: number;
/**
* Optional end line of breakpoint location if the location covers a range.
*/
endLine?: number;
/**
* Optional end column of breakpoint location if the location covers a range.
*/
endColumn?: number;
/**
* A unique ID that identifies this breakpoint's location.
*/
locationID: string;
}
|
BogdanMihaiciuc/ThingTransformer
|
src/transformer/TWCoreTypes.ts
|
export interface TWInfoTable {
dataShape: {
fieldDefinitions: Record<string, TWFieldBase>;
};
rows: Record<string, unknown>[];
}
export interface TWFieldBase<T = any> {
name: string;
baseType: string;
description: string;
aspects: TWFieldAspects<T>;
ordinal: number;
}
export interface TWFieldAspects<T> {
thingShape?: string;
thingTemplate?: string;
dataShape?: string;
defaultValue?: T;
}
export interface TWDataShapeField<T = any> extends TWFieldBase<T> {
aspects: TWDataShapeFieldAspects<T>;
}
export interface TWDataShapeFieldAspects<T> extends TWFieldAspects<T> {
isPrimaryKey?: boolean;
}
export interface TWPropertyDefinition<T = any> extends TWFieldBase<T> {
aspects: TWPropertyAspects<T>;
category: string;
/** @deprecated */ isLocalOnly: false;
remoteBinding?: TWPropertyRemoteBinding;
localBinding?: TWPropertyBinding;
}
export interface TWPropertyAspects<T> extends TWFieldAspects<T> {
isPersistent?: boolean;
isLogged?: boolean;
isReadOnly?: boolean;
isRemote?: boolean;
dataChangeType: TWPropertyDataChangeKind;
dataChangeThreshold?: T;
// NOTE: This appears to control the cache method of remote properties as such:
// 0 (default) = read from server cache
// -1 = fetched from remote every read
// >0 = cached for x seconds
cacheTime: number;
minimumValue?: number;
maximumValue?: number;
units?: string;
}
export const enum TWPropertyDataChangeKind {
Value = 'VALUE',
Always = 'ALWAYS',
Never = 'NEVER',
On = 'ON',
Off = 'OFF'
}
export interface TWPropertyBinding {
aspects: TWPropertyBindingAspects;
name: string;
sourceName: string;
sourceThingName: string;
}
export interface TWPropertyBindingAspects {
startType: "null";
tagAddresss: "";
}
export interface TWPropertyRemoteBinding {
name: string;
sourceName: string;
pushType: TWPropertyRemotePushKind;
pushThreshold: any;
foldType: TWPropertyRemoteFoldKind;
timeout: number;
aspects: TWPropertyRemoteBindingAspects;
}
export interface TWPropertyRemoteBindingAspects {
// This appears in exports, but weirdly thingworx complains about it when specified
source?: "";
startType: TWPropertyRemoteStartKind;
// This appears in exports, but weirdly thingworx complains about it when specified
tagAddress?: string;
}
export const enum TWPropertyRemotePushKind {
Value = 'VALUE',
Always = 'ALWAYS',
Never = 'NEVER'
}
export const enum TWPropertyRemoteStartKind {
DefaultValue = 'useDefaultValue',
EdgeValue = 'useEdgeValue'
}
export const enum TWPropertyRemoteFoldKind {
None = 'NONE',
Fold = 'FOLD'
}
export interface TWServiceDefinition {
name: string;
parameterDefinitions: TWServiceParameter[];
resultType: TWFieldBase;
aspects: TWServiceAspects;
category: string;
description: string;
isAllowOverride: boolean;
isLocalOnly: boolean;
isOpen: boolean;
isPrivate: boolean;
code: string;
remoteBinding?: TWServiceRemoteBinding;
isOverriden?: boolean;
}
export interface TWServiceAspects {
isAsync?: boolean;
}
export interface TWServiceParameter<T = any> extends TWFieldBase<T> {
aspects: TWServiceParameterAspects<T>;
}
export interface TWServiceParameterAspects<T = any> extends TWFieldAspects<T> {
isRequired?: boolean;
}
export interface TWServiceRemoteBinding {
enableQueue: boolean;
name: string;
sourceName: string;
timeout: number;
}
export interface TWEventDefinition {
name: string;
description: string;
category: string;
dataShape: string;
remoteBinding?: TWEventRemoteBinding;
}
export interface TWEventRemoteBinding {
name: string;
sourceName: string;
}
export interface TWSubscriptionDefinition {
name: string;
description: string;
enabled: boolean;
eventName: string;
source: string;
sourceType: TWSubscriptionSourceKind;
sourceProperty: string;
code: string;
}
export const enum TWSubscriptionSourceKind {
Thing = 'Thing',
ThingTemplate = 'ThingTemplate',
ThingShape = 'ThingShape'
}
export interface TWConfigurationTable {
category: string;
dataShapeName: string;
description: string;
isHidden: boolean;
isMultiRow: boolean;
name: string;
source?: string;
}
export const TWDataThings = ['Stream', 'RemoteStream', 'DataTable', 'RemoteDataTable'];
export const TWBaseTypes = {
NOTHING: "NOTHING",
void: 'NOTHING',
nothing: 'NOTHING',
STRING: "STRING",
string: 'STRING',
NUMBER: "NUMBER",
number: 'NUMBER',
BOOLEAN: "BOOLEAN",
boolean: 'BOOLEAN',
DATETIME: "DATETIME",
Date: 'DATETIME',
datetime: 'DATETIME',
TIMESPAN: "TIMESPAN",
timespan: 'TIMESPAN',
INFOTABLE: "INFOTABLE",
infotable: 'INFOTABLE',
InfoTableReference: 'INFOTABLE',
InfoTable: 'INFOTABLE',
LOCATION: "LOCATION",
location: 'LOCATION',
XML: "XML",
xml: 'XML',
Object: "JSON",
JSON: "JSON",
TWJSON: "JSON",
json: 'JSON',
QUERY: "QUERY",
query: 'QUERY',
IMAGE: "IMAGE",
image: 'IMAGE',
HYPERLINK: "HYPERLINK",
hyperlink: 'HYPERLINK',
IMAGELINK: "IMAGELINK",
imagelink: 'IMAGELINK',
PASSWORD: "PASSWORD",
password: 'PASSWORD',
HTML: "HTML",
html: 'HTML',
TEXT: "TEXT",
text: 'TEXT',
TAGS: "TAGS",
tags: 'TAGS',
SCHEDULE: "SCHEDULE",
schedule: 'SCHEDULE',
VARIANT: "VARIANT",
variant: 'variant',
GUID: "GUID",
guid: 'GUILD',
BLOB: "BLOB",
blob: 'BLOB',
INTEGER: "INTEGER",
integer: 'INTEGER',
LONG: "LONG",
long: 'LONG',
PROPERTYNAME: "PROPERTYNAME",
SERVICENAME: "SERVICENAME",
EVENTNAME: "EVENTNAME",
THINGNAME: "THINGNAME",
THINGSHAPENAME: "THINGSHAPENAME",
THINGTEMPLATENAME: "THINGTEMPLATENAME",
DATASHAPENAME: "DATASHAPENAME",
MASHUPNAME: "MASHUPNAME",
MENUNAME: "MENUNAME",
BASETYPENAME: "BASETYPENAME",
USERNAME: "USERNAME",
GROUPNAME: "GROUPNAME",
CATEGORYNAME: "CATEGORYNAME",
STATEDEFINITIONNAME: "STATEDEFINITIONNAME",
STYLEDEFINITIONNAME: "STYLEDEFINITIONNAME",
MODELTAGVOCABULARYNAME: "MODELTAGVOCABULARYNAME",
DATATAGVOCABULARYNAME: "DATATAGVOCABULARYNAME",
NETWORKNAME: "NETWORKNAME",
MEDIAENTITYNAME: "MEDIAENTITYNAME",
APPLICATIONKEYNAME: "APPLICATIONKEYNAME",
LOCALIZATIONTABLENAME: "LOCALIZATIONTABLENAME",
ORGANIZATIONNAME: "ORGANIZATIONNAME",
DASHBOARDNAME: "DASHBOARDNAME",
PERSISTENCEPROVIDERPACKAGENAME: "PERSISTENCEPROVIDERPACKAGENAME",
PERSISTENCEPROVIDERNAME: "PERSISTENCEPROVIDERNAME",
PROJECTNAME: "PROJECTNAME",
propertyName: "PROPERTYNAME",
serviceName: "SERVICENAME",
eventName: "EVENTNAME",
thingName: "THINGNAME",
thingShapeName: "THINGSHAPENAME",
thingTemplateName: "THINGTEMPLATENAME",
dataShapeName: "DATASHAPENAME",
mashupName: "MASHUPNAME",
menuName: "MENUNAME",
baseTypeName: "BASETYPENAME",
userName: "USERNAME",
groupName: "GROUPNAME",
categoryName: "CATEGORYNAME",
stateDefinitionName: "STATEDEFINITIONNAME",
styleDefinitionName: "STYLEDEFINITIONNAME",
modelTagVocabularyName: "MODELTAGVOCABULARYNAME",
dataTagVocabularyName: "DATATAGVOCABULARYNAME",
networkName: "NETWORKNAME",
mediaEntityName: "MEDIAENTITYNAME",
applicationKeyName: "APPLICATIONKEYNAME",
localizationTableName: "LOCALIZATIONTABLENAME",
organizationName: "ORGANIZATIONNAME",
dashboardName: "DASHBOARDNAME",
presistenceProviderPackageName: "PERSISTENCEPROVIDERPACKAGENAME",
persistenceProviderName: "PERSISTENCEPROVIDERNAME",
projectName: "PROJECTNAME",
VEC2: "VEC2",
VEC3: "VEC3",
VEC4: "VEC4",
THINGCODE: "THINGCODE",
thingcode: 'THINGCODE'
};
export const enum TWEntityKind {
Thing = "Thing",
ThingTemplate = "ThingTemplate",
ThingShape = "ThingShape",
DataShape = "DataShape",
UserList = "UserList",
Organization = "Organization"
}
export interface TWEntityDefinition {
name: string;
description: string;
documentationContent: string;
tags: any; // TBD
project: string;
propertyDefinitions: TWPropertyDefinition[];
serviceDefinitions: TWServiceDefinition[];
eventDefinitions: TWEventDefinition[];
subscriptionDefinitions: TWSubscriptionDefinition[];
aspects?: TWEntityDefinitionAspects;
}
export interface TWEntityDefinitionAspects {
isEditableExtensionObject?: boolean;
}
export interface TWThingTemplate extends TWEntityDefinition {
valueStream: string;
implementedShapes: string[];
thingTemplate: string;
}
export interface TWThing extends TWThingTemplate {
published: boolean;
enabled: boolean;
identifier: string;
}
export interface TWPrincipal {
name: string;
type: string;
}
export interface TWPermission {
isPermitted: boolean;
principal: string;
type: string;
}
export interface TWRuntimePermissionDeclaration {
PropertyRead: TWPermission[],
PropertyWrite: TWPermission[],
ServiceInvoke: TWPermission[],
EventInvoke: TWPermission[],
EventSubscribe: TWPermission[],
}
export interface TWRuntimePermissionsList {
// These are indexed with the resource name
[key: string]: TWRuntimePermissionDeclaration
}
export interface TWExtractedPermissionLists {
runtime?: TWRuntimePermissionsList,
runtimeInstance?: TWRuntimePermissionsList
}
export interface TWMemberBase {
name: string;
type: string;
}
export interface TWVisibility extends TWMemberBase {
isPermitted: boolean;
}
export interface TWPrincipalBase {
name: string;
description?: string;
}
export interface TWUser extends TWPrincipalBase {
extensions: { [key: string]: any };
}
export interface TWUserGroup extends TWPrincipalBase {
members: TWPrincipal[];
}
export interface TWConnection {
from: string;
to: string;
}
export interface TWOrganizationalUnit {
description?: string;
name: string;
members: TWMemberBase[];
}
|
skimah/skimah
|
packages/ds-json/src/index.ts
|
<filename>packages/ds-json/src/index.ts
export { default } from "./json";
export { Config } from "./json";
|
skimah/skimah
|
packages/ds-json/test/json.test.ts
|
<reponame>skimah/skimah
import { generate, SkimahConfig } from "@skimah/api";
import { graphql } from "graphql";
import Records from "../src/json";
const typeDefs = `
type Customer @datasource(name: "customers") {
id: ID @named(as: "CustomerId")
firstName: String @named(as: "FirstName")
lastName: String @named(as: "LastName")
email: String @named(as: "Email")
supportRep: Employee! @relation @named(as: "SupportRepId")
}
type Employee @datasource(name: "employees") {
id: ID @named(as: "EmployeeId")
firstName: String @named(as: "FirstName")
lastName: String @named(as: "LastName")
title: String @named(as: "Title")
email: String @named(as: "Email")
supporting: [Customer] @relation
}
`;
describe("JSON Datasource", () => {
let schema;
beforeAll(async () => {
const customers = new Records({
filepath: "fixtures/Customer.json"
});
const employees = new Records({
filepath: "fixtures/Employee.json"
});
const sources = {
customers,
employees
};
const config: SkimahConfig = {
typeDefs,
sources
};
const skimahResult = await generate(config);
schema = skimahResult.schema;
});
describe("Selection", () => {
test("Skip and Limit", async () => {
const query = `
query {
findCustomers(limit: 2) {
firstName
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"findCustomers": Array [
Object {
"firstName": "Luís",
},
Object {
"firstName": "Leonie",
},
],
}
`);
});
test("One-to-One Relationships", async () => {
const query = `
query {
findCustomers(limit: 2) {
firstName
supportRep {
id
firstName
email
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"findCustomers": Array [
Object {
"firstName": "Luís",
"supportRep": Object {
"email": "<EMAIL>",
"firstName": "Jane",
"id": "3",
},
},
Object {
"firstName": "Leonie",
"supportRep": Object {
"email": "<EMAIL>",
"firstName": "Steve",
"id": "5",
},
},
],
}
`);
});
test("One-to-Many Relationships", async () => {
const query = `
query {
findEmployees(limit: 2, skip: 2) {
id
firstName
email
supporting(limit: 2) {
firstName
email
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"findEmployees": Array [
Object {
"email": "<EMAIL>",
"firstName": "Jane",
"id": "3",
"supporting": Array [
Object {
"email": "<EMAIL>",
"firstName": "Luís",
},
Object {
"email": "<EMAIL>",
"firstName": "François",
},
],
},
Object {
"email": "<EMAIL>",
"firstName": "Margaret",
"id": "4",
"supporting": Array [
Object {
"email": "<EMAIL>",
"firstName": "Bjørn",
},
Object {
"email": "<EMAIL>",
"firstName": "František",
},
],
},
],
}
`);
});
test("Criteria", async () => {
const query = `
query {
findCustomers(where: { supportRep: { eq: "3" }}, limit: 2) {
id
firstName
email
supportRep {
id
email
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"findCustomers": Array [
Object {
"email": "<EMAIL>",
"firstName": "Luís",
"id": "1",
"supportRep": Object {
"email": "<EMAIL>",
"id": "3",
},
},
Object {
"email": "<EMAIL>",
"firstName": "François",
"id": "3",
"supportRep": Object {
"email": "<EMAIL>",
"id": "3",
},
},
],
}
`);
});
test("Sort - ASC", async () => {
const query = `
query {
findCustomers(orderBy: { firstName: asc }, limit: 5) {
firstName
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"findCustomers": Array [
Object {
"firstName": "Aaron",
},
Object {
"firstName": "Alexandre",
},
Object {
"firstName": "Astrid",
},
Object {
"firstName": "Bjørn",
},
Object {
"firstName": "Camille",
},
],
}
`);
});
test("Sort - DESC", async () => {
const query = `
query {
findCustomers(orderBy: { firstName: desc }, limit: 5) {
firstName
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"findCustomers": Array [
Object {
"firstName": "Wyatt",
},
Object {
"firstName": "Victor",
},
Object {
"firstName": "Tim",
},
Object {
"firstName": "Terhi",
},
Object {
"firstName": "Steve",
},
],
}
`);
});
});
describe("Mutations", () => {
it("Insert", async () => {
const query = `
mutation {
createCustomers(data: [
{ id: 1112, firstName: "James", lastName: "Bond", supportRep: "3", email:"<EMAIL>" },
{ id: 1113, firstName: "Agent", lastName: "007", supportRep: "3", email:"<EMAIL>" }
]) {
affected
customers {
firstName
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"createCustomers": Object {
"affected": Array [
"1112",
"1113",
],
"customers": Array [
Object {
"firstName": "James",
},
Object {
"firstName": "Agent",
},
],
},
}
`);
});
it("Update", async () => {
const query = `
mutation {
updateCustomers(
where: { supportRep: { eq: 3 } },
changes: { supportRep: 5 } ) {
affected
customers {
firstName
supportRep {
id
}
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"updateCustomers": Object {
"affected": Array [
"1",
"3",
"12",
"15",
"18",
"19",
"24",
"29",
"30",
"33",
"37",
"38",
"42",
"43",
"44",
"45",
"46",
"52",
"53",
"58",
"59",
"1112",
"1113",
],
"customers": Array [
Object {
"firstName": "Luís",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "François",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Roberto",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Jennifer",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Michelle",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Tim",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Frank",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Robert",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Edward",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Ellie",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Fynn",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Niklas",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Wyatt",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Isabelle",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Terhi",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Ladislav",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Hugh",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Emma",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Phil",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Manoj",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Puja",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "James",
"supportRep": Object {
"id": "5",
},
},
Object {
"firstName": "Agent",
"supportRep": Object {
"id": "5",
},
},
],
},
}
`);
});
it("Delete", async () => {
const query = `
mutation {
deleteCustomers( where: { supportRep: { eq: 4 } }) {
affected
customers {
firstName
supportRep {
email
}
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"deleteCustomers": Object {
"affected": Array [
"4",
"5",
"8",
"9",
"10",
"13",
"16",
"20",
"22",
"23",
"26",
"27",
"32",
"34",
"35",
"39",
"40",
"49",
"55",
"56",
],
"customers": Array [
Object {
"firstName": "Bjørn",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "František",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Daan",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Kara",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Eduardo",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Fernanda",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Frank",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Dan",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Heather",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "John",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Richard",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Patrick",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Aaron",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "João",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Madalena",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Camille",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Dominique",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Stanisław",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Mark",
"supportRep": Object {
"email": "<EMAIL>",
},
},
Object {
"firstName": "Diego",
"supportRep": Object {
"email": "<EMAIL>",
},
},
],
},
}
`);
});
});
});
|
skimah/skimah
|
packages/api/test/datasource.test.ts
|
<reponame>skimah/skimah
import { Datasource } from "../src/types";
import generate from "../src/generate";
describe("Schema Datasource", () => {
const typeDefs = `
type SpecialUser @datasource(name: "users") {
userid: Int @unique
}
type Profile @datasource(name: "profiles") {
id: ID @unique
}
type Post @datasource(name: "posts") {
id: ID @unique
}
type NoneInit @datasource(name: "none") {
id: ID @unique
}
`;
const noop: Datasource = {
select: jest.fn(),
delete: jest.fn(),
create: jest.fn(),
update: jest.fn()
};
const users = Object.assign({}, noop, { initialize: jest.fn() });
const profiles = Object.assign({}, noop, { initialize: jest.fn() });
const posts = Object.assign({}, noop, { initialize: jest.fn() });
const none = Object.assign({}, noop);
test("initialize sources", async () => {
await generate({
typeDefs,
sources: {
users,
profiles,
posts,
none
}
});
expect(users.initialize).toHaveBeenCalledTimes(1);
expect(users.initialize.mock.calls[0][0][0].name).toMatchInlineSnapshot(
`"SpecialUser"`
);
expect(profiles.initialize).toHaveBeenCalledTimes(1);
expect(profiles.initialize.mock.calls[0][0][0].name).toMatchInlineSnapshot(
`"Profile"`
);
expect(posts.initialize).toHaveBeenCalledTimes(1);
expect(posts.initialize.mock.calls[0][0][0].name).toMatchInlineSnapshot(
`"Post"`
);
});
});
|
skimah/skimah
|
packages/api/src/relations.ts
|
import {
getPluralName,
ObjectTypeComposer,
SchemaComposer
} from "graphql-compose";
import { Model } from "./types";
export const isFieldRelation = (fieldName: string, tc: ObjectTypeComposer) => {
const isDefined = !!tc.getFieldDirectiveByName(fieldName, "relation");
return isDefined;
};
export const constructRelationType = (
isCollection: boolean,
isDifferentSources: boolean
) => {
return {
collectionFromSameSources: isCollection && !isDifferentSources,
collectionFromDifferentSources: isCollection && isDifferentSources,
singleFromSameSources: !isCollection && !isDifferentSources,
singleFromDifferentSources: !isCollection && isDifferentSources
};
};
/**
* @internal
* This module will create relations between a Type and its fields
*
* To determine if a field should be considered for relation,
* the following conditions must be satisfied
*
* 1. Must be defined with a `@relation` directive
* 2. Must be non scalar type
*
* fields with datasources different from the parent type
* will use the field's type resolver instead of use the parent's
* resolver
*
*/
export default (
tc: ObjectTypeComposer,
composer: SchemaComposer<any>,
models: { [key: string]: Model }
) => {
const fields = tc.getFields();
for (const fieldName in fields) {
const fieldTC = tc.getFieldTC(fieldName);
const isNonScalar = !composer.isScalarType(fieldTC.getType());
const isRelation = isFieldRelation(fieldName, tc);
const isCollection = tc.isFieldPlural(fieldName);
const fieldTypeName = fieldTC.getTypeName();
const parentModel = models[tc.getTypeName()];
const fieldModel = models[fieldTypeName];
/**
* It is possible that fieldModel might not be an ObjectType but
* instead an interface or a union type that will be resolved at runtime
*/
if (isRelation && isNonScalar && fieldModel) {
const differentDatasources =
parentModel.datasource !== fieldModel.datasource;
const typeResolverName = getPluralName(`find ${fieldTypeName}`);
const typeCollectionResolver = composer
.getOTC(fieldTypeName)
.getResolver(typeResolverName)
.clone();
const singleResolver = typeCollectionResolver
.clone()
.removeArg(["where", "limit", "skip", "orderBy"])
.setType(fields[fieldName].type);
const relationshipType = constructRelationType(
isCollection,
differentDatasources
);
if (relationshipType.collectionFromDifferentSources) {
tc.addRelation(fieldName, { resolver: typeCollectionResolver });
} else if (relationshipType.singleFromDifferentSources) {
tc.addRelation(fieldName, { resolver: singleResolver });
} else if (relationshipType.collectionFromSameSources) {
tc.extendField(fieldName, { args: typeCollectionResolver.args });
} else if (relationshipType.singleFromSameSources) {
tc.extendField(fieldName, {
resolver: singleResolver
});
}
}
}
};
|
skimah/skimah
|
packages/api/src/models/selection.ts
|
<filename>packages/api/src/models/selection.ts<gh_stars>1-10
import { ResolveTree } from "graphql-parse-resolve-info";
import {
Attribute,
Criteria,
CriteriaFilter,
Model,
QueryModel,
Relation
} from "../types";
/**
* Converts graphql arguments criteria and criteria filter
*
* 1. { where: { and : [ { name: {eq: "James" } }, { name: {eq: "Bond" } } ] } }
* 2. { where: { or : [ { name: {eq: "James" } }, { name: {eq: "Bond" } } ] } }
* 3. { where: { name: { eq: "James" } } }
*
* @param args {[key:string]: any} Parsed arguments
*/
export const argsToCriteria = (
/* eslint-disable @typescript-eslint/no-explicit-any */
args: { [key: string]: any },
model: Model
): Criteria => {
/**
* Convert `and` filters
*/
const andFilters = (args.where?.and || []).map(filter => {
const newFilter = {};
Object.entries(filter).forEach(([fieldName, val]) => {
const attr = model.attributes[fieldName];
newFilter[attr.sourceName] = val;
});
return newFilter;
});
/**
* Convert `or` filters
*/
const orFilters = (args.where?.or || []).map(filter => {
const newFilter = {};
Object.entries(filter).forEach(([fieldName, val]) => {
const attr = model.attributes[fieldName];
newFilter[attr.sourceName] = val;
});
return newFilter;
});
/**
* Assign the none array arguments into a filter that can be added to default
* `and` filter e.g
* where: { name: { eq: "Bond" } }
*/
const noneArrayEntries = Object.entries(args.where || {});
const baseFilters = [];
if (noneArrayEntries.length > 0) {
const baseFilter: CriteriaFilter = {};
noneArrayEntries.forEach(([key, val]) => {
if (key !== "and" && key !== "or") {
const attribute = model.attributes[key] || model.relations[key];
baseFilter[attribute.sourceName] = val;
}
});
baseFilters.push(baseFilter);
}
return {
and: [...andFilters, ...baseFilters],
or: orFilters,
limit: args.limit,
skip: args.skip,
orderBy: args.orderBy || {}
};
};
interface SelectionArg {
baseModel: Model;
models: { [key: string]: Model };
interfaces: { [key: string]: Model[] };
tree: ResolveTree;
}
/**
* Maps a model to a selection model.
*
* Only includes selected attributes from the projection in the query
*
*/
const createQueryModel = ({
baseModel,
tree,
models,
interfaces
}: SelectionArg): QueryModel => {
const projectedAttributes: { [key: string]: Attribute } = {};
const projectedRelations: { [key: string]: Relation } = {};
const { fieldsByTypeName, args: criteriaArgs } = tree;
const [[, fields]] = Object.entries(fieldsByTypeName);
for (const [fieldName, fieldTree] of Object.entries(fields)) {
if (baseModel.attributes[fieldTree.name]) {
// account for GraphQL field aliasing
projectedAttributes[fieldName] = Object.assign(
{},
baseModel.attributes[fieldTree.name]
);
} else {
const theRelation = baseModel.relations[fieldTree.name];
let relationModel = models[theRelation.type];
/**
* There are a 2 reasons why a relationModel could be undefined/null
*
* 1. if the relation is an interface
*
* 2. if the relation is a union type
*
* Then we need to manually resolve what type (model) should be used
* for the relational model based on the requested fields
*/
if (!relationModel) {
const nonObjectRequestedFields = Object.keys(
fieldTree.fieldsByTypeName[theRelation.type]
);
const nonObjectTypeName = theRelation.type;
const interfaceModels = interfaces[nonObjectTypeName] || [];
/**
* Using the field comparison, we will pick the first model
* that matches the requested fields for the interface
*/
const [interfaceModel] = interfaceModels.filter(itrModel => {
const allModelFields = Object.keys(itrModel.attributes).concat(
Object.keys(itrModel.relations)
);
return nonObjectRequestedFields.every(itrField =>
allModelFields.includes(itrField)
);
});
/**
* If no object type has implemented the interface
* then We will throw an error because we don't know how to source
* the model
*/
if (!interfaceModel) {
throw new Error(
`Can not find any implementation for interface ${nonObjectTypeName}`
);
}
relationModel = interfaceModel;
}
/**
* For one-to-one relationships, an attribute should be added to
* the projected attributes for selection and later for comparison
* in the child relations
*
* Also account for the field alias
*/
if (!theRelation.isCollection) {
projectedAttributes[fieldTree.name] = {
name: fieldTree.name,
sourceName: theRelation.sourceName,
type: "ID",
unique: false
};
}
/**
* Only include relationships of models that are from
* the same datasource. This will allow the datasource in
* question to perform batch fetch
*
* e.g in a SQL datasource, a left join can be performed
* to join tables
*
*/
if (baseModel.datasource === relationModel.datasource) {
const newRelation = Object.assign({}, theRelation, {
model: createQueryModel({
baseModel: relationModel,
models,
tree: fieldTree,
interfaces
})
});
/**
* For a direct one-to-many relationship,
* include the child condition of the relation
* in the projected attribute of the child
*
* This only works if the relationship is bidirectional
*/
if (newRelation.isCollection) {
const foreignFieldName = newRelation.condition.child.name;
const foreignRelation = newRelation.model.relations[foreignFieldName];
if (foreignRelation) {
newRelation.model.projectedAttributes[foreignFieldName] = {
name: foreignRelation.name,
sourceName: foreignRelation.sourceName,
unique: false,
type: "ID"
};
}
}
projectedRelations[fieldName] = newRelation;
}
}
}
/**
* Include the identities for this model automatically in the attributes that should
* be selected. This will allow for joining of models
* across datasources
*/
baseModel.identities.forEach(attr => {
Object.assign(projectedAttributes, {
[attr.name]: attr
});
});
return {
...baseModel,
projectedAttributes,
projectedRelations,
criteria: argsToCriteria(criteriaArgs, baseModel)
};
};
export default createQueryModel;
|
skimah/skimah
|
packages/api/test/readonly.test.ts
|
<filename>packages/api/test/readonly.test.ts
import { graphql } from "graphql";
import { ObjectTypeComposer, schemaComposer } from "graphql-compose";
import generate from "../src/generate";
import { Datasource } from "../src/types";
const typeDefs = `
type User {
userid: Int
username: String
avatar: Avatar @relation(as:"user")
}
type Avatar @readOnly {
id: ID
url: String
user: User
}
`;
describe("Schema Orderby", () => {
const defaultSource: Datasource = {
select: jest.fn(),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn()
};
test("confirms @readonly is immutable", async () => {
const ts = schemaComposer.addTypeDefs(typeDefs);
const tc = <ObjectTypeComposer>ts.get("User");
const { schema } = await generate({
typeDefs,
sources: { default: defaultSource }
});
const query = `
mutation {
createAvatars(data:[{id: "simple", url: "http://example.com/me"}]) {
affected
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toMatchInlineSnapshot(`
Array [
[GraphQLError: Cannot query field "createAvatars" on type "Mutation". Did you mean "createUsers"?],
]
`);
});
});
|
skimah/skimah
|
packages/api/src/resolvers/create.ts
|
import { getPluralName } from "graphql-compose";
import createCreation from "../models/creation";
import { ResolverDefinition } from "./index";
/**
* @internal
*/
export default ({
models,
datasources,
type: tc,
composer
}: ResolverDefinition): string => {
const name = getPluralName(`create${tc.getTypeName()}`);
tc.addResolver({
name,
type: `${tc.getTypeName()}MutationResponse`,
args: {
data: {
type: composer
.getITC(`${tc.getTypeName()}Input`)
.getTypeNonNull()
.getTypePlural()
.getTypeNonNull()
}
},
resolve: async ({ args }) => {
const modelType = tc.getTypeName();
const baseModel = models[modelType];
const modelSource = datasources[baseModel.datasource];
const creationModels = args.data.map(values =>
createCreation({
baseModel,
models,
values
})
);
const response = await modelSource.create(creationModels);
return response;
}
});
return name;
};
|
skimah/skimah
|
packages/api/test/relation.test.ts
|
import generate from "../src/generate";
import { Datasource, SkimahResult } from "../src/types";
import { graphql } from "graphql";
const typeDefs = `
type User {
userid: ID
email: String
age: Int
height: Float
videos: [Video] @relation(field: "publisher")
}
type Video {
videoID: ID
name: String
url: String
rated: Rated! @relation(field: "media")
comments: [Comments] @relation @relation
publisher: User! @relation(field: "userid")
}
type Comments @datasource(name: "wiki") {
commentId: ID
text: String
video: Video @relation
}
type Rated @datasource(name: "google") {
id: ID
value: Float
media: Video
}
type Query {
hello: String
}
type Mutation {
hello: String
}
`;
const defaultSource: Datasource = {
select: jest.fn(),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn()
};
const googleSource: Datasource = {
select: jest.fn().mockResolvedValue([{ id: "ratedid" }]),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn()
};
let skimahResult: SkimahResult;
describe("Schema Relations", () => {
beforeAll(async () => {
skimahResult = await generate({
typeDefs,
sources: {
default: defaultSource,
google: googleSource,
wiki: defaultSource
}
});
});
test("One-to-many field relations", () => {
// videos field has a filter argument
// emails which is a scalar has no filter
expect(skimahResult.schemaComposer.getOTC("User").toSDL())
.toMatchInlineSnapshot(`
"type User {
userid: ID
email: String
age: Int
height: Float
videos(
\\"\\"\\"Limit the number of videos that will be returned\\"\\"\\"
limit: Int
\\"\\"\\"Skip the first number of videos that will be returned\\"\\"\\"
skip: Int
\\"\\"\\"Filter condition for videos that will be returned\\"\\"\\"
where: VideoFilter
\\"\\"\\"Sort videos that will be returned\\"\\"\\"
orderBy: VideoOrderBy
): [Video] @relation(field: \\"publisher\\")
}"
`);
// the publisher field, a non collection has no filter field
expect(skimahResult.schemaComposer.getOTC("Video").toSDL())
.toMatchInlineSnapshot(`
"type Video {
videoID: ID
name: String
url: String
rated: Rated!
comments(
\\"\\"\\"Limit the number of comments that will be returned\\"\\"\\"
limit: Int
\\"\\"\\"Skip the first number of comments that will be returned\\"\\"\\"
skip: Int
\\"\\"\\"Filter condition for comments that will be returned\\"\\"\\"
where: CommentsFilter
\\"\\"\\"Sort comments that will be returned\\"\\"\\"
orderBy: CommentsOrderBy
): [Comments]!
publisher: User! @relation(field: \\"userid\\")
}"
`);
});
test("One-to-one field relations", () => {
// videos field has a filter argument
// emails which is a scalar has no filter
expect(skimahResult.schemaComposer.getOTC("Video").toSDL())
.toMatchInlineSnapshot(`
"type Video {
videoID: ID
name: String
url: String
rated: Rated!
comments(
\\"\\"\\"Limit the number of comments that will be returned\\"\\"\\"
limit: Int
\\"\\"\\"Skip the first number of comments that will be returned\\"\\"\\"
skip: Int
\\"\\"\\"Filter condition for comments that will be returned\\"\\"\\"
where: CommentsFilter
\\"\\"\\"Sort comments that will be returned\\"\\"\\"
orderBy: CommentsOrderBy
): [Comments]!
publisher: User! @relation(field: \\"userid\\")
}"
`);
// the publisher field, a non collection has no filter field
expect(skimahResult.schemaComposer.getOTC("Video").toSDL())
.toMatchInlineSnapshot(`
"type Video {
videoID: ID
name: String
url: String
rated: Rated!
comments(
\\"\\"\\"Limit the number of comments that will be returned\\"\\"\\"
limit: Int
\\"\\"\\"Skip the first number of comments that will be returned\\"\\"\\"
skip: Int
\\"\\"\\"Filter condition for comments that will be returned\\"\\"\\"
where: CommentsFilter
\\"\\"\\"Sort comments that will be returned\\"\\"\\"
orderBy: CommentsOrderBy
): [Comments]!
publisher: User! @relation(field: \\"userid\\")
}"
`);
});
test("Same source Parent & Child use same resolver", async () => {
const videoSource: Datasource = {
select: jest.fn().mockResolvedValue([{ userid: "sample-video" }]),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn()
};
const wikiSource: Datasource = {
select: jest.fn(),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn()
};
const { schema } = await generate({
typeDefs,
sources: {
default: videoSource,
wiki: wikiSource,
google: googleSource
}
});
const query = `
query {
findUsers {
videos(where : { name:{ eq: "trending" } }) {
name
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(videoSource.select).toHaveBeenCalledTimes(1);
});
test("Different source Parent & Child use different resolvers", async () => {
const defaultSource: Datasource = {
select: jest.fn().mockResolvedValue([{ userid: "sample-video" }]),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn()
};
const googleSource: Datasource = {
select: jest.fn().mockResolvedValue([{ id: "ratedid", value: 2 }]),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn()
};
const wikiSource: Datasource = {
select: jest.fn().mockResolvedValue([{ id: "ratedid" }]),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn()
};
const { schema } = await generate({
typeDefs,
sources: {
default: defaultSource,
google: googleSource,
wiki: wikiSource
}
});
const query = `
query {
findVideos {
rated {
value
}
comments( where: { text:{ eq: "nice" } } ) {
text
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(defaultSource.select).toHaveBeenCalledTimes(1);
expect(googleSource.select).toHaveBeenCalledTimes(1);
expect(wikiSource.select).toHaveBeenCalledTimes(1);
});
test("Non-collection fields have no fields", async () => {
const defaultSource: Datasource = {
select: jest.fn().mockResolvedValue([{ userid: "sample-video" }]),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn()
};
const googleSource: Datasource = {
select: jest.fn().mockResolvedValue([]),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn()
};
const { schema } = await generate({
typeDefs,
sources: {
default: defaultSource,
google: googleSource,
wiki: defaultSource
}
});
const query = `
query {
findVideos {
rated (skip: 1) {
value
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors[0].toString()).toContain(
`Unknown argument "skip" on field "Video.rated`
);
});
});
|
skimah/skimah
|
packages/api/src/filter.ts
|
<reponame>skimah/skimah<filename>packages/api/src/filter.ts
import {
getPluralName,
InputTypeComposerFieldConfigAsObjectDefinition,
ObjectTypeComposer,
SchemaComposer
} from "graphql-compose";
const TYPE_OPERATORS = {
Boolean: ["eq", "ne"],
Int: ["eq", "ne", "lte", "lt", "in", "nin", "gte", "gt"],
Float: ["eq", "ne", "lte", "lt", "gte", "gt"],
String: ["eq", "ne", "like", "in", "nin"],
ID: ["eq", "ne", "in", "nin"]
};
/**
* Create an operator input type
*/
const createTypeOperators = (composer: SchemaComposer<any>) => {
for (let [typeKey, operators] of Object.entries(TYPE_OPERATORS)) {
composer.getOrCreateITC(`${typeKey}Opr`, itc => {
itc.setDescription(`Filter input based on ${typeKey}`);
operators.forEach(operator => {
// create array types
if (["in", "nin"].includes(operator)) {
itc.setField(operator, {
type: `[${typeKey}!]`
});
} else {
// check for the array type here and create a list type input
itc.setField(operator, {
type: typeKey
});
}
});
});
}
};
/** @internal */
export default (tc: ObjectTypeComposer, composer: SchemaComposer<any>) => {
createTypeOperators(composer);
const fields = tc.getFields();
const typeFilterName = `${tc.getTypeName()}Filter`;
composer.getOrCreateITC(typeFilterName, itc => {
itc.setDescription(`Filter ${tc.getTypeName()} fields`);
for (const fieldName in fields) {
const field = fields[fieldName];
const fieldType = field.type.getType();
const isScalar = composer.isScalarType(fieldType);
// single field relationship
const isSingleRelation = !tc.isFieldPlural(fieldName) && !isScalar;
const pluralFieldName = getPluralName(tc.getTypeName());
/**
* Only scalar and a single relationship
*/
if (isScalar || isSingleRelation) {
// non-scalar single fields
const type = isSingleRelation ? `IDOpr` : `${fieldType}Opr`;
const objConfig = <InputTypeComposerFieldConfigAsObjectDefinition>{
type,
description: `Filter ${pluralFieldName} based on ${fieldName}`
};
itc.setField(fieldName, objConfig);
}
}
/**
* Combination filters
*/
itc.setField("and", {
type: `[${typeFilterName}!]`,
description: `Combine filters`
});
itc.setField("or", {
type: `[${typeFilterName}!]`,
description: `Combine filters`
});
});
};
|
skimah/skimah
|
packages/ds-csv/test/csv.test.ts
|
<filename>packages/ds-csv/test/csv.test.ts
import { generate, SkimahConfig } from "@skimah/api";
import { graphql } from "graphql";
import CSVSource from "../src/csv";
const typeDefs = `
type Album @datasource(name: "albums") {
id: ID @named(as: "AlbumId")
title: String @named(as: "Title")
artist: Artist @relation @named(as: "ArtistId")
}
type Artist @datasource(name: "artists") {
id: ID @named(as: "ArtistId")
name: String @named(as: "Name")
albums: [Album] @relation
}
`;
describe("Datasource CSV", () => {
let schema;
beforeAll(async () => {
const albums = new CSVSource({
filepath: "fixtures/Album.csv"
});
const artists = new CSVSource({
filepath: "fixtures/Artist.csv"
});
const sources = { albums, artists };
const config: SkimahConfig = { typeDefs, sources };
const scaffoldResult = await generate(config);
schema = scaffoldResult.schema;
});
describe("Selection", () => {
test("Skip and Limit", async () => {
const query = `
query {
findAlbums(skip: 2, limit: 2) {
title
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"findAlbums": Array [
Object {
"title": "Restless and Wild",
},
Object {
"title": "Let There Be Rock",
},
],
}
`);
});
test("One-to-Many relationship", async () => {
const query = `
query {
findArtists(where: { name: { eq: "U2" } }) {
id
name
albums {
title
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"findArtists": Array [
Object {
"albums": Array [
Object {
"title": "Achtung Baby",
},
Object {
"title": "All That You Can't Leave Behind",
},
Object {
"title": "B-Sides 1980-1990",
},
Object {
"title": "How To Dismantle An Atomic Bomb",
},
Object {
"title": "Pop",
},
Object {
"title": "Rattle And Hum",
},
Object {
"title": "The Best Of 1980-1990",
},
Object {
"title": "War",
},
Object {
"title": "Zooropa",
},
Object {
"title": "Instant Karma: The Amnesty International Campaign to Save Darfur",
},
],
"id": "150",
"name": "U2",
},
],
}
`);
});
test("One-to-One relationship", async () => {
const query = `
query {
findAlbums(limit: 2) {
title
artist {
name
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"findAlbums": Array [
Object {
"artist": Object {
"name": "AC/DC",
},
"title": "For Those About To Rock We Salute You",
},
Object {
"artist": Object {
"name": "Accept",
},
"title": "Balls to the Wall",
},
],
}
`);
});
});
describe("Mutation", () => {
it("Create", async () => {
const createId = () => Math.round(Math.random() * 100000);
const query = `
mutation {
createArtists(data: [
{ id: ${createId()}, name: "Artist-${createId()}" },
{ id: ${createId()}, name: "Artist-${createId()}" },
]) {
affected
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data.createArtists.affected).toHaveLength(2);
});
it("Update", async () => {
const query = `
mutation {
updateArtists(changes: { name: "<NAME>", }, where: { id: {eq: 100} }) {
affected
artists {
id
name
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"updateArtists": Object {
"affected": Array [
"100",
],
"artists": Array [
Object {
"id": "100",
"name": "<NAME>",
},
],
},
}
`);
});
it("Delete", async () => {
const query = `
mutation {
deleteAlbums(where: { title: { like: "For Those*" } } ) {
affected
albums {
title
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"deleteAlbums": Object {
"affected": Array [
"1",
],
"albums": Array [
Object {
"title": "For Those About To Rock We Salute You",
},
],
},
}
`);
});
});
});
|
skimah/skimah
|
packages/api/src/index.ts
|
export { default as generate } from "./generate";
export * from "./datasource";
export * from "./types";
|
skimah/skimah
|
packages/api/test/resolvers/delete.test.ts
|
<reponame>skimah/skimah<filename>packages/api/test/resolvers/delete.test.ts<gh_stars>1-10
import generate from "../../src/generate";
import { Datasource } from "../../src/types";
import { graphql } from "graphql";
const typeDefs = `
type User {
userid: ID
age: Int
height: Float
avatar: Avatar @relation
}
type Avatar {
avatarId: ID
url: String
user: User @relation
}
`;
describe("Schema Delete Resolver", () => {
test("delete criteria", async () => {
const source: Datasource = {
select: jest.fn(),
update: jest.fn(),
create: jest.fn(),
delete: jest.fn(() => Promise.resolve({ affected: ["1", "2", "3"] }))
};
const { schema } = await generate({
typeDefs,
sources: { default: source }
});
const query = `
mutation {
deleteUsers (where: { age: { gte: 10 }, height: { lt: 50 }, avatar: { eq: "1" } }) {
affected
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
const [[arg]] = (source.delete as jest.MockedFunction<any>).mock.calls;
expect(source.delete).toHaveBeenCalledTimes(1);
expect(arg).toMatchInlineSnapshot(`
Object {
"and": Array [
Object {
"age": Object {
"gte": 10,
},
"avatar": Object {
"eq": "1",
},
"height": Object {
"lt": 50,
},
},
],
"limit": undefined,
"or": Array [],
"orderBy": Object {},
"skip": undefined,
}
`);
});
test("return deleted records", async () => {
let calls = [];
const source: Datasource = {
update: jest.fn(),
create: jest.fn(),
select: jest.fn(() => {
calls.push("selection");
return Promise.resolve([
{ userid: 1, age: 10, avatar: { avatarId: 1, url: "a-b-c" } },
{ userid: 2, age: 2, avatar: { avatarId: 12, url: "d-e-f" } },
{ userid: 3, age: 4, avatar: { avatarId: 20, url: "g-h-j" } }
]);
}),
delete: jest.fn(() => {
calls.push("deletion");
return Promise.resolve({
affected: ["1", "2", "3"],
users: [{ userid: 1 }, { userid: 2 }, { userid: 3 }]
});
})
};
const { schema } = await generate({
typeDefs,
sources: { default: source }
});
const query = `
mutation {
deleteUsers (where: { age: { gte: 10 } }) {
affected
users {
userid
age
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(source.select).toBeCalledTimes(1);
expect(calls).toMatchInlineSnapshot(`
Array [
"selection",
"deletion",
]
`);
const [[arg]] = (source.select as jest.MockedFunction<any>).mock.calls;
expect(arg.criteria).toMatchInlineSnapshot(`
Object {
"and": Array [
Object {
"age": Object {
"gte": 10,
},
},
],
"limit": undefined,
"or": Array [],
"orderBy": Object {},
"skip": undefined,
}
`);
expect(result.data).toMatchInlineSnapshot(`
Object {
"deleteUsers": Object {
"affected": Array [
"1",
"2",
"3",
],
"users": Array [
Object {
"age": 10,
"userid": "1",
},
Object {
"age": 2,
"userid": "2",
},
Object {
"age": 4,
"userid": "3",
},
],
},
}
`);
});
});
|
skimah/skimah
|
packages/api/src/models/creation.ts
|
import { Model, MutationModel, MutationAttribute } from "../types";
interface CreationArg {
baseModel: Model;
models: { [key: string]: Model };
/* eslint-disable @typescript-eslint/no-explicit-any */
values: any;
parentType?: string;
}
/**
* Create a creation model with the arg value mapped to the attribute values
*/
const mapToModel = ({ baseModel, values }: CreationArg): MutationModel => {
const mutatedAttributes: { [key: string]: MutationAttribute } = {};
for (const [fieldName, value] of Object.entries(values)) {
if (baseModel.attributes[fieldName]) {
mutatedAttributes[fieldName] = Object.assign(
{},
baseModel.attributes[fieldName],
{
value
}
);
} else if (baseModel.relations[fieldName]) {
/**
* In the case of updating a one-to-one relationship
* include the field as a ID (String) to be able to create
* the relationship
*/
const relation = baseModel.relations[fieldName];
mutatedAttributes[fieldName] = {
name: relation.name,
sourceName: relation.sourceName,
value,
unique: true,
type: "ID"
};
}
}
return {
...baseModel,
mutatedAttributes
};
};
export default mapToModel;
|
skimah/skimah
|
packages/api/test/models/creation.test.ts
|
import { graphql } from "graphql";
import generate from "../../src/generate";
import { Datasource } from "../../src/types";
const typeDefs = `
type User {
userid: ID
email: String
username: String
profile: Profile @relation
}
type Profile {
id: ID
type: String
}
`;
describe("Schema Creation", () => {
test("creation model", async () => {
const defaultSource: Datasource = {
select: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
create: jest.fn(() => Promise.resolve({ affected: ["1", "2", "3"] }))
};
const { schema } = await generate({
typeDefs,
sources: { default: defaultSource }
});
const query = `
mutation {
createUsers ( data:[{ userid: "my-id", username: "bond" }]) {
affected
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
const [[arg]] = (defaultSource.create as jest.MockedFunction<
any
>).mock.calls;
expect(defaultSource.create).toHaveBeenCalledTimes(1);
expect(arg).toMatchInlineSnapshot(`
Array [
Object {
"attributes": Object {
"email": Object {
"name": "email",
"sourceName": "email",
"type": "String",
"unique": false,
},
"userid": Object {
"name": "userid",
"sourceName": "userid",
"type": "ID",
"unique": true,
},
"username": Object {
"name": "username",
"sourceName": "username",
"type": "String",
"unique": false,
},
},
"datasource": "default",
"identities": Array [
Object {
"name": "userid",
"sourceName": "userid",
"type": "ID",
"unique": true,
},
],
"mutatedAttributes": Object {
"userid": Object {
"name": "userid",
"sourceName": "userid",
"type": "ID",
"unique": true,
"value": "my-id",
},
"username": Object {
"name": "username",
"sourceName": "username",
"type": "String",
"unique": false,
"value": "bond",
},
},
"name": "User",
"relations": Object {
"profile": Object {
"condition": Object {
"child": Object {
"name": "id",
"sourceName": "id",
},
"parent": Object {
"name": "profile",
"sourceName": "profile",
},
},
"isCollection": false,
"model": null,
"name": "profile",
"sourceName": "profile",
"type": "Profile",
"unique": false,
},
},
"sourceName": "User",
},
]
`);
});
test("creation response", async () => {
const defaultSource: Datasource = {
select: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
create: jest.fn(() => Promise.resolve({ affected: ["1", "2", "3"] }))
};
const { schema } = await generate({
typeDefs,
sources: { default: defaultSource }
});
const query = `
mutation {
createUsers ( data:[{ userid: "my-id", username: "bond" }]) {
affected
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data).toMatchInlineSnapshot(`
Object {
"createUsers": Object {
"affected": Array [
"1",
"2",
"3",
],
},
}
`);
});
test("returned records", async () => {
const defaultSource: Datasource = {
select: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
create: jest.fn(() =>
Promise.resolve({
affected: ["1", "2", "3"],
records: [{ userid: 1 }, { userid: 2 }, { userid: 3 }]
})
)
};
const { schema } = await generate({
typeDefs,
sources: {
default: defaultSource
}
});
const query = `
mutation {
createUsers (
data:[{ userid: "my-id", username: "bond" }]
) {
affected
users {
userid
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
expect(result.data.createUsers).toMatchInlineSnapshot(`
Object {
"affected": Array [
"1",
"2",
"3",
],
"users": Array [
Object {
"userid": "1",
},
Object {
"userid": "2",
},
Object {
"userid": "3",
},
],
}
`);
});
test("query returned records", async () => {
const defaultSource: Datasource = {
update: jest.fn(),
delete: jest.fn(),
select: jest.fn(() =>
Promise.resolve([{ userid: 1 }, { userid: 2 }, { userid: 3 }])
),
create: jest.fn(() =>
Promise.resolve({
affected: ["1", "2", "3"]
})
)
};
const { schema } = await generate({
typeDefs,
sources: {
default: defaultSource
}
});
const query = `
mutation {
createUsers (
data:[{ userid: "my-id", username: "bond" }]
) {
affected
users {
userid
}
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
const [[selection]] = (<any>defaultSource.select).mock.calls;
expect(selection.criteria).toMatchInlineSnapshot(`
Object {
"and": Array [
Object {
"userid": Object {
"in": Array [
"1",
"2",
"3",
],
},
},
],
"limit": undefined,
"or": Array [],
"orderBy": Object {},
"skip": undefined,
}
`);
expect(result.data.createUsers).toMatchInlineSnapshot(`
Object {
"affected": Array [
"1",
"2",
"3",
],
"users": Array [
Object {
"userid": "1",
},
Object {
"userid": "2",
},
Object {
"userid": "3",
},
],
}
`);
});
});
|
skimah/skimah
|
packages/api/test/resolvers/find.test.ts
|
<filename>packages/api/test/resolvers/find.test.ts
import generate from "../../src/generate";
import { Datasource } from "../../src/types";
import { graphql } from "graphql";
const typeDefs = `
type User @datasource(name: "users") {
userid: ID
email: String
age: Int
height: Float
status: Status
videos: [Video] @relation
}
enum Status {
disabled
ready
}
type Video @datasource(name: "videos") {
videoID: ID
name: String
url: String
publisher: User! @relation
acl: ACL
limit: Limit @relation
uploadLimits: [Limit] @relation
}
type ACL {
disabled: Boolean
}
interface Limit {
id: ID
when: String
how: String
video: Video @relation
}
type VideoLimit implements Limit {
id: ID
when: String
how: String
url: String
video: Video @relation
}
type UploadLimit implements Limit @datasource(name: "uploadLimits") {
id: ID
when: String
how: String
count: Int
video: Video @relation
}
`;
const users: Datasource = {
select: jest
.fn()
.mockResolvedValue([{ userid: "new-user-id", email: "<EMAIL>" }]),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn()
};
const videos: Datasource = {
select: jest.fn().mockResolvedValue([
{
videoID: "new-video",
acl: { disabled: false },
limit: { when: "now", url: "link_to_blocked_video" },
uploadLimits: [{ when: "now", count: 5 }]
}
]),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn()
};
const uploadLimits: Datasource = {
select: jest.fn().mockResolvedValue([{ when: "now", count: 5 }]),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn()
};
describe("Schema Find Resolver", () => {
let schemaResult;
beforeAll(async () => {
schemaResult = await generate({
typeDefs,
sources: {
uploadLimits,
users,
videos
}
});
});
test("query and mutation", () => {
expect(schemaResult.schemaComposer.Mutation.toSDL()).toMatchInlineSnapshot(`
"type Mutation {
createUsers(data: [UserInput!]!): UserMutationResponse
\\"\\"\\"Update users\\"\\"\\"
updateUsers(
\\"\\"\\"Update filter for users\\"\\"\\"
where: UserFilter!
changes: UserInput!
): UserMutationResponse
\\"\\"\\"Delete users\\"\\"\\"
deleteUsers(
\\"\\"\\"Deletion filter for users\\"\\"\\"
where: UserFilter!
): UserMutationResponse
createVideos(data: [VideoInput!]!): VideoMutationResponse
\\"\\"\\"Update videos\\"\\"\\"
updateVideos(
\\"\\"\\"Update filter for videos\\"\\"\\"
where: VideoFilter!
changes: VideoInput!
): VideoMutationResponse
\\"\\"\\"Delete videos\\"\\"\\"
deleteVideos(
\\"\\"\\"Deletion filter for videos\\"\\"\\"
where: VideoFilter!
): VideoMutationResponse
createACL(data: [ACLInput!]!): ACLMutationResponse
\\"\\"\\"Update aCL\\"\\"\\"
updateACL(
\\"\\"\\"Update filter for aCL\\"\\"\\"
where: ACLFilter!
changes: ACLInput!
): ACLMutationResponse
\\"\\"\\"Delete aCL\\"\\"\\"
deleteACL(
\\"\\"\\"Deletion filter for aCL\\"\\"\\"
where: ACLFilter!
): ACLMutationResponse
createVideoLimits(data: [VideoLimitInput!]!): VideoLimitMutationResponse
\\"\\"\\"Update videoLimits\\"\\"\\"
updateVideoLimits(
\\"\\"\\"Update filter for videoLimits\\"\\"\\"
where: VideoLimitFilter!
changes: VideoLimitInput!
): VideoLimitMutationResponse
\\"\\"\\"Delete videoLimits\\"\\"\\"
deleteVideoLimits(
\\"\\"\\"Deletion filter for videoLimits\\"\\"\\"
where: VideoLimitFilter!
): VideoLimitMutationResponse
createUploadLimits(data: [UploadLimitInput!]!): UploadLimitMutationResponse
\\"\\"\\"Update uploadLimits\\"\\"\\"
updateUploadLimits(
\\"\\"\\"Update filter for uploadLimits\\"\\"\\"
where: UploadLimitFilter!
changes: UploadLimitInput!
): UploadLimitMutationResponse
\\"\\"\\"Delete uploadLimits\\"\\"\\"
deleteUploadLimits(
\\"\\"\\"Deletion filter for uploadLimits\\"\\"\\"
where: UploadLimitFilter!
): UploadLimitMutationResponse
}"
`);
expect(schemaResult.schemaComposer.Query.toSDL()).toMatchInlineSnapshot(`
"type Query {
findUsers(
\\"\\"\\"Limit the number of users that will be returned\\"\\"\\"
limit: Int
\\"\\"\\"Skip the first number of users that will be returned\\"\\"\\"
skip: Int
\\"\\"\\"Filter condition for users that will be returned\\"\\"\\"
where: UserFilter
\\"\\"\\"Sort users that will be returned\\"\\"\\"
orderBy: UserOrderBy
): [User]!
findVideos(
\\"\\"\\"Limit the number of videos that will be returned\\"\\"\\"
limit: Int
\\"\\"\\"Skip the first number of videos that will be returned\\"\\"\\"
skip: Int
\\"\\"\\"Filter condition for videos that will be returned\\"\\"\\"
where: VideoFilter
\\"\\"\\"Sort videos that will be returned\\"\\"\\"
orderBy: VideoOrderBy
): [Video]!
findACL(
\\"\\"\\"Limit the number of aCL that will be returned\\"\\"\\"
limit: Int
\\"\\"\\"Skip the first number of aCL that will be returned\\"\\"\\"
skip: Int
\\"\\"\\"Filter condition for aCL that will be returned\\"\\"\\"
where: ACLFilter
\\"\\"\\"Sort aCL that will be returned\\"\\"\\"
orderBy: ACLOrderBy
): [ACL]!
findVideoLimits(
\\"\\"\\"Limit the number of videoLimits that will be returned\\"\\"\\"
limit: Int
\\"\\"\\"Skip the first number of videoLimits that will be returned\\"\\"\\"
skip: Int
\\"\\"\\"Filter condition for videoLimits that will be returned\\"\\"\\"
where: VideoLimitFilter
\\"\\"\\"Sort videoLimits that will be returned\\"\\"\\"
orderBy: VideoLimitOrderBy
): [VideoLimit]!
findUploadLimits(
\\"\\"\\"Limit the number of uploadLimits that will be returned\\"\\"\\"
limit: Int
\\"\\"\\"Skip the first number of uploadLimits that will be returned\\"\\"\\"
skip: Int
\\"\\"\\"Filter condition for uploadLimits that will be returned\\"\\"\\"
where: UploadLimitFilter
\\"\\"\\"Sort uploadLimits that will be returned\\"\\"\\"
orderBy: UploadLimitOrderBy
): [UploadLimit]!
}"
`);
});
test("Resolver returns a single response for single query", async () => {
const query = `
query {
findVideos {
publisher {
email
}
}
}
`;
const result = await graphql(schemaResult.schema, query);
expect(result.errors).toMatchInlineSnapshot(`undefined`);
const {
findVideos: [video]
} = result.data;
expect(video.publisher).toMatchInlineSnapshot(`
Object {
"email": "<EMAIL>",
}
`);
});
test("confirms resolver returns a single response for single query", async () => {
const query = `
query {
findVideos {
publisher {
email
}
}
}
`;
const result = await graphql(schemaResult.schema, query);
expect(result.errors).toMatchInlineSnapshot(`undefined`);
const {
findVideos: [video]
} = result.data;
expect(video.publisher).toMatchInlineSnapshot(`
Object {
"email": "<EMAIL>",
}
`);
});
test("confirms alias query fields", async () => {
const query = `
query {
myVideos: findVideos {
me:publisher {
myEmail:email
}
}
}
`;
const result = await graphql(schemaResult.schema, query);
expect(result.errors).toMatchInlineSnapshot(`undefined`);
const {
myVideos: [video]
} = result.data;
expect(video.me).toMatchInlineSnapshot(`
Object {
"myEmail": "<EMAIL>",
}
`);
});
test("confirms non-relationship object types", async () => {
const query = `
query {
myVideos: findVideos {
name
acl {
disabled
}
}
}
`;
const result = await graphql(schemaResult.schema, query);
expect(result.errors).toMatchInlineSnapshot(`undefined`);
const {
myVideos: [video]
} = result.data;
expect(video.acl).toMatchInlineSnapshot(`
Object {
"disabled": false,
}
`);
});
test("confirms one-to-one interface resolution", async () => {
const query = `
query {
myVideos: findVideos {
name
limit {
when
... on VideoLimit {
url
}
}
}
}
`;
const result = await graphql(schemaResult.schema, query);
expect(result.errors).toMatchInlineSnapshot(`undefined`);
const {
myVideos: [video]
} = result.data;
expect(video.limit).toMatchInlineSnapshot(`
Object {
"url": "link_to_blocked_video",
"when": "now",
}
`);
});
test("confirms one-to-many interface resolution", async () => {
const query = `
query {
myVideos: findVideos {
name
uploadLimits {
when
... on UploadLimit {
count
}
}
}
}
`;
const result = await graphql(schemaResult.schema, query);
expect(result.errors).toMatchInlineSnapshot(`undefined`);
const {
myVideos: [video]
} = result.data;
expect(video.uploadLimits).toMatchInlineSnapshot(`
Array [
Object {
"count": 5,
"when": "now",
},
]
`);
});
test("confirms relation field are passed on to child selection as criteria", async () => {
const query = `
query {
findUsers {
videos {
name
}
}
}
`;
const result = await graphql(schemaResult.schema, query);
expect(result.errors).toMatchInlineSnapshot(`undefined`);
const [[selection]] = (<jest.Mock>videos.select).mock.calls.reverse();
expect(selection.criteria).toMatchInlineSnapshot(`
Object {
"and": Array [
Object {
"publisher": Object {
"eq": "new-user-id",
},
},
],
"limit": undefined,
"or": Array [],
"orderBy": Object {},
"skip": undefined,
}
`);
});
});
|
skimah/skimah
|
packages/api/src/generate.ts
|
<reponame>skimah/skimah<filename>packages/api/src/generate.ts<gh_stars>1-10
import {
ObjectTypeComposer,
SchemaComposer,
InterfaceTypeComposer
} from "graphql-compose";
import { nullSource } from "./datasource";
import createInputFilter from "./filter";
import createInput from "./inputs";
import createModel from "./models/base";
import createOrderBy from "./orderby";
import createRelations from "./relations";
import createResolvers from "./resolvers";
import createMutationResponse from "./response";
import { Model, SkimahConfig, SkimahResult } from "./types";
/**
* @internal
*/
const DIRECTIVES = `
""" Attach a datasource to this type """
directive @datasource(
""" The name of the datasource configured in the Skimah config """
name: String
) on OBJECT
""" Create relationships between types """
directive @relation(
""" The name of the field in the type for the connection """
field: String,
""" For one-to-one relations, specify the owner of that relationship. This will be the type that can create the relationship """
isOwner: Boolean
) on FIELD_DEFINITION
""" Mark a field as unique """
directive @unique on FIELD_DEFINITION
""" Rename a field or object from their source """
directive @named(as: String) on FIELD_DEFINITION | OBJECT
""" Skip mutation operations for models marked as readonly """
directive @readOnly on OBJECT
`;
/**
* @internal
*/
const DEFAULT_TYPES = [
"Query",
"Mutation",
"String",
"Float",
"Boolean",
"ID",
"Int"
];
export default async (config: SkimahConfig): Promise<SkimahResult> => {
const schemaComposer = new SchemaComposer<any>();
const datasources = Object.assign({ default: nullSource }, config.sources);
/**
* Include the framework directives
*/
const typeStorage = schemaComposer.addTypeDefs(
`${DIRECTIVES} \n ${config.typeDefs}`
);
const models: { [key: string]: Model } = {};
const interfaces: { [key: string]: Model[] } = {};
const modelsBySource: { [key: string]: Model[] } = {};
const typeModels = Array.from(typeStorage.types.values()).filter(t => {
const typeKind = t.getType().astNode.kind;
const isObject = typeKind === "ObjectTypeDefinition";
return isObject && !DEFAULT_TYPES.includes(t.getTypeName());
});
// extend the types
for (let tc of typeModels) {
const typeName = tc.getTypeName();
// create models
models[typeName] = createModel(<ObjectTypeComposer>tc);
// add type input
createInput(<ObjectTypeComposer>tc, schemaComposer);
// add a mutation response for this type
createMutationResponse(<ObjectTypeComposer>tc, schemaComposer);
// add input filters
createInputFilter(<ObjectTypeComposer>tc, schemaComposer);
// add orderby filters
createOrderBy(<ObjectTypeComposer>tc, schemaComposer);
// add resolvers
createResolvers({
composer: schemaComposer,
datasources,
type: <ObjectTypeComposer>tc,
models,
interfaces
});
// Resolve interfaces
const objComposer = tc as ObjectTypeComposer;
objComposer.getInterfaces().forEach(itf => {
const itComposer = itf as InterfaceTypeComposer;
interfaces[itComposer.getTypeName()] = (
interfaces[itComposer.getTypeName()] || []
).concat(models[typeName]);
itComposer.addTypeResolver(objComposer, src => {
const objectFields = objComposer.getFieldNames();
const itfFields = Object.keys(src);
const isSubset = itfFields.every(field => objectFields.includes(field));
return isSubset;
});
});
/**
* Validate that datasources defined for defined types
*/
const model: Model = models[typeName];
const modelSource = datasources[model.datasource];
if (!modelSource) {
return Promise.reject(
`Schema: No datasource named ${model.datasource} found for ${typeName}`
);
}
modelsBySource[model.datasource] = (
modelsBySource[model.datasource] || []
).concat([model]);
}
/**
* Once all resolvers have been generated for the defined types
* then add the resolvers to the relational field in the types
*/
for (let tc of typeModels) {
createRelations(<ObjectTypeComposer>tc, schemaComposer, models);
}
/**
* Initialize all of the declare datasource with the models
* attached to those datasources
*/
for (const [name, datasource] of Object.entries(datasources)) {
if (datasource.initialize) {
try {
const modelsAttachedToSource = modelsBySource[name] || [];
await datasource.initialize(modelsAttachedToSource);
} catch (error) {
return Promise.reject(
`Skimah Datasource Error: ${name}, ${error.toString()}`
);
}
}
}
return {
schema: schemaComposer.buildSchema(),
resolvers: schemaComposer.getResolveMethods(),
models,
schemaComposer
};
};
|
skimah/skimah
|
packages/api/test/resolvers/create.test.ts
|
import generate from "../../src/generate";
import { Datasource } from "../../src/types";
import { graphql } from "graphql";
const typeDefs = `
type User {
userid: ID
age: Int
height: Float
avatar: Avatar @relation
}
type Avatar {
id: ID
url: String
}
`;
describe("Schema Create Resolvers", () => {
test("create data", async () => {
const source: Datasource = {
select: jest.fn(),
update: jest.fn(),
create: jest.fn(),
delete: jest.fn()
};
const { schema } = await generate({
typeDefs,
sources: { default: source }
});
const query = `
mutation {
createUsers (data: [{userid: 1, age: 10, avatar: "an_avatar"}]) {
affected
}
}
`;
const result = await graphql(schema, query);
expect(result.errors).toBeUndefined();
const [[models]] = (source.create as jest.MockedFunction<any>).mock.calls;
expect(source.create).toHaveBeenCalledTimes(1);
expect(models).toMatchInlineSnapshot(`
Array [
Object {
"attributes": Object {
"age": Object {
"name": "age",
"sourceName": "age",
"type": "Int",
"unique": false,
},
"height": Object {
"name": "height",
"sourceName": "height",
"type": "Float",
"unique": false,
},
"userid": Object {
"name": "userid",
"sourceName": "userid",
"type": "ID",
"unique": true,
},
},
"datasource": "default",
"identities": Array [
Object {
"name": "userid",
"sourceName": "userid",
"type": "ID",
"unique": true,
},
],
"mutatedAttributes": Object {
"age": Object {
"name": "age",
"sourceName": "age",
"type": "Int",
"unique": false,
"value": 10,
},
"avatar": Object {
"name": "avatar",
"sourceName": "avatar",
"type": "ID",
"unique": true,
"value": "an_avatar",
},
"userid": Object {
"name": "userid",
"sourceName": "userid",
"type": "ID",
"unique": true,
"value": "1",
},
},
"name": "User",
"relations": Object {
"avatar": Object {
"condition": Object {
"child": Object {
"name": "id",
"sourceName": "id",
},
"parent": Object {
"name": "avatar",
"sourceName": "avatar",
},
},
"isCollection": false,
"model": null,
"name": "avatar",
"sourceName": "avatar",
"type": "Avatar",
"unique": false,
},
},
"sourceName": "User",
},
]
`);
});
});
|
skimah/skimah
|
packages/api/test/models/base.test.ts
|
import { schemaComposer } from "graphql-compose";
import createModel from "../../src/models/base";
const typeDefs = `
directive @datasource(
name: String
) on OBJECT
directive @relation(
field: String
) on FIELD_DEFINITION
directive @unique on FIELD_DEFINITION
directive @named(as: String) on FIELD_DEFINITION | OBJECT
type User {
userid: ID
email: String
videos: [Video] @relation(field: "publisher")
}
type Video {
videoID: ID
name: String
publisher: User! @named(as: "user") @relation(field: "userid")
}
type Consumer {
id: ID
ratings: [Rating] @relation
}
type Rating @named(as: "ratings") {
ratingID: Int @unique
count: Float @named(as: "total")
consumer: Consumer @relation
}
type Sample {
id: ID
text: String
}
`;
schemaComposer.addTypeDefs(typeDefs);
test("create model with named directives", () => {
const sampleModel = createModel(schemaComposer.getOTC("Rating"));
expect(sampleModel).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"count": Object {
"name": "count",
"sourceName": "total",
"type": "Float",
"unique": false,
},
"ratingID": Object {
"name": "ratingID",
"sourceName": "ratingID",
"type": "Int",
"unique": true,
},
},
"datasource": "default",
"identities": Array [
Object {
"name": "ratingID",
"sourceName": "ratingID",
"type": "Int",
"unique": true,
},
],
"name": "Rating",
"relations": Object {
"consumer": Object {
"condition": Object {
"child": Object {
"name": "id",
"sourceName": "id",
},
"parent": Object {
"name": "consumer",
"sourceName": "consumer",
},
},
"isCollection": false,
"model": null,
"name": "consumer",
"sourceName": "consumer",
"type": "Consumer",
"unique": false,
},
},
"sourceName": "ratings",
}
`);
});
test("create model with no directives", () => {
const sampleModel = createModel(schemaComposer.getOTC("Sample"));
expect(sampleModel).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"id": Object {
"name": "id",
"sourceName": "id",
"type": "ID",
"unique": true,
},
"text": Object {
"name": "text",
"sourceName": "text",
"type": "String",
"unique": false,
},
},
"datasource": "default",
"identities": Array [
Object {
"name": "id",
"sourceName": "id",
"type": "ID",
"unique": true,
},
],
"name": "Sample",
"relations": Object {},
"sourceName": "Sample",
}
`);
});
test("create model relations with directive: one-to-many", () => {
const sampleModel = createModel(schemaComposer.getOTC("User"));
expect(sampleModel.relations).toMatchInlineSnapshot(`
Object {
"videos": Object {
"condition": Object {
"child": Object {
"name": "publisher",
"sourceName": "user",
},
"parent": Object {
"name": "userid",
"sourceName": "userid",
},
},
"isCollection": true,
"model": null,
"name": "videos",
"sourceName": "videos",
"type": "Video",
"unique": false,
},
}
`);
});
test("create model relations with directive: one-to-one", () => {
const sampleModel = createModel(schemaComposer.getOTC("Video"));
expect(sampleModel.relations).toMatchInlineSnapshot(`
Object {
"publisher": Object {
"condition": Object {
"child": Object {
"name": "userid",
"sourceName": "userid",
},
"parent": Object {
"name": "publisher",
"sourceName": "user",
},
},
"isCollection": false,
"model": null,
"name": "publisher",
"sourceName": "user",
"type": "User",
"unique": false,
},
}
`);
});
test("create model relations with directive: one-to-one", () => {
const sampleModel = createModel(schemaComposer.getOTC("Video"));
expect(sampleModel.relations).toMatchInlineSnapshot(`
Object {
"publisher": Object {
"condition": Object {
"child": Object {
"name": "userid",
"sourceName": "userid",
},
"parent": Object {
"name": "publisher",
"sourceName": "user",
},
},
"isCollection": false,
"model": null,
"name": "publisher",
"sourceName": "user",
"type": "User",
"unique": false,
},
}
`);
});
test("Infer one-to-many relationships from field definition", () => {
const consumer = createModel(schemaComposer.getOTC("Consumer"));
expect(consumer.relations).toMatchInlineSnapshot(`
Object {
"ratings": Object {
"condition": Object {
"child": Object {
"name": "consumer",
"sourceName": "consumer",
},
"parent": Object {
"name": "id",
"sourceName": "id",
},
},
"isCollection": true,
"model": null,
"name": "ratings",
"sourceName": "ratings",
"type": "Rating",
"unique": false,
},
}
`);
});
test("Infer one-to-one relationships from field definition", () => {
const rating = createModel(schemaComposer.getOTC("Rating"));
expect(rating.relations).toMatchInlineSnapshot(`
Object {
"consumer": Object {
"condition": Object {
"child": Object {
"name": "id",
"sourceName": "id",
},
"parent": Object {
"name": "consumer",
"sourceName": "consumer",
},
},
"isCollection": false,
"model": null,
"name": "consumer",
"sourceName": "consumer",
"type": "Consumer",
"unique": false,
},
}
`);
});
|
skimah/skimah
|
packages/api/src/resolvers/index.ts
|
<gh_stars>1-10
import { SchemaComposer, ObjectTypeComposer } from "graphql-compose";
import { Datasource, Model } from "../types";
import findResolver from "./find";
import createResolver from "./create";
import updateResolver from "./update";
import deleteResolver from "./delete";
/**
* @internal
*/
export interface ResolverDefinition {
/* eslint-disable @typescript-eslint/no-explicit-any */
composer: SchemaComposer<any>;
datasources: { [key: string]: Datasource };
type: ObjectTypeComposer;
models: { [key: string]: Model };
interfaces: { [key: string]: Model[] };
}
/**
* @internal
*/
export default (definition: ResolverDefinition): void => {
const { composer, type } = definition;
const isReadOnly = !!type.getDirectiveByName("readOnly");
// add the resolvers to the type composers
const findName = findResolver(definition);
composer.Query.addFields({
[`${findName}`]: definition.type.getResolver(findName)
});
if (!isReadOnly) {
const createName = createResolver(definition);
const updateName = updateResolver(definition);
const deleteName = deleteResolver(definition);
composer.Mutation.addFields({
[`${createName}`]: definition.type.getResolver(createName)
});
composer.Mutation.addFields({
[`${updateName}`]: definition.type.getResolver(updateName)
});
composer.Mutation.addFields({
[`${deleteName}`]: definition.type.getResolver(deleteName)
});
}
};
|
skimah/skimah
|
packages/api/src/datasource.ts
|
<filename>packages/api/src/datasource.ts
import {
Datasource,
Model,
MutationModel,
Criteria,
QueryModel
} from "./types";
export const noopSource = (): Datasource => {
return {
initialize: (_: Model[]) => Promise.resolve(null),
select: (_: QueryModel) => Promise.resolve([]),
create: (_: MutationModel[]) =>
Promise.resolve({ records: [], affected: [] }),
update: (_: Criteria) => Promise.resolve({ affected: [], records: [] }),
delete: (_: Criteria, _1: Model) =>
Promise.resolve({ records: [], affected: [] })
};
};
export const nullSource = (): Datasource => {
return {
select: (q: QueryModel) =>
Promise.reject(`No datasource configured for ${q.name}`),
create: (m: MutationModel[]) =>
Promise.reject(
`No datasource configured for ${m[0] ? m[0].name : "creating models"} `
),
update: (c: Criteria, changes: MutationModel) =>
Promise.reject(`No datasource configured for ${changes[0].name}`),
delete: (_: Criteria, m: Model) =>
Promise.reject(`No datasource configured for ${m.name}`)
};
};
|
skimah/skimah
|
packages/api/test/filter.test.ts
|
<gh_stars>1-10
import { schemaComposer, ObjectTypeComposer } from "graphql-compose";
import createInputFilter from "../src/filter";
const typeDefs = `
type User {
userid: ID
username: String
online: Boolean
height: Float
age: Int
status: Status
comments: [Comment]
}
type Comment {
id: ID
text: String
}
type Status {
id: ID
statusType: Boolean
}
`;
describe("Schema Filter", () => {
test("Operators", () => {
const ts = schemaComposer.addTypeDefs(typeDefs);
const tc = <ObjectTypeComposer>ts.get("User");
createInputFilter(tc, schemaComposer);
expect(schemaComposer.getAnyTC("UserFilter").toSDL())
.toMatchInlineSnapshot(`
"\\"\\"\\"Filter User fields\\"\\"\\"
input UserFilter {
\\"\\"\\"Filter users based on userid\\"\\"\\"
userid: IDOpr
\\"\\"\\"Filter users based on username\\"\\"\\"
username: StringOpr
\\"\\"\\"Filter users based on online\\"\\"\\"
online: BooleanOpr
\\"\\"\\"Filter users based on height\\"\\"\\"
height: FloatOpr
\\"\\"\\"Filter users based on age\\"\\"\\"
age: IntOpr
\\"\\"\\"Filter users based on status\\"\\"\\"
status: IDOpr
\\"\\"\\"Combine filters\\"\\"\\"
and: [UserFilter!]
\\"\\"\\"Combine filters\\"\\"\\"
or: [UserFilter!]
}"
`);
});
test("Scalar", () => {
const ts = schemaComposer.addTypeDefs(typeDefs);
const tc = <ObjectTypeComposer>ts.get("User");
createInputFilter(tc, schemaComposer);
expect(schemaComposer.getAnyTC("IDOpr").toSDL()).toMatchInlineSnapshot(`
"\\"\\"\\"Filter input based on ID\\"\\"\\"
input IDOpr {
eq: ID
ne: ID
in: [ID!]
nin: [ID!]
}"
`);
expect(schemaComposer.getAnyTC("StringOpr").toSDL()).toMatchInlineSnapshot(`
"\\"\\"\\"Filter input based on String\\"\\"\\"
input StringOpr {
eq: String
ne: String
like: String
in: [String!]
nin: [String!]
}"
`);
expect(schemaComposer.getAnyTC("BooleanOpr").toSDL())
.toMatchInlineSnapshot(`
"\\"\\"\\"Filter input based on Boolean\\"\\"\\"
input BooleanOpr {
eq: Boolean
ne: Boolean
}"
`);
expect(schemaComposer.getAnyTC("IntOpr").toSDL()).toMatchInlineSnapshot(`
"\\"\\"\\"Filter input based on Int\\"\\"\\"
input IntOpr {
eq: Int
ne: Int
lte: Int
lt: Int
in: [Int!]
nin: [Int!]
gte: Int
gt: Int
}"
`);
expect(schemaComposer.getAnyTC("FloatOpr").toSDL()).toMatchInlineSnapshot(`
"\\"\\"\\"Filter input based on Float\\"\\"\\"
input FloatOpr {
eq: Float
ne: Float
lte: Float
lt: Float
gte: Float
gt: Float
}"
`);
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.