Fix build setup

pull/219/head
Candid Dauth 2023-09-12 13:31:55 +02:00
rodzic b83d3ba1dd
commit 06493182d4
42 zmienionych plików z 3945 dodań i 6346 usunięć

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Wyświetl plik

@ -3,5 +3,7 @@ nodeLinker: node-modules
plugins: plugins:
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs - path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
spec: "@yarnpkg/plugin-interactive-tools" spec: "@yarnpkg/plugin-interactive-tools"
- path: .yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs
spec: "@yarnpkg/plugin-workspace-tools"
yarnPath: .yarn/releases/yarn-3.5.0.cjs yarnPath: .yarn/releases/yarn-3.6.3.cjs

Wyświetl plik

@ -38,11 +38,11 @@
"devDependencies": { "devDependencies": {
"@types/geojson": "^7946.0.7", "@types/geojson": "^7946.0.7",
"rimraf": "^3.0.2", "rimraf": "^3.0.2",
"source-map-loader": "^3.0.0", "source-map-loader": "^4.0.1",
"ts-loader": "^9.2.2", "ts-loader": "^9.4.4",
"typescript": "^4.1.3", "typescript": "^5.2.2",
"webpack": "^5.37.1", "webpack": "^5.88.2",
"webpack-bundle-analyzer": "^4.4.2", "webpack-bundle-analyzer": "^4.9.1",
"webpack-cli": "^4.2.0" "webpack-cli": "^5.1.4"
} }
} }

Wyświetl plik

@ -540,7 +540,7 @@ export default class Client<DataType = Record<string, string>> {
try { try {
const obj = await this._emit("setPadId", padId); const obj = await this._emit("setPadId", padId);
this._receiveMultiple(obj); this._receiveMultiple(obj);
} catch(err) { } catch(err: any) {
this._set(this, 'serverError', err); this._set(this, 'serverError', err);
this._simulateEvent("serverError", err); this._simulateEvent("serverError", err);
throw err; throw err;

Wyświetl plik

@ -1,6 +1,6 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "es3", "target": "es5",
"esModuleInterop": true, "esModuleInterop": true,
"strict": true, "strict": true,
"sourceMap": true, "sourceMap": true,

Wyświetl plik

@ -21,6 +21,8 @@ services:
MYSQL_USER: facilmap MYSQL_USER: facilmap
MYSQL_PASSWORD: facilmap MYSQL_PASSWORD: facilmap
MYSQL_RANDOM_ROOT_PASSWORD: "true" MYSQL_RANDOM_ROOT_PASSWORD: "true"
ports:
- "127.0.0.1:40830:3306"
phpmyadmin: phpmyadmin:
image: phpmyadmin image: phpmyadmin
links: links:

Wyświetl plik

@ -63,7 +63,7 @@
"popper-max-size-modifier": "^0.2.0", "popper-max-size-modifier": "^0.2.0",
"portal-vue": "^2.1.7", "portal-vue": "^2.1.7",
"tablesorter": "^2.31.3", "tablesorter": "^2.31.3",
"vee-validate": "^3.4.5", "vee-validate": "3",
"vue": "^2.6.12", "vue": "^2.6.12",
"vue-class-component": "^7.2.6", "vue-class-component": "^7.2.6",
"vue-color": "^2.8.1", "vue-color": "^2.8.1",
@ -86,29 +86,30 @@
"@types/webpack-bundle-analyzer": "^4.4.0", "@types/webpack-bundle-analyzer": "^4.4.0",
"@types/webpack-dev-server": "^3.11.4", "@types/webpack-dev-server": "^3.11.4",
"@types/webpack-node-externals": "^2.5.1", "@types/webpack-node-externals": "^2.5.1",
"copy-webpack-plugin": "^9.0.0", "copy-webpack-plugin": "^11.0.0",
"css-loader": "^5.2.5", "css-loader": "^6.8.1",
"ejs-compiled-loader": "^3.1.0", "ejs-compiled-loader": "^3.1.0",
"html-loader": "^2.1.2", "html-loader": "^4.2.0",
"html-webpack-plugin": "^5.3.1", "html-webpack-plugin": "^5.5.3",
"jest": "^26.6.3", "jest": "^26.6.3",
"mini-svg-data-uri": "^1.3.3", "mini-svg-data-uri": "^1.3.3",
"rimraf": "^5.0.1",
"sass": "^1.34.0", "sass": "^1.34.0",
"sass-loader": "^11.1.1", "sass-loader": "^13.3.2",
"source-map-loader": "^3.0.0", "source-map-loader": "^4.0.1",
"style-loader": "^2.0.0", "style-loader": "^3.3.3",
"svgo": "^2.2.2", "svgo": "^2.2.2",
"ts-jest": "^26.5.4", "ts-jest": "^26.5.4",
"ts-loader": "^9.2.2", "ts-loader": "^9.4.4",
"ts-node": "^9.1.1", "ts-node": "^9.1.1",
"typescript": "^4.2.3", "typescript": "^5.2.2",
"vue-template-compiler": "^2.6.12", "vue-template-compiler": "^2.6.12",
"vue-template-loader": "^1.1.0", "vue-template-loader": "^1.1.0",
"webpack": "^5.37.1", "webpack": "^5.88.2",
"webpack-bundle-analyzer": "^4.4.2", "webpack-bundle-analyzer": "^4.9.1",
"webpack-cli": "^4.2.0", "webpack-cli": "^5.1.4",
"webpack-dev-server": "^3.11.2", "webpack-dev-server": "^4.15.1",
"webpack-hot-middleware": "^2.24.3", "webpack-hot-middleware": "^2.25.4",
"webpack-node-externals": "^3.0.0" "webpack-node-externals": "^3.0.0"
} }
} }

Wyświetl plik

@ -15,6 +15,7 @@ import { flyTo, getZoomDestinationForLine } from "../../utils/zoom";
import RouteForm from "../route-form/route-form"; import RouteForm from "../route-form/route-form";
import StringMap from "../../utils/string-map"; import StringMap from "../../utils/string-map";
import { Context } from "../facilmap/facilmap"; import { Context } from "../facilmap/facilmap";
import saveAs from "file-saver";
@WithRender @WithRender
@Component({ @Component({

Wyświetl plik

@ -342,7 +342,7 @@ export default class RouteForm extends Vue {
if(dest.selectedSuggestion == null) if(dest.selectedSuggestion == null)
Vue.set(dest, "selectedSuggestion", this.getSelectedSuggestion(dest)); Vue.set(dest, "selectedSuggestion", this.getSelectedSuggestion(dest));
} catch (err) { } catch (err: any) {
if(query != dest.loadingQuery) if(query != dest.loadingQuery)
return; // The destination has changed in the meantime return; // The destination has changed in the meantime

Wyświetl plik

@ -13,7 +13,7 @@ import Icon from "../icon/icon";
}) })
export default class Coordinates extends Vue { export default class Coordinates extends Vue {
@Prop({ type: String }) point!: Point; @Prop({ type: Object }) point!: Point;
get formattedCoordinates(): string { get formattedCoordinates(): string {
return `${round(this.point.lat, 5)}, ${round(this.point.lon, 5)}`; return `${round(this.point.lat, 5)}, ${round(this.point.lon, 5)}`;

Wyświetl plik

@ -1,5 +1,7 @@
import { extend, withValidation } from "vee-validate"; import { extend } from "vee-validate";
import Vue from "vue"; import Vue from "vue";
import { ValidationContext as OriginalValidationContext } from "vee-validate/dist/types/components/common";
import { ValidationFlags } from "vee-validate/dist/types/types";
extend("required", { extend("required", {
validate: (val: any) => !!val, validate: (val: any) => !!val,
@ -7,7 +9,13 @@ extend("required", {
computesRequired: true computesRequired: true
}); });
export type ValidationContext = Parameters<Exclude<Parameters<typeof withValidation>[1], undefined>>[0]; // ValidationContext extends Pick<ValidationFlags, KnownKeys<ValidationFlags>>, but the KnownKeys type is broken.
// This is a replacement from https://github.com/slackapi/bolt-js/issues/951#issuecomment-857308100
type OmitIndexSignature<T> = {
[K in keyof T as string extends K ? never : number extends K ? never : K]: T[K];
};
export type ValidationContext = OriginalValidationContext & OmitIndexSignature<ValidationFlags>;
export function getValidationState(v: ValidationContext, showValid = false): boolean | null { export function getValidationState(v: ValidationContext, showValid = false): boolean | null {
if (v.dirty || v.validated) if (v.dirty || v.validated)

Wyświetl plik

@ -68,24 +68,24 @@
"@types/webpack-node-externals": "^2.5.0", "@types/webpack-node-externals": "^2.5.0",
"@types/yauzl": "^2.9.1", "@types/yauzl": "^2.9.1",
"cheerio": "^1.0.0-rc.5", "cheerio": "^1.0.0-rc.5",
"css-loader": "^5.2.5", "css-loader": "^6.8.1",
"expose-loader": "^3.0.0", "expose-loader": "^4.1.0",
"highland": "^2.13.5", "highland": "^2.13.5",
"jest": "^26.6.3", "jest": "^26.6.3",
"node-fetch": "^2.6.1", "node-fetch": "^2.6.1",
"rimraf": "^3.0.2", "rimraf": "^3.0.2",
"sass-loader": "^11.1.1", "sass-loader": "^13.3.2",
"source-map-loader": "^3.0.0", "source-map-loader": "^4.0.1",
"style-loader": "^2.0.0", "style-loader": "^3.3.3",
"svgo": "^2.2.2", "svgo": "^2.2.2",
"ts-jest": "^26.5.4", "ts-jest": "^26.5.4",
"ts-loader": "^9.2.2", "ts-loader": "^9.4.4",
"ts-node": "^9.1.1", "ts-node": "^9.1.1",
"typescript": "^4.2.3", "typescript": "^5.2.2",
"webpack": "^5.37.1", "webpack": "^5.88.2",
"webpack-bundle-analyzer": "^4.4.2", "webpack-bundle-analyzer": "^4.9.1",
"webpack-cli": "^4.5.0", "webpack-cli": "^5.1.4",
"webpack-dev-server": "^3.11.2", "webpack-dev-server": "^4.15.1",
"webpack-node-externals": "^3.0.0", "webpack-node-externals": "^3.0.0",
"yauzl": "^2.10.0" "yauzl": "^2.10.0"
}, },

Wyświetl plik

@ -11,7 +11,7 @@ interface LinesLayerOptions extends LayerOptions {
export default class LinesLayer extends FeatureGroup { export default class LinesLayer extends FeatureGroup {
options!: LayerOptions; declare options: LayerOptions;
client: Client<any>; client: Client<any>;
linesById: Record<string, InstanceType<typeof HighlightablePolyline>> = {}; linesById: Record<string, InstanceType<typeof HighlightablePolyline>> = {};
highlightedLinesIds = new Set<ID>(); highlightedLinesIds = new Set<ID>();

Wyświetl plik

@ -16,7 +16,7 @@ export interface MarkerLayerOptions extends MarkerOptions {
export default class MarkerLayer extends LeafletMarker { export default class MarkerLayer extends LeafletMarker {
options!: MarkerLayerOptions; declare options: MarkerLayerOptions;
_fmDragging: boolean = false; _fmDragging: boolean = false;
_fmDraggingMouseEvent?: LeafletMouseEvent; _fmDraggingMouseEvent?: LeafletMouseEvent;

Wyświetl plik

@ -11,7 +11,7 @@ export interface MarkersLayerOptions extends MarkerClusterOptions {
export default class MarkersLayer extends MarkerCluster { export default class MarkersLayer extends MarkerCluster {
options!: MarkersLayerOptions; declare options: MarkersLayerOptions;
client: Client<any>; client: Client<any>;
markersById: Record<string, MarkerLayer> = {}; markersById: Record<string, MarkerLayer> = {};
highlightedMarkerIds = new Set<ID>(); highlightedMarkerIds = new Set<ID>();

Wyświetl plik

@ -34,7 +34,7 @@ export interface OverpassLayerOptions extends LayerOptions {
export default class OverpassLayer extends FeatureGroup { export default class OverpassLayer extends FeatureGroup {
options!: OverpassLayerOptions; declare options: OverpassLayerOptions;
_highlightedElements = new Set<string>(); _highlightedElements = new Set<string>();
_query: string | OverpassPreset[] | undefined; _query: string | OverpassPreset[] | undefined;
_lastRequestController?: AbortController; _lastRequestController?: AbortController;
@ -147,7 +147,7 @@ export default class OverpassLayer extends FeatureGroup {
for (const element of elements) for (const element of elements)
this.addLayer(this._elementToLayer(element)); this.addLayer(this._elementToLayer(element));
this.fire("loadend", { status: elements.length < this.options.limit! ? OverpassLoadStatus.COMPLETE : OverpassLoadStatus.INCOMPLETE }); this.fire("loadend", { status: elements.length < this.options.limit! ? OverpassLoadStatus.COMPLETE : OverpassLoadStatus.INCOMPLETE });
} catch (error) { } catch (error: any) {
if (error.name == "AbortError") { if (error.name == "AbortError") {
this.fire("loadend", { status: OverpassLoadStatus.ABORTED }); this.fire("loadend", { status: OverpassLoadStatus.ABORTED });
return; return;

Wyświetl plik

@ -45,7 +45,7 @@ export async function validateOverpassQuery(query: string, signal?: AbortSignal)
try { try {
await getOverpassElements(query, latLngBounds([0, 0], [0, 0]), 1, 1, signal); await getOverpassElements(query, latLngBounds([0, 0], [0, 0]), 1, 1, signal);
return undefined; return undefined;
} catch (e) { } catch (e: any) {
return e.message; return e.message;
} }
} }

Wyświetl plik

@ -7,7 +7,7 @@ interface RouteDragHandlerOptions extends DraggableLinesHandlerOptions {
export default class RouteDragHandler extends DraggableLines { export default class RouteDragHandler extends DraggableLines {
realOptions!: RouteDragHandlerOptions; declare realOptions: RouteDragHandlerOptions;
client: Client<any>; client: Client<any>;
constructor(map: Map, client: Client<any>, options?: RouteDragHandlerOptions) { constructor(map: Map, client: Client<any>, options?: RouteDragHandlerOptions) {

Wyświetl plik

@ -10,7 +10,7 @@ interface RouteLayerOptions extends HighlightableLayerOptions<PolylineOptions> {
export default class RouteLayer extends HighlightablePolyline { export default class RouteLayer extends HighlightablePolyline {
realOptions!: RouteLayerOptions; declare realOptions: RouteLayerOptions;
client: Client<any>; client: Client<any>;
routeId: string | undefined; routeId: string | undefined;

Wyświetl plik

@ -12,7 +12,7 @@ interface SearchResultGeoJSONOptions extends GeoJSONOptions {
export default class SearchResultGeoJSON extends GeoJSONLayer { export default class SearchResultGeoJSON extends GeoJSONLayer {
options!: SearchResultGeoJSONOptions; declare options: SearchResultGeoJSONOptions;
constructor(geojson: GeoJSON, options?: SearchResultGeoJSONOptions) { constructor(geojson: GeoJSON, options?: SearchResultGeoJSONOptions) {
super(geojson, options); super(geojson, options);

Wyświetl plik

@ -19,7 +19,7 @@ interface SearchResultsLayerOptions extends LayerOptions {
export default class SearchResultsLayer extends FeatureGroup { export default class SearchResultsLayer extends FeatureGroup {
options!: SearchResultsLayerOptions; declare options: SearchResultsLayerOptions;
highlightedResults = new Set<SearchResult>(); highlightedResults = new Set<SearchResult>();
constructor(results?: SearchResult[], options?: SearchResultsLayerOptions) { constructor(results?: SearchResult[], options?: SearchResultsLayerOptions) {

Wyświetl plik

@ -11,15 +11,15 @@
], ],
"scripts": { "scripts": {
"lint": "eslint **/*.ts", "lint": "eslint **/*.ts",
"clean": "yarn workspaces run clean", "clean": "yarn workspaces foreach -v run clean",
"build": "yarn workspaces run build" "build": "yarn workspaces foreach -vt run build"
}, },
"devDependencies": { "devDependencies": {
"@typescript-eslint/eslint-plugin": "^4.24.0", "@typescript-eslint/eslint-plugin": "^4.24.0",
"@typescript-eslint/parser": "^4.24.0", "@typescript-eslint/parser": "^4.24.0",
"eslint": "^7.27.0", "eslint": "^8.49.0",
"eslint-plugin-import": "^2.23.3" "eslint-plugin-import": "^2.28.1"
}, },
"version": "0.0.0", "version": "0.0.0",
"packageManager": "yarn@3.5.0" "packageManager": "yarn@3.6.3"
} }

Wyświetl plik

@ -35,9 +35,7 @@
"types": "tsc --noEmit src/**/*.ts", "types": "tsc --noEmit src/**/*.ts",
"lint": "eslint src/**/*.ts" "lint": "eslint src/**/*.ts"
}, },
"bin": { "bin": "./dist/server.js",
"facilmap-server": "./dist/server.js"
},
"dependencies": { "dependencies": {
"@mapbox/polyline": "^1.1.1", "@mapbox/polyline": "^1.1.1",
"async": "^3.2.0", "async": "^3.2.0",
@ -97,9 +95,9 @@
"rimraf": "^3.0.2", "rimraf": "^3.0.2",
"ts-jest": "^26.4.4", "ts-jest": "^26.4.4",
"ts-node": "^9.1.1", "ts-node": "^9.1.1",
"typescript": "^4.1.3", "typescript": "^5.2.2",
"webpack": "^5.37.1", "webpack": "^5.88.2",
"webpack-dev-middleware": "^4.3.0", "webpack-dev-middleware": "^6.1.1",
"webpack-hot-middleware": "^2.25.0" "webpack-hot-middleware": "^2.25.4"
} }
} }

Wyświetl plik

@ -1,14 +1,28 @@
import highland from "highland"; import highland from "highland";
import { streamEachPromise } from "../utils/streams"; import { streamEachPromise } from "../utils/streams";
import { clone } from "../utils/utils"; import { clone } from "../utils/utils";
import { AssociationOptions, Model, ModelAttributeColumnOptions, ModelCtor, WhereOptions, DataTypes, FindOptions, Op, Sequelize } from "sequelize"; import { AssociationOptions, Model, ModelAttributeColumnOptions, ModelCtor, WhereOptions, DataTypes, FindOptions, Op, Sequelize, ModelStatic, InferAttributes, InferCreationAttributes, CreationAttributes } from "sequelize";
import { Line, Marker, PadId, ID, LineUpdate, MarkerUpdate, Type, Bbox } from "facilmap-types"; import { Line, Marker, PadId, ID, LineUpdate, MarkerUpdate, Type, Bbox } from "facilmap-types";
import Database from "./database"; import Database from "./database";
import { isEqual } from "lodash"; import { isEqual } from "lodash";
import { calculateRouteForLine } from "../routing/routing"; import { calculateRouteForLine } from "../routing/routing";
import { PadModel } from "./pad";
const ITEMS_PER_BATCH = 5000; const ITEMS_PER_BATCH = 5000;
// Workaround for https://github.com/sequelize/sequelize/issues/15898
export function createModel<ModelInstance extends Model<any, any>>(): ModelStatic<ModelInstance> {
return class extends Model {} as any;
}
export function getDefaultIdType(): ModelAttributeColumnOptions {
return {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
};
}
export function getVirtualLatType(): ModelAttributeColumnOptions { export function getVirtualLatType(): ModelAttributeColumnOptions {
return { return {
type: DataTypes.VIRTUAL, type: DataTypes.VIRTUAL,
@ -74,13 +88,14 @@ export function getLonType(): ModelAttributeColumnOptions {
export const validateColour = { is: /^[a-fA-F0-9]{3}([a-fA-F0-9]{3})?$/ }; export const validateColour = { is: /^[a-fA-F0-9]{3}([a-fA-F0-9]{3})?$/ };
export class DataModel extends Model { export interface DataModel extends Model<InferAttributes<DataModel>, InferCreationAttributes<DataModel>> {
id!: ID; id: ID;
name!: string; name: string;
value!: string; value: string;
} }
export const dataDefinition = { export const dataDefinition = {
id: getDefaultIdType(),
"name" : { type: DataTypes.TEXT, allowNull: false }, "name" : { type: DataTypes.TEXT, allowNull: false },
"value" : { type: DataTypes.TEXT, allowNull: false } "value" : { type: DataTypes.TEXT, allowNull: false }
}; };
@ -265,7 +280,7 @@ export default class DatabaseHelpers {
condition.include = [ ...(condition.include ? (Array.isArray(condition.include) ? condition.include : [ condition.include ]) : [ ]), this._db._conn.model(type + "Data") ]; condition.include = [ ...(condition.include ? (Array.isArray(condition.include) ? condition.include : [ condition.include ]) : [ ]), this._db._conn.model(type + "Data") ];
} }
const Pad = this._db.pads.PadModel.build({ id: padId }); const Pad = this._db.pads.PadModel.build({ id: padId } satisfies Partial<CreationAttributes<PadModel>> as any);
const objs: Array<Model> = await (Pad as any)["get" + this._db._conn.model(type).getTableName()](condition); const objs: Array<Model> = await (Pad as any)["get" + this._db._conn.model(type).getTableName()](condition);
return objs.map((obj) => { return objs.map((obj) => {

Wyświetl plik

@ -1,30 +1,26 @@
import { clone } from "../utils/utils"; import { clone } from "../utils/utils";
import { Model, DataTypes, FindOptions } from "sequelize"; import { Model, DataTypes, FindOptions, InferAttributes, CreationOptional, ForeignKey, InferCreationAttributes } from "sequelize";
import Database from "./database"; import Database from "./database";
import { HistoryEntry, HistoryEntryAction, HistoryEntryCreate, HistoryEntryType, ID, PadId } from "facilmap-types"; import { HistoryEntry, HistoryEntryAction, HistoryEntryCreate, HistoryEntryType, ID, PadData, PadId } from "facilmap-types";
import { makeNotNullForeignKey } from "./helpers"; import { createModel, getDefaultIdType, makeNotNullForeignKey } from "./helpers";
function createHistoryModel() { interface HistoryModel extends Model<InferAttributes<HistoryModel>, InferCreationAttributes<HistoryModel>> {
return class HistoryModel extends Model { id: CreationOptional<ID>;
id!: ID; time: Date;
time!: Date; type: HistoryEntryType;
type!: HistoryEntryType; action: HistoryEntryAction;
action!: HistoryEntryAction; objectId: ID;
objectId!: ID; objectBefore: string | null;
objectBefore!: string | null; objectAfter: string | null;
objectAfter!: string | null; padId: ForeignKey<PadData["id"]>;
padId!: PadId; toJSON: () => HistoryEntry;
toJSON!: () => HistoryEntry;
};
} }
type HistoryModel = InstanceType<ReturnType<typeof createHistoryModel>>;
export default class DatabaseHistory { export default class DatabaseHistory {
HISTORY_ENTRIES = 50; HISTORY_ENTRIES = 50;
HistoryModel = createHistoryModel(); HistoryModel = createModel<HistoryModel>();
_db: Database; _db: Database;
@ -32,6 +28,7 @@ export default class DatabaseHistory {
this._db = database; this._db = database;
this.HistoryModel.init({ this.HistoryModel.init({
id: getDefaultIdType(),
time: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW }, time: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW },
type: { type: DataTypes.ENUM("Marker", "Line", "View", "Type", "Pad"), allowNull: false }, type: { type: DataTypes.ENUM("Marker", "Line", "View", "Type", "Pad"), allowNull: false },
action: { type: DataTypes.ENUM("create", "update", "delete"), allowNull: false }, action: { type: DataTypes.ENUM("create", "update", "delete"), allowNull: false },

Wyświetl plik

@ -1,63 +1,58 @@
import { DataTypes, HasManyGetAssociationsMixin, Model, Op } from "sequelize"; import { CreationAttributes, CreationOptional, DataTypes, ForeignKey, HasManyGetAssociationsMixin, InferAttributes, InferCreationAttributes, Model, Op } from "sequelize";
import { BboxWithZoom, ID, Latitude, Line, LineCreate, ExtraInfo, LineUpdate, Longitude, PadId, Point, Route, TrackPoint } from "facilmap-types"; import { BboxWithZoom, ID, Latitude, Line, LineCreate, ExtraInfo, LineUpdate, Longitude, PadId, Point, Route, TrackPoint } from "facilmap-types";
import Database from "./database"; import Database from "./database";
import { BboxWithExcept, dataDefinition, DataModel, getLatType, getLonType, getPosType, getVirtualLatType, getVirtualLonType, makeBboxCondition, makeNotNullForeignKey, validateColour } from "./helpers"; import { BboxWithExcept, createModel, dataDefinition, DataModel, getDefaultIdType, getLatType, getLonType, getPosType, getVirtualLatType, getVirtualLonType, makeBboxCondition, makeNotNullForeignKey, validateColour } from "./helpers";
import { groupBy, isEqual, mapValues, omit } from "lodash"; import { groupBy, isEqual, mapValues, omit } from "lodash";
import { wrapAsync } from "../utils/streams"; import { wrapAsync } from "../utils/streams";
import { calculateRouteForLine } from "../routing/routing"; import { calculateRouteForLine } from "../routing/routing";
import { PadModel } from "./pad";
import { Point as GeoJsonPoint } from "geojson";
import { TypeModel } from "./type";
export type LineWithTrackPoints = Line & { export type LineWithTrackPoints = Line & {
trackPoints: TrackPoint[]; trackPoints: TrackPoint[];
} }
function createLineModel() { export interface LineModel extends Model<InferAttributes<LineModel>, InferCreationAttributes<LineModel>> {
return class LineModel extends Model { id: CreationOptional<ID>;
id!: ID; padId: ForeignKey<PadModel["id"]>;
padId!: PadId; routePoints: string;
routePoints!: string; typeId: ForeignKey<TypeModel["id"]>;
mode!: string; mode: CreationOptional<string>;
colour!: string; colour: CreationOptional<string>;
width!: number; width: CreationOptional<number>;
name!: string | null; name: CreationOptional<string | null>;
distance!: number | null; distance: CreationOptional<number | null>;
time!: number | null; time: CreationOptional<number | null>;
ascent!: number | null; ascent: CreationOptional<number | null>;
descent!: number | null; descent: CreationOptional<number | null>;
top!: Latitude; top: Latitude;
bottom!: Latitude; bottom: Latitude;
left!: Longitude; left: Longitude;
right!: Longitude; right: Longitude;
extraInfo!: string | null; extraInfo: CreationOptional<string | null>;
getLinePoints!: HasManyGetAssociationsMixin<LinePointModel>; getLinePoints: HasManyGetAssociationsMixin<LinePointModel>;
toJSON!: () => Line; toJSON: () => Line;
}
} }
function createLinePointModel() { export interface LinePointModel extends Model<InferAttributes<LinePointModel>, InferCreationAttributes<LinePointModel>> {
return class LinePointModel extends Model { id: CreationOptional<ID>;
id!: ID; lineId: ForeignKey<LineModel["id"]>;
lat!: Latitude; pos: GeoJsonPoint;
lon!: Longitude; lat: Latitude;
zoom!: number; lon: Longitude;
idx!: number; zoom: number;
ele!: number | null; idx: number;
toJSON!: () => TrackPoint; ele: number | null;
}; toJSON: () => TrackPoint;
} }
function createLineDataModel() {
return class LineData extends DataModel {};
}
export type LineModel = InstanceType<ReturnType<typeof createLineModel>>;
export type LinePointModel = InstanceType<ReturnType<typeof createLinePointModel>>;
export default class DatabaseLines { export default class DatabaseLines {
LineModel = createLineModel(); LineModel = createModel<LineModel>();
LinePointModel = createLinePointModel(); LinePointModel = createModel<LinePointModel>();
LineDataModel = createLineDataModel(); LineDataModel = createModel<DataModel>();
_db: Database; _db: Database;
@ -65,6 +60,7 @@ export default class DatabaseLines {
this._db = database; this._db = database;
this.LineModel.init({ this.LineModel.init({
id: getDefaultIdType(),
routePoints : { routePoints : {
type: DataTypes.TEXT, type: DataTypes.TEXT,
allowNull: false, allowNull: false,
@ -118,6 +114,7 @@ export default class DatabaseLines {
}); });
this.LinePointModel.init({ this.LinePointModel.init({
id: getDefaultIdType(),
lat: getVirtualLatType(), lat: getVirtualLatType(),
lon: getVirtualLonType(), lon: getVirtualLonType(),
pos: getPosType(), pos: getPosType(),
@ -172,7 +169,7 @@ export default class DatabaseLines {
async getLineTemplate(padId: PadId, data: { typeId: ID }): Promise<Line> { async getLineTemplate(padId: PadId, data: { typeId: ID }): Promise<Line> {
const lineTemplate = { const lineTemplate = {
...this.LineModel.build({ ...data, padId: padId }).toJSON(), ...this.LineModel.build({ ...data, padId: padId } satisfies Partial<CreationAttributes<LineModel>> as any).toJSON(),
data: { } data: { }
} as Line; } as Line;
@ -296,7 +293,7 @@ export default class DatabaseLines {
} }
async getAllLinePoints(lineId: ID): Promise<TrackPoint[]> { async getAllLinePoints(lineId: ID): Promise<TrackPoint[]> {
const points = await this.LineModel.build({ id: lineId }).getLinePoints({ const points = await this.LineModel.build({ id: lineId } satisfies Partial<CreationAttributes<LineModel>> as any).getLinePoints({
attributes: [ "pos", "lat", "lon", "ele", "zoom", "idx" ], attributes: [ "pos", "lat", "lon", "ele", "zoom", "idx" ],
order: [["idx", "ASC"]] order: [["idx", "ASC"]]
}); });

Wyświetl plik

@ -1,35 +1,32 @@
import { DataTypes, Model } from "sequelize"; import { CreationOptional, DataTypes, ForeignKey, InferAttributes, InferCreationAttributes, Model } from "sequelize";
import { BboxWithZoom, ID, Latitude, Longitude, Marker, MarkerCreate, MarkerUpdate, PadId } from "facilmap-types"; import { BboxWithZoom, ID, Latitude, Longitude, Marker, MarkerCreate, MarkerUpdate, PadId } from "facilmap-types";
import { BboxWithExcept, dataDefinition, DataModel, getPosType, getVirtualLatType, getVirtualLonType, makeBboxCondition, makeNotNullForeignKey, validateColour } from "./helpers"; import { BboxWithExcept, createModel, dataDefinition, DataModel, getDefaultIdType, getPosType, getVirtualLatType, getVirtualLonType, makeBboxCondition, makeNotNullForeignKey, validateColour } from "./helpers";
import Database from "./database"; import Database from "./database";
import { getElevationForPoint } from "../elevation"; import { getElevationForPoint } from "../elevation";
import { PadModel } from "./pad";
import { Point as GeoJsonPoint } from "geojson";
import { TypeModel } from "./type";
function createMarkerModel() { export interface MarkerModel extends Model<InferAttributes<MarkerModel>, InferCreationAttributes<MarkerModel>> {
return class MarkerModel extends Model { id: CreationOptional<ID>;
id!: ID; padId: ForeignKey<PadModel["id"]>;
padId!: PadId; pos: GeoJsonPoint;
lat!: Latitude; lat: Latitude;
lon!: Longitude; lon: Longitude;
name!: string | null; name: string | null;
colour!: string; typeId: ForeignKey<TypeModel["id"]>;
size!: number; colour: string;
symbol!: string | null; size: number;
shape!: string | null; symbol: string | null;
ele!: number | null; shape: string | null;
toJSON!: () => Marker; ele: number | null;
}; toJSON: () => Marker;
} }
function createMarkerDataModel() {
return class MarkerData extends DataModel {};
}
export type MarkerModel = InstanceType<ReturnType<typeof createMarkerModel>>;
export default class DatabaseMarkers { export default class DatabaseMarkers {
MarkerModel = createMarkerModel(); MarkerModel = createModel<MarkerModel>();
MarkerDataModel = createMarkerDataModel(); MarkerDataModel = createModel<DataModel>();
_db: Database; _db: Database;
@ -37,6 +34,7 @@ export default class DatabaseMarkers {
this._db = database; this._db = database;
this.MarkerModel.init({ this.MarkerModel.init({
id: getDefaultIdType(),
lat: getVirtualLatType(), lat: getVirtualLatType(),
lon: getVirtualLonType(), lon: getVirtualLonType(),
pos: getPosType(), pos: getPosType(),

Wyświetl plik

@ -1,16 +1,15 @@
import { DataTypes, Model } from "sequelize"; import { DataTypes, InferAttributes, InferCreationAttributes, Model } from "sequelize";
import Database from "./database"; import Database from "./database";
import { createModel } from "./helpers";
function createMetaModel() { interface MetaModel extends Model<InferAttributes<MetaModel>, InferCreationAttributes<MetaModel>> {
return class MetaModel extends Model { key: string;
key!: string; value: string;
value!: string;
};
} }
export default class DatabaseMeta { export default class DatabaseMeta {
MetaModel = createMetaModel(); MetaModel = createModel<MetaModel>();
_db: Database; _db: Database;

Wyświetl plik

@ -1,11 +1,11 @@
import { clone, generateRandomId, promiseProps } from "../utils/utils"; import { clone, generateRandomId, promiseProps } from "../utils/utils";
import { streamEachPromise } from "../utils/streams"; import { streamEachPromise } from "../utils/streams";
import Sequelize, { DataTypes } from "sequelize"; import Sequelize, { CreationAttributes, DataTypes } from "sequelize";
import { isEqual } from "lodash"; import { isEqual } from "lodash";
import Database from "./database"; import Database from "./database";
import { PadModel } from "./pad"; import { PadModel } from "./pad";
import { Line, Marker } from "facilmap-types"; import { Line, Marker } from "facilmap-types";
import { LinePointModel } from "./line"; import { LineModel, LinePointModel } from "./line";
import { getElevationForPoints } from "../elevation"; import { getElevationForPoints } from "../elevation";
const Op = Sequelize.Op; const Op = Sequelize.Op;
@ -163,7 +163,7 @@ export default class DatabaseMigrations {
const lines = await this._db.lines.LineModel.findAll(); const lines = await this._db.lines.LineModel.findAll();
for(const line of lines) { for(const line of lines) {
const trackPoints = await this._db.lines.LineModel.build({ id: line.id }).getLinePoints(); const trackPoints = await this._db.lines.LineModel.build({ id: line.id } satisfies Partial<CreationAttributes<LineModel>> as any).getLinePoints();
await this._db.lines._setLinePoints(line.padId, line.id, trackPoints, true); await this._db.lines._setLinePoints(line.padId, line.id, trackPoints, true);
} }

Wyświetl plik

@ -1,28 +1,25 @@
import { DataTypes, Model, Op, Sequelize } from "sequelize"; import { DataTypes, InferAttributes, InferCreationAttributes, Model, Op, Sequelize } from "sequelize";
import { FindPadsQuery, FindPadsResult, PadData, PadDataCreate, PadDataUpdate, PadId, PagedResults } from "facilmap-types"; import { FindPadsQuery, FindPadsResult, PadData, PadDataCreate, PadDataUpdate, PadId, PagedResults } from "facilmap-types";
import Database from "./database"; import Database from "./database";
import { streamEachPromise } from "../utils/streams"; import { streamEachPromise } from "../utils/streams";
import { createModel } from "./helpers";
function createPadModel() { export interface PadModel extends Model<InferAttributes<PadModel>, InferCreationAttributes<PadModel>> {
return class PadModel extends Model { id: PadId;
id!: PadId; name: string;
name!: string; writeId: PadId;
writeId!: PadId; adminId: PadId;
adminId!: PadId; searchEngines: boolean;
searchEngines!: boolean; description: string;
description!: string; clusterMarkers: boolean;
clusterMarkers!: boolean; legend1: string;
legend1!: string; legend2: string;
legend2!: string; toJSON: () => PadData;
toJSON!: () => PadData; };
};
}
export type PadModel = InstanceType<ReturnType<typeof createPadModel>>;
export default class DatabasePads { export default class DatabasePads {
PadModel = createPadModel(); PadModel = createModel<PadModel>();
_db: Database; _db: Database;

Wyświetl plik

@ -1,24 +1,23 @@
import { generateRandomId } from "../utils/utils"; import { generateRandomId } from "../utils/utils";
import { DataTypes, Model, Op } from "sequelize"; import { DataTypes, InferAttributes, InferCreationAttributes, Model, Op, WhereOptions } from "sequelize";
import Database from "./database"; import Database from "./database";
import { BboxWithZoom, ID, Latitude, Longitude, PadId, Point, Route, RouteMode, TrackPoint } from "facilmap-types"; import { BboxWithZoom, ID, Latitude, Longitude, PadId, Point, Route, RouteMode, TrackPoint } from "facilmap-types";
import { BboxWithExcept, getPosType, getVirtualLatType, getVirtualLonType, makeBboxCondition } from "./helpers"; import { BboxWithExcept, createModel, getPosType, getVirtualLatType, getVirtualLonType, makeBboxCondition } from "./helpers";
import { WhereOptions } from "sequelize/types/lib/model";
import { calculateRouteForLine } from "../routing/routing"; import { calculateRouteForLine } from "../routing/routing";
import { omit } from "lodash"; import { omit } from "lodash";
import { Point as GeoJsonPoint } from "geojson";
const updateTimes: Record<string, number> = {}; const updateTimes: Record<string, number> = {};
function createRoutePointModel() { interface RoutePointModel extends Model<InferAttributes<RoutePointModel>, InferCreationAttributes<RoutePointModel>> {
return class RoutePointModel extends Model { routeId: string;
routeId!: string; lat: Latitude;
lat!: Latitude; lon: Longitude;
lon!: Longitude; pos: GeoJsonPoint;
zoom!: number; zoom: number;
idx!: number; idx: number;
ele!: number | null; ele: number | null;
toJSON!: () => TrackPoint; toJSON: () => TrackPoint;
};
} }
export interface RouteWithId extends Route { export interface RouteWithId extends Route {
@ -27,7 +26,7 @@ export interface RouteWithId extends Route {
export default class DatabaseRoutes { export default class DatabaseRoutes {
RoutePointModel = createRoutePointModel(); private RoutePointModel = createModel<RoutePointModel>();
_db: Database; _db: Database;

Wyświetl plik

@ -1,33 +1,30 @@
import Sequelize, { Model } from "sequelize"; import Sequelize, { CreationOptional, ForeignKey, InferAttributes, InferCreationAttributes, Model } from "sequelize";
import { Field, ID, PadId, Type, TypeCreate, TypeUpdate } from "facilmap-types"; import { Field, ID, PadId, Type, TypeCreate, TypeUpdate } from "facilmap-types";
import Database from "./database"; import Database from "./database";
import { makeNotNullForeignKey, validateColour } from "./helpers"; import { createModel, getDefaultIdType, makeNotNullForeignKey, validateColour } from "./helpers";
import { PadModel } from "./pad";
function createTypeModel() { export interface TypeModel extends Model<InferAttributes<TypeModel>, InferCreationAttributes<TypeModel>> {
return class TypeModel extends Model { id: CreationOptional<ID>;
id!: ID; name: string;
name!: string; type: "marker" | "line";
type!: "marker" | "line"; padId: ForeignKey<PadModel["id"]>;
padId!: PadId; defaultColour: string | null;
defaultColour!: string | null; colourFixed: boolean | null;
colourFixed!: boolean | null; defaultSize: string | null;
defaultSize!: string | null; sizeFixed: boolean | null;
sizeFixed!: boolean | null; defaultSymbol: string | null;
defaultSymbol!: string | null; symbolFixed: boolean | null;
symbolFixed!: boolean | null; defaultShape: string | null;
defaultShape!: string | null; shapeFixed: boolean | null;
shapeFixed!: boolean | null; defaultWidth: string | null;
defaultWidth!: string | null; widthFixed: boolean | null;
widthFixed!: boolean | null; defaultMode: string | null;
defaultMode!: string | null; modeFixed: boolean | null;
modeFixed!: boolean | null; showInLegend: boolean | null;
showInLegend!: boolean | null; fields: Field[];
fields!: Field[]; toJSON: () => Type;
toJSON!: () => Type; };
};
}
export type TypeModel = InstanceType<ReturnType<typeof createTypeModel>>;
const DEFAULT_TYPES: TypeCreate[] = [ const DEFAULT_TYPES: TypeCreate[] = [
{ name: "Marker", type: "marker", fields: [ { name: "Description", type: "textarea" } ] }, { name: "Marker", type: "marker", fields: [ { name: "Description", type: "textarea" } ] },
@ -36,7 +33,7 @@ const DEFAULT_TYPES: TypeCreate[] = [
export default class DatabaseTypes { export default class DatabaseTypes {
TypeModel = createTypeModel(); TypeModel = createModel<TypeModel>();
_db: Database; _db: Database;
@ -44,6 +41,7 @@ export default class DatabaseTypes {
this._db = database; this._db = database;
this.TypeModel.init({ this.TypeModel.init({
id: getDefaultIdType(),
name: { type: Sequelize.TEXT, allowNull: false }, name: { type: Sequelize.TEXT, allowNull: false },
type: { type: Sequelize.ENUM("marker", "line"), allowNull: false }, type: { type: Sequelize.ENUM("marker", "line"), allowNull: false },
defaultColour: { type: Sequelize.STRING(6), allowNull: true, validate: validateColour }, defaultColour: { type: Sequelize.STRING(6), allowNull: true, validate: validateColour },

Wyświetl plik

@ -1,28 +1,26 @@
import { DataTypes, Model } from "sequelize"; import { CreationOptional, DataTypes, ForeignKey, InferAttributes, InferCreationAttributes, Model } from "sequelize";
import { ID, Latitude, Longitude, PadId, View, ViewCreate, ViewUpdate } from "facilmap-types"; import { ID, Latitude, Longitude, PadId, View, ViewCreate, ViewUpdate } from "facilmap-types";
import Database from "./database"; import Database from "./database";
import { getLatType, getLonType, makeNotNullForeignKey } from "./helpers"; import { createModel, getDefaultIdType, getLatType, getLonType, makeNotNullForeignKey } from "./helpers";
import { PadModel } from "./pad";
function createViewModel() { export interface ViewModel extends Model<InferAttributes<ViewModel>, InferCreationAttributes<ViewModel>> {
return class ViewModel extends Model { id: CreationOptional<ID>;
id!: ID; padId: ForeignKey<PadModel["id"]>;
name!: string; name: string;
baseLayer!: string; baseLayer: string;
layers!: string; layers: string;
top!: Latitude; top: Latitude;
bottom!: Latitude; bottom: Latitude;
left!: Longitude; left: Longitude;
right!: Longitude; right: Longitude;
filter!: string | null; filter: string | null;
toJSON!: () => View; toJSON: () => View;
}
} }
type ViewModel = InstanceType<ReturnType<typeof createViewModel>>;
export default class DatabaseViews { export default class DatabaseViews {
ViewModel = createViewModel(); ViewModel = createModel<ViewModel>();
_db: Database; _db: Database;
@ -30,6 +28,7 @@ export default class DatabaseViews {
this._db = database; this._db = database;
this.ViewModel.init({ this.ViewModel.init({
id: getDefaultIdType(),
name : { type: DataTypes.TEXT, allowNull: false }, name : { type: DataTypes.TEXT, allowNull: false },
baseLayer : { type: DataTypes.TEXT, allowNull: false }, baseLayer : { type: DataTypes.TEXT, allowNull: false },
layers : { layers : {

Wyświetl plik

@ -36,7 +36,7 @@ export async function calculateRoute(routePoints: Point[], encodedMode: RouteMod
} }
calculateZoomLevels(route!.trackPoints); calculateZoomLevels(route!.trackPoints);
Object.assign(route, calculateBbox(route!.trackPoints)); Object.assign(route!, calculateBbox(route!.trackPoints));
return route as RouteInfo; return route as RouteInfo;
} }

Wyświetl plik

@ -74,7 +74,7 @@ class SocketConnection {
registerSocketHandlers() { registerSocketHandlers() {
for (const i of Object.keys(this.socketHandlers) as Array<keyof SocketHandlers>) { for (const i of Object.keys(this.socketHandlers) as Array<keyof SocketHandlers>) {
this.socket.on(i, async (data, callback) => { this.socket.on(i, async (data: any, callback: any): Promise<void> => {
try { try {
const res = await this.socketHandlers[i](data); const res = await this.socketHandlers[i](data);
@ -82,7 +82,7 @@ class SocketConnection {
console.trace("No callback available to send result of socket handler " + i); console.trace("No callback available to send result of socket handler " + i);
callback && callback(null, res); callback && callback(null, res);
} catch (err) { } catch (err: any) {
console.log(err.stack); console.log(err.stack);
callback && callback({ message: err.message, stack: err.stack }); callback && callback({ message: err.message, stack: err.stack });

Wyświetl plik

@ -88,10 +88,10 @@ type PromiseCreatorMap<T extends object> = {
[P in keyof T]: PromiseLike<T[P]> | ((...args: Array<any>) => Promise<T[P]>) [P in keyof T]: PromiseLike<T[P]> | ((...args: Array<any>) => Promise<T[P]>)
}; };
export function promiseAuto<T extends object>(obj: PromiseCreatorMap<T>): Promise<T> { export function promiseAuto<T extends Record<string, any>>(obj: PromiseCreatorMap<T>): Promise<T> {
const promises = { } as PromiseMap<T>; const promises = { } as PromiseMap<T>;
function _get(str: keyof T) { function _get(str: keyof T & string) {
const dep = obj[str]; const dep = obj[str];
if(!dep) if(!dep)
throw new Error("Invalid dependency '" + str + "' in promiseAuto()."); throw new Error("Invalid dependency '" + str + "' in promiseAuto().");
@ -112,7 +112,7 @@ export function promiseAuto<T extends object>(obj: PromiseCreatorMap<T>): Promis
function _getDeps(arr: Array<keyof T>) { function _getDeps(arr: Array<keyof T>) {
const deps = { } as PromiseMap<T>; const deps = { } as PromiseMap<T>;
arr.forEach(function(it) { arr.forEach(function(it) {
deps[it] = _get(it); deps[it] = _get(it as string);
}); });
return promiseProps(deps); return promiseProps(deps);
} }

Wyświetl plik

@ -29,6 +29,6 @@
}, },
"devDependencies": { "devDependencies": {
"rimraf": "^3.0.2", "rimraf": "^3.0.2",
"typescript": "^4.2.4" "typescript": "^5.2.2"
} }
} }

Wyświetl plik

@ -49,10 +49,10 @@
"@types/marked": "^2.0.3", "@types/marked": "^2.0.3",
"@typescript-eslint/eslint-plugin": "^4.24.0", "@typescript-eslint/eslint-plugin": "^4.24.0",
"@typescript-eslint/parser": "^4.24.0", "@typescript-eslint/parser": "^4.24.0",
"eslint": "^7.27.0", "eslint": "^8.49.0",
"jest": "^26.6.3", "jest": "^26.6.3",
"rimraf": "^3.0.2", "rimraf": "^3.0.2",
"ts-jest": "^26.5.4", "ts-jest": "^26.5.4",
"typescript": "^4.2.3" "typescript": "^5.2.2"
} }
} }

Wyświetl plik

@ -23,7 +23,7 @@ export function filterHasError(expr: string): Error | undefined {
try { try {
if(expr && expr.trim()) if(expr && expr.trim())
filtrexCompileExpression(expr, { extraFunctions: customFuncs }); filtrexCompileExpression(expr, { extraFunctions: customFuncs });
} catch(e) { } catch(e: any) {
return e; return e;
} }
} }

Wyświetl plik

@ -85,7 +85,7 @@ export function renderOsmTag(key: string, value: string): string {
}).join(";"); }).join(";");
} else { } else {
return linkifyStr(value, { return linkifyStr(value, {
target: (href, type) => type === "url" ? "_blank" : "" target: (href: string, type: string) => type === "url" ? "_blank" : ""
}); });
} }
} }

9185
yarn.lock

Plik diff jest za duży Load Diff