integrasi database dan UI

This commit is contained in:
unknown 2025-03-20 13:03:20 +07:00
commit 04f085597b
6272 changed files with 723163 additions and 0 deletions

6
backend/.env Normal file
View File

@ -0,0 +1,6 @@
PORT=5000
DB_HOST=localhost
DB_USER=root
DB_NAME=sibayam
API_URL=http://localhost:5000
JWT_SECRET=2c5t0ny38989t03cr4ny904r8xy12jc

55
backend/app.js Normal file
View File

@ -0,0 +1,55 @@
const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const sequelize = require('./config/database');
const path = require('path');
const userRoutes = require('./routes/userRoutes');
const authRoutes = require('./routes/authRoutes');
const gejalaRoutes = require('./routes/gejalaRoute');
const hamaRoutes = require('./routes/hamaRoutes');
const penyakitRoutes = require('./routes/penyakitRoutes');
const swaggerDocs = require('./swagger');
dotenv.config();
const app = express();
// Middlewares
app.use(express.json());
app.use(cors());
// Routes
app.use("/api/users", userRoutes);
app.use("/api/auth", authRoutes);
app.use("/api/gejala", gejalaRoutes);
app.use("/api/hama", hamaRoutes);
app.use("/api/penyakit", penyakitRoutes);
// Swagger Documentation
swaggerDocs(app); // Setup Swagger UI documentation
const PORT = process.env.PORT || 5000;
// Database Initialization
const initializeDatabase = async () => {
try {
await sequelize.sync({ force: false });
console.log('Database synced');
} catch (error) {
console.error('Error syncing database:', error);
throw error;
}
};
// Start Server
initializeDatabase()
.then(() => {
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`Swagger UI available at http://localhost:${PORT}/api-sibayam`);
});
})
.catch((error) => {
console.error('Error starting the server:', error);
process.exit(1);
});

View File

@ -0,0 +1,23 @@
{
"development": {
"username": "root",
"password": null,
"database": "sibayam",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}

View File

@ -0,0 +1,10 @@
const { Sequelize } = require('sequelize');
require('dotenv').config();
const sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASSWORD, {
host: process.env.DB_HOST,
dialect: 'mysql',
timezone: '+07:00',
});
module.exports = sequelize;

View File

@ -0,0 +1,106 @@
const jwt = require('jsonwebtoken');
const argon2 = require('argon2');
const randomstring = require('randomstring');
const User = require('../models/user'); // Pastikan sesuai dengan struktur project
require('dotenv').config();
// Fungsi untuk membuat token JWT
const generateToken = (user) => {
return jwt.sign(
{ id: user.id, email: user.email, role: user.role }, // id bukan _id untuk Sequelize
process.env.JWT_SECRET,
{ expiresIn: process.env.JWT_EXPIRES_IN || '1d' }
);
};
// Menambahkan user baru dengan hashing Argon2
exports.register = async (req, res) => {
try {
const { name, email, password, alamat, nomorTelepon, role } = req.body;
// Cek apakah email sudah terdaftar
const existingUser = await User.findOne({ where: { email } });
if (existingUser) return res.status(400).json({ message: 'Email already exists' });
// Hash password menggunakan Argon2
const hashedPassword = await argon2.hash(password);
const newUser = await User.create({
name,
email,
password: hashedPassword,
alamat,
nomorTelepon,
role: 'user'
});
res.status(201).json({ message: 'User created successfully', user: newUser });
} catch (error) {
res.status(500).json({ message: 'Error creating user', error });
}
};
// Login
exports.login = async (req, res) => {
try {
const { email, password } = req.body;
// 🔹 Cek apakah user dengan email tersebut ada
const user = await User.findOne({ where: { email } });
if (!user) {
return res.status(401).json({ message: "Email atau password salah" });
}
// 🔹 Verifikasi password
const isPasswordValid = await argon2.verify(user.password, password);
if (!isPasswordValid) {
return res.status(401).json({ message: "Email atau password salah" });
}
// 🔹 Buat token JWT
const token = jwt.sign(
{ id: user.id, email: user.email, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: process.env.JWT_EXPIRES_IN || '1d' }
);
// 🔹 Kirim response dengan token dan role
res.status(200).json({
message: "Login berhasil",
token,
role: user.role // Ini penting untuk Flutter agar bisa menentukan halaman tujuan
});
} catch (error) {
res.status(500).json({ message: "Terjadi kesalahan", error });
}
};
exports.forgotPassword = async (req, res) => {
try {
const { email, password } = req.body; // Gunakan 'password' sebagai field yang dikirim
// 🔹 Validasi input
if (!email || !password) {
return res.status(400).json({ message: "Email dan password baru harus diisi" });
}
// 🔹 Cek apakah user dengan email tersebut ada
const user = await User.findOne({ where: { email } });
if (!user) {
return res.status(404).json({ message: "User tidak ditemukan" });
}
// 🔹 Hash password baru dengan Argon2
const hashedPassword = await argon2.hash(password);
// 🔹 Update password user di database
await user.update({ password: hashedPassword });
res.status(200).json({ message: "Password berhasil diperbarui" });
} catch (error) {
console.error("Error pada forgotPassword:", error);
res.status(500).json({ message: "Terjadi kesalahan", error: error.message });
}
};

View File

@ -0,0 +1,88 @@
const Gejala = require('../models/gejala');
// 🔹 Menampilkan semua data gejala
exports.getAllGejala = async (req, res) => {
try {
const gejala = await Gejala.findAll();
res.status(200).json(gejala);
} catch (error) {
res.status(500).json({ message: 'Terjadi kesalahan', error });
}
};
// 🔹 Menampilkan satu gejala berdasarkan ID
exports.getGejalaById = async (req, res) => {
try {
const gejala = await Gejala.findByPk(req.params.id);
if (!gejala) {
return res.status(404).json({ message: 'Gejala tidak ditemukan' });
}
res.status(200).json(gejala);
} catch (error) {
res.status(500).json({ message: 'Terjadi kesalahan', error });
}
};
// 🔹 Menambahkan gejala baru dengan kode otomatis
exports.createGejala = async (req, res) => {
try {
const { nama } = req.body;
if (!nama) {
return res.status(400).json({ message: 'Nama gejala wajib diisi' });
}
// Cari kode terakhir di database
const lastGejala = await Gejala.findOne({
order: [['id', 'DESC']]
});
// Generate kode baru berdasarkan kode terakhir
let newKode = 'G01';
if (lastGejala && lastGejala.kode) {
const lastNumber = parseInt(lastGejala.kode.substring(1)); // Ambil angka setelah 'G'
const nextNumber = lastNumber + 1;
newKode = `G${nextNumber.toString().padStart(2, '0')}`; // Format G01, G02, dst.
}
// Buat data baru
const newGejala = await Gejala.create({ kode: newKode, nama });
res.status(201).json({ message: 'Gejala berhasil ditambahkan', data: newGejala });
} catch (error) {
res.status(500).json({ message: 'Gagal menambahkan gejala', error: error.message });
}
};
// 🔹 Mengupdate gejala berdasarkan ID
exports.updateGejala = async (req, res) => {
try {
const { kode, nama } = req.body;
const gejala = await Gejala.findByPk(req.params.id);
if (!gejala) {
return res.status(404).json({ message: 'Gejala tidak ditemukan' });
}
await gejala.update({ kode, nama });
res.status(200).json({ message: 'Gejala berhasil diperbarui', data: gejala });
} catch (error) {
res.status(500).json({ message: 'Gagal memperbarui gejala', error });
}
};
// 🔹 Menghapus gejala berdasarkan ID
exports.deleteGejala = async (req, res) => {
try {
const gejala = await Gejala.findByPk(req.params.id);
if (!gejala) {
return res.status(404).json({ message: 'Gejala tidak ditemukan' });
}
await gejala.destroy();
res.status(200).json({ message: 'Gejala berhasil dihapus' });
} catch (error) {
res.status(500).json({ message: 'Gagal menghapus gejala', error });
}
};

View File

@ -0,0 +1,88 @@
const Hama = require('../models/hama');
// 🔹 Fungsi untuk mendapatkan semua data hama
exports.getAllHama = async (req, res) => {
try {
const dataHama = await Hama.findAll();
res.status(200).json({ message: 'Data hama berhasil diambil', data: dataHama });
} catch (error) {
res.status(500).json({ message: 'Gagal mengambil data hama', error });
}
};
// 🔹 Fungsi untuk mendapatkan detail hama berdasarkan ID
exports.getHamaById = async (req, res) => {
try {
const { id } = req.params;
const hama = await Hama.findByPk(id);
if (!hama) {
return res.status(404).json({ message: 'Hama tidak ditemukan' });
}
res.status(200).json({ message: 'Data hama ditemukan', data: hama });
} catch (error) {
res.status(500).json({ message: 'Gagal mengambil data hama', error });
}
};
// 🔹 Fungsi untuk menambahkan hama baru (kode otomatis & kategori default)
exports.createHama = async (req, res) => {
try {
const { nama, deskripsi, penanganan } = req.body;
// Cek kode terakhir
const lastHama = await Hama.findOne({ order: [['id', 'DESC']] });
let newKode = 'H01'; // Default kode awal
if (lastHama) {
const lastNumber = parseInt(lastHama.kode.substring(1)) + 1;
newKode = `H${lastNumber.toString().padStart(2, '0')}`;
}
const newHama = await Hama.create({
kode: newKode,
nama,
kategori: 'hama', // Default kategori
deskripsi,
penanganan,
});
res.status(201).json({ message: 'Hama berhasil ditambahkan', data: newHama });
} catch (error) {
res.status(500).json({ message: 'Gagal menambahkan hama', error });
}
};
// 🔹 Fungsi untuk mengupdate hama berdasarkan ID
exports.updateHama = async (req, res) => {
try {
const { id } = req.params;
const { nama, kategori, deskripsi, penanganan } = req.body;
const hama = await Hama.findByPk(id);
if (!hama) {
return res.status(404).json({ message: 'Hama tidak ditemukan' });
}
await hama.update({ nama, kategori, deskripsi, penanganan });
res.status(200).json({ message: 'Hama berhasil diperbarui', data: hama });
} catch (error) {
res.status(500).json({ message: 'Gagal memperbarui hama', error });
}
};
// 🔹 Fungsi untuk menghapus hama berdasarkan ID
exports.deleteHama = async (req, res) => {
try {
const { id } = req.params;
const hama = await Hama.findByPk(id);
if (!hama) {
return res.status(404).json({ message: 'Hama tidak ditemukan' });
}
await hama.destroy();
res.status(200).json({ message: 'Hama berhasil dihapus' });
} catch (error) {
res.status(500).json({ message: 'Gagal menghapus hama', error });
}
};

View File

@ -0,0 +1,88 @@
const Penyakit = require('../models/penyakit');
// 🔹 Fungsi untuk mendapatkan semua data penyakit
exports.getAllPenyakit = async (req, res) => {
try {
const dataPenyakit = await Penyakit.findAll();
res.status(200).json({ message: 'Data penyakit berhasil diambil', data: dataPenyakit });
} catch (error) {
res.status(500).json({ message: 'Gagal mengambil data penyakit', error });
}
};
// 🔹 Fungsi untuk mendapatkan detail penyakit berdasarkan ID
exports.getPenyakitById = async (req, res) => {
try {
const { id } = req.params;
const penyakit = await Penyakit.findByPk(id);
if (!penyakit) {
return res.status(404).json({ message: 'Penyakit tidak ditemukan' });
}
res.status(200).json({ message: 'Data penyakit ditemukan', data: penyakit });
} catch (error) {
res.status(500).json({ message: 'Gagal mengambil data penyakit', error });
}
};
// 🔹 Fungsi untuk menambahkan penyakit baru (kode otomatis & kategori default)
exports.createPenyakit = async (req, res) => {
try {
const { nama, deskripsi, penanganan } = req.body;
// Cek kode terakhir
const lastPenyakit = await Penyakit.findOne({ order: [['id', 'DESC']] });
let newKode = 'P01'; // Default kode awal
if (lastPenyakit) {
const lastNumber = parseInt(lastPenyakit.kode.substring(1)) + 1;
newKode = `P${lastNumber.toString().padStart(2, '0')}`;
}
const newPenyakit = await Penyakit.create({
kode: newKode,
nama,
kategori: 'penyakit', // Default kategori
deskripsi,
penanganan,
});
res.status(201).json({ message: 'Penyakit berhasil ditambahkan', data: newPenyakit });
} catch (error) {
res.status(500).json({ message: 'Gagal menambahkan penyakit', error });
}
};
// 🔹 Fungsi untuk mengupdate penyakit berdasarkan ID
exports.updatePenyakit = async (req, res) => {
try {
const { id } = req.params;
const { nama, kategori, deskripsi, penanganan } = req.body;
const penyakit = await Penyakit.findByPk(id);
if (!penyakit) {
return res.status(404).json({ message: 'Penyakit tidak ditemukan' });
}
await penyakit.update({ nama, kategori, deskripsi, penanganan });
res.status(200).json({ message: 'Penyakit berhasil diperbarui', data: penyakit });
} catch (error) {
res.status(500).json({ message: 'Gagal memperbarui penyakit', error });
}
};
// 🔹 Fungsi untuk menghapus penyakit berdasarkan ID
exports.deletePenyakit = async (req, res) => {
try {
const { id } = req.params;
const penyakit = await Penyakit.findByPk(id);
if (!penyakit) {
return res.status(404).json({ message: 'Penyakit tidak ditemukan' });
}
await penyakit.destroy();
res.status(200).json({ message: 'Penyakit berhasil dihapus' });
} catch (error) {
res.status(500).json({ message: 'Gagal menghapus penyakit', error });
}
};

View File

@ -0,0 +1,150 @@
const User = require('../models/user');
const argon2 = require('argon2');
const { Op } = require('sequelize');
// Menampilkan semua user
exports.getAllUsers = async (req, res) => {
try {
const users = await User.findAll({ attributes: { exclude: ['password'] } });
res.status(200).json(users);
} catch (error) {
res.status(500).json({ message: 'Error retrieving users', error });
}
};
// Menampilkan satu user berdasarkan ID
exports.getUserById = async (req, res) => {
try {
const user = await User.findByPk(req.params.id, { attributes: { exclude: ['password'] } });
if (!user) return res.status(404).json({ message: 'User not found' });
res.status(200).json(user);
} catch (error) {
res.status(500).json({ message: 'Error retrieving user', error });
}
};
// Menambahkan user baru dengan hashing Argon2
exports.createUser = async (req, res) => {
try {
const { name, email, password, alamat, nomorTelepon, role } = req.body;
// Cek apakah email sudah terdaftar
const existingUser = await User.findOne({ where: { email } });
if (existingUser) return res.status(400).json({ message: 'Email already exists' });
// Hash password menggunakan Argon2
const hashedPassword = await argon2.hash(password);
const newUser = await User.create({
name,
email,
password: hashedPassword,
alamat,
nomorTelepon,
role
});
res.status(201).json({ message: 'User created successfully', user: newUser });
} catch (error) {
res.status(500).json({ message: 'Error creating user', error });
}
};
// Mengupdate user berdasarkan ID
exports.updateUser = async (req, res) => {
try {
const { name, email, alamat, nomorTelepon, role } = req.body;
const user = await User.findByPk(req.params.id);
if (!user) return res.status(404).json({ message: 'User not found' });
await user.update({ name, email, alamat, nomorTelepon, role });
res.status(200).json({ message: 'User updated successfully', user });
} catch (error) {
res.status(500).json({ message: 'Error updating user', error });
}
};
// Mengupdate berdasarkan email
exports.updateUserEmail = async (req, res) => {
try {
const { email, name, alamat, nomorTelepon, newPassword } = req.body;
if (!email) {
return res.status(400).json({ message: "Email harus disertakan" });
}
const user = await User.findOne({ where: { email } });
if (!user) {
return res.status(404).json({ message: "User tidak ditemukan" });
}
let hashedPassword = user.password;
if (newPassword) {
hashedPassword = await argon2.hash(newPassword);
}
await user.update({
name: name || user.name,
alamat: alamat || user.alamat,
nomorTelepon: nomorTelepon || user.nomorTelepon,
password: hashedPassword,
});
res.status(200).json({ message: "User berhasil diperbarui", user });
} catch (error) {
res.status(500).json({ message: "Terjadi kesalahan pada server", error });
}
};
// Menghapus user berdasarkan ID (soft delete)
exports.deleteUser = async (req, res) => {
try {
const user = await User.findByPk(req.params.id);
if (!user) return res.status(404).json({ message: 'User not found' });
await user.destroy();
res.status(200).json({ message: 'User deleted successfully' });
} catch (error) {
res.status(500).json({ message: 'Error deleting user', error });
}
};
// Mengembalikan user yang telah dihapus (restore soft delete)
exports.restoreUser = async (req, res) => {
try {
const user = await User.findOne({
where: { id: req.params.id },
paranoid: false,
});
if (!user) return res.status(404).json({ message: 'User not found' });
await user.restore();
res.status(200).json({ message: 'User restored successfully' });
} catch (error) {
res.status(500).json({ message: 'Error restoring user', error });
}
};
// Verifikasi password dengan Argon2
exports.verifyPassword = async (req, res) => {
try {
const { email, password } = req.body;
// Cari user berdasarkan email
const user = await User.findOne({ where: { email } });
if (!user) return res.status(404).json({ message: 'User not found' });
// Verifikasi password
const validPassword = await argon2.verify(user.password, password);
if (!validPassword) return res.status(400).json({ message: 'Invalid password' });
res.status(200).json({ message: 'Login successful' });
} catch (error) {
res.status(500).json({ message: 'Error verifying password', error });
}
};

View File

@ -0,0 +1,30 @@
// roleMiddleware.js
const jwt = require('jsonwebtoken');
// Middleware to restrict access based on roles
const roleMiddleware = (roles) => {
return (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'Access Denied. No Token Provided!' });
}
try {
// Verify the token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
// Check if the user has one of the allowed roles
if (roles.includes(req.user.role)) {
next();
} else {
return res.status(403).json({ message: 'Access Denied. Insufficient permissions!' });
}
} catch (error) {
return res.status(401).json({ message: 'Invalid Token' });
}
};
};
module.exports = roleMiddleware;

View File

@ -0,0 +1,41 @@
'use strict';
const { sequelize } = require('../models');
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING,
allowNull: true
},
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
password: {
type: Sequelize.STRING,
allowNull: false
},
alamat: {
type: Sequelize.STRING,
allowNull: true
},
nomorTelepon: {
type: Sequelize.STRING,
allowNull: true
},
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Users');
}
};

View File

@ -0,0 +1,14 @@
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn('users', 'role', {
type: Sequelize.STRING,
allowNull: true,
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn('users', 'role');
}
};

View File

@ -0,0 +1,25 @@
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Gejala', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
kode: {
type: Sequelize.STRING,
allowNull: true
},
nama: {
type: Sequelize.STRING,
allowNull: true
},
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Gejala');
}
};

View File

@ -0,0 +1,33 @@
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('hamas', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
kode: {
type: Sequelize.STRING,
allowNull: true
},
nama: {
type: Sequelize.STRING,
allowNull: true
},
deskripsi: {
type: Sequelize.STRING
},
penanganan: {
type: Sequelize.STRING,
allowNull: true
},
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('hamas');
}
};

View File

@ -0,0 +1,33 @@
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('penyakit', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
kode: {
type: Sequelize.STRING,
allowNull: true
},
nama: {
type: Sequelize.STRING,
allowNull: true
},
deskripsi: {
type: Sequelize.STRING,
allowNull: true
},
penanganan: {
type: Sequelize.STRING,
allowNull: true
},
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('penyakit');
}
};

32
backend/models/gejala.js Normal file
View File

@ -0,0 +1,32 @@
const { Model, DataTypes } = require('sequelize');
const sequelize = require('../config/database');
class Gejala extends Model {}
Gejala.init(
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
kode: {
type: DataTypes.STRING,
allowNull: false,
},
nama: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
sequelize,
modelName: 'Gejala',
tableName: 'gejala',
timestamps: false, // Jika ingin menggunakan createdAt & updatedAt, ubah ke true
paranoid: false, // Jika menggunakan soft delete, ubah ke true
}
);
module.exports = Gejala;

40
backend/models/hama.js Normal file
View File

@ -0,0 +1,40 @@
const { Model, DataTypes } = require('sequelize');
const sequelize = require('../config/database');
class Hama extends Model {}
Hama.init(
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
kode: {
type: DataTypes.STRING,
allowNull: false,
},
nama: {
type: DataTypes.STRING,
allowNull: false,
},
deskripsi: {
type: DataTypes.STRING,
allowNull: true,
},
penanganan: {
type: DataTypes.STRING,
allowNull: true,
},
},
{
sequelize,
modelName: 'Hama',
tableName: 'hama',
timestamps: false, // Jika ingin menggunakan createdAt & updatedAt, ubah ke true
paranoid: false, // Jika menggunakan soft delete, ubah ke true
}
);
module.exports = Hama;

43
backend/models/index.js Normal file
View File

@ -0,0 +1,43 @@
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const process = require('process');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(file => {
return (
file.indexOf('.') !== 0 &&
file !== basename &&
file.slice(-3) === '.js' &&
file.indexOf('.test.js') === -1
);
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;

View File

@ -0,0 +1,40 @@
const { Model, DataTypes } = require('sequelize');
const sequelize = require('../config/database');
class Penyakit extends Model {}
Penyakit.init(
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
kode: {
type: DataTypes.STRING,
allowNull: false,
},
nama: {
type: DataTypes.STRING,
allowNull: false,
},
deskripsi: {
type: DataTypes.STRING,
allowNull: true,
},
penanganan: {
type: DataTypes.STRING,
allowNull: true,
},
},
{
sequelize,
modelName: 'Penyakit',
tableName: 'penyakit',
timestamps: false, // Jika ingin menggunakan createdAt & updatedAt, ubah ke true
paranoid: false, // Jika menggunakan soft delete, ubah ke true
}
);
module.exports = Penyakit;

53
backend/models/user.js Normal file
View File

@ -0,0 +1,53 @@
const { Model, DataTypes } = require('sequelize');
const sequelize = require('../config/database');
class User extends Model {}
User.init(
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
name: {
type: DataTypes.STRING,
allowNull: true,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true,
},
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
alamat: {
type: DataTypes.STRING,
allowNull: true,
},
nomorTelepon: {
type: DataTypes.STRING,
allowNull: true,
},
role: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
sequelize,
modelName: 'User',
tableName: 'users',
timestamps: false, // Pastikan timestamps aktif jika menggunakan paranoid
paranoid: false, // Hanya gunakan ini jika timestamps: true
}
);
module.exports = User;

16
backend/node_modules/.bin/css-beautify generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../js-beautify/js/bin/css-beautify.js" "$@"
else
exec node "$basedir/../js-beautify/js/bin/css-beautify.js" "$@"
fi

17
backend/node_modules/.bin/css-beautify.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\js-beautify\js\bin\css-beautify.js" %*

28
backend/node_modules/.bin/css-beautify.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../js-beautify/js/bin/css-beautify.js" $args
} else {
& "$basedir/node$exe" "$basedir/../js-beautify/js/bin/css-beautify.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../js-beautify/js/bin/css-beautify.js" $args
} else {
& "node$exe" "$basedir/../js-beautify/js/bin/css-beautify.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/editorconfig generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../editorconfig/bin/editorconfig" "$@"
else
exec node "$basedir/../editorconfig/bin/editorconfig" "$@"
fi

17
backend/node_modules/.bin/editorconfig.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\editorconfig\bin\editorconfig" %*

28
backend/node_modules/.bin/editorconfig.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../editorconfig/bin/editorconfig" $args
} else {
& "$basedir/node$exe" "$basedir/../editorconfig/bin/editorconfig" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../editorconfig/bin/editorconfig" $args
} else {
& "node$exe" "$basedir/../editorconfig/bin/editorconfig" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/glob generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../glob/dist/esm/bin.mjs" "$@"
else
exec node "$basedir/../glob/dist/esm/bin.mjs" "$@"
fi

17
backend/node_modules/.bin/glob.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\glob\dist\esm\bin.mjs" %*

28
backend/node_modules/.bin/glob.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../glob/dist/esm/bin.mjs" $args
} else {
& "$basedir/node$exe" "$basedir/../glob/dist/esm/bin.mjs" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../glob/dist/esm/bin.mjs" $args
} else {
& "node$exe" "$basedir/../glob/dist/esm/bin.mjs" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/html-beautify generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../js-beautify/js/bin/html-beautify.js" "$@"
else
exec node "$basedir/../js-beautify/js/bin/html-beautify.js" "$@"
fi

17
backend/node_modules/.bin/html-beautify.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\js-beautify\js\bin\html-beautify.js" %*

28
backend/node_modules/.bin/html-beautify.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../js-beautify/js/bin/html-beautify.js" $args
} else {
& "$basedir/node$exe" "$basedir/../js-beautify/js/bin/html-beautify.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../js-beautify/js/bin/html-beautify.js" $args
} else {
& "node$exe" "$basedir/../js-beautify/js/bin/html-beautify.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/js-beautify generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../js-beautify/js/bin/js-beautify.js" "$@"
else
exec node "$basedir/../js-beautify/js/bin/js-beautify.js" "$@"
fi

17
backend/node_modules/.bin/js-beautify.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\js-beautify\js\bin\js-beautify.js" %*

28
backend/node_modules/.bin/js-beautify.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../js-beautify/js/bin/js-beautify.js" $args
} else {
& "$basedir/node$exe" "$basedir/../js-beautify/js/bin/js-beautify.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../js-beautify/js/bin/js-beautify.js" $args
} else {
& "node$exe" "$basedir/../js-beautify/js/bin/js-beautify.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/js-yaml generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../js-yaml/bin/js-yaml.js" "$@"
else
exec node "$basedir/../js-yaml/bin/js-yaml.js" "$@"
fi

17
backend/node_modules/.bin/js-yaml.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\js-yaml\bin\js-yaml.js" %*

28
backend/node_modules/.bin/js-yaml.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
} else {
& "$basedir/node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
} else {
& "node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/mime generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../mime/cli.js" "$@"
else
exec node "$basedir/../mime/cli.js" "$@"
fi

17
backend/node_modules/.bin/mime.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mime\cli.js" %*

28
backend/node_modules/.bin/mime.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../mime/cli.js" $args
} else {
& "$basedir/node$exe" "$basedir/../mime/cli.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../mime/cli.js" $args
} else {
& "node$exe" "$basedir/../mime/cli.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/node-gyp-build generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../node-gyp-build/bin.js" "$@"
else
exec node "$basedir/../node-gyp-build/bin.js" "$@"
fi

16
backend/node_modules/.bin/node-gyp-build-optional generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../node-gyp-build/optional.js" "$@"
else
exec node "$basedir/../node-gyp-build/optional.js" "$@"
fi

17
backend/node_modules/.bin/node-gyp-build-optional.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-gyp-build\optional.js" %*

28
backend/node_modules/.bin/node-gyp-build-optional.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../node-gyp-build/optional.js" $args
} else {
& "$basedir/node$exe" "$basedir/../node-gyp-build/optional.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../node-gyp-build/optional.js" $args
} else {
& "node$exe" "$basedir/../node-gyp-build/optional.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/node-gyp-build-test generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../node-gyp-build/build-test.js" "$@"
else
exec node "$basedir/../node-gyp-build/build-test.js" "$@"
fi

17
backend/node_modules/.bin/node-gyp-build-test.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-gyp-build\build-test.js" %*

28
backend/node_modules/.bin/node-gyp-build-test.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../node-gyp-build/build-test.js" $args
} else {
& "$basedir/node$exe" "$basedir/../node-gyp-build/build-test.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../node-gyp-build/build-test.js" $args
} else {
& "node$exe" "$basedir/../node-gyp-build/build-test.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

17
backend/node_modules/.bin/node-gyp-build.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\node-gyp-build\bin.js" %*

28
backend/node_modules/.bin/node-gyp-build.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../node-gyp-build/bin.js" $args
} else {
& "$basedir/node$exe" "$basedir/../node-gyp-build/bin.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../node-gyp-build/bin.js" $args
} else {
& "node$exe" "$basedir/../node-gyp-build/bin.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/node-which generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../which/bin/node-which" "$@"
else
exec node "$basedir/../which/bin/node-which" "$@"
fi

17
backend/node_modules/.bin/node-which.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\which\bin\node-which" %*

28
backend/node_modules/.bin/node-which.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args
} else {
& "$basedir/node$exe" "$basedir/../which/bin/node-which" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../which/bin/node-which" $args
} else {
& "node$exe" "$basedir/../which/bin/node-which" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/nopt generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../nopt/bin/nopt.js" "$@"
else
exec node "$basedir/../nopt/bin/nopt.js" "$@"
fi

17
backend/node_modules/.bin/nopt.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\nopt\bin\nopt.js" %*

28
backend/node_modules/.bin/nopt.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../nopt/bin/nopt.js" $args
} else {
& "$basedir/node$exe" "$basedir/../nopt/bin/nopt.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../nopt/bin/nopt.js" $args
} else {
& "node$exe" "$basedir/../nopt/bin/nopt.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/randomstring generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../randomstring/bin/randomstring" "$@"
else
exec node "$basedir/../randomstring/bin/randomstring" "$@"
fi

17
backend/node_modules/.bin/randomstring.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\randomstring\bin\randomstring" %*

28
backend/node_modules/.bin/randomstring.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../randomstring/bin/randomstring" $args
} else {
& "$basedir/node$exe" "$basedir/../randomstring/bin/randomstring" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../randomstring/bin/randomstring" $args
} else {
& "node$exe" "$basedir/../randomstring/bin/randomstring" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/resolve generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../resolve/bin/resolve" "$@"
else
exec node "$basedir/../resolve/bin/resolve" "$@"
fi

17
backend/node_modules/.bin/resolve.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\resolve\bin\resolve" %*

28
backend/node_modules/.bin/resolve.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../resolve/bin/resolve" $args
} else {
& "$basedir/node$exe" "$basedir/../resolve/bin/resolve" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../resolve/bin/resolve" $args
} else {
& "node$exe" "$basedir/../resolve/bin/resolve" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/semver generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../semver/bin/semver.js" "$@"
else
exec node "$basedir/../semver/bin/semver.js" "$@"
fi

17
backend/node_modules/.bin/semver.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver.js" %*

28
backend/node_modules/.bin/semver.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
} else {
& "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../semver/bin/semver.js" $args
} else {
& "node$exe" "$basedir/../semver/bin/semver.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/sequelize generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../sequelize-cli/lib/sequelize" "$@"
else
exec node "$basedir/../sequelize-cli/lib/sequelize" "$@"
fi

16
backend/node_modules/.bin/sequelize-cli generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../sequelize-cli/lib/sequelize" "$@"
else
exec node "$basedir/../sequelize-cli/lib/sequelize" "$@"
fi

17
backend/node_modules/.bin/sequelize-cli.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\sequelize-cli\lib\sequelize" %*

28
backend/node_modules/.bin/sequelize-cli.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../sequelize-cli/lib/sequelize" $args
} else {
& "$basedir/node$exe" "$basedir/../sequelize-cli/lib/sequelize" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../sequelize-cli/lib/sequelize" $args
} else {
& "node$exe" "$basedir/../sequelize-cli/lib/sequelize" $args
}
$ret=$LASTEXITCODE
}
exit $ret

17
backend/node_modules/.bin/sequelize.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\sequelize-cli\lib\sequelize" %*

28
backend/node_modules/.bin/sequelize.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../sequelize-cli/lib/sequelize" $args
} else {
& "$basedir/node$exe" "$basedir/../sequelize-cli/lib/sequelize" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../sequelize-cli/lib/sequelize" $args
} else {
& "node$exe" "$basedir/../sequelize-cli/lib/sequelize" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/swagger-jsdoc generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../swagger-jsdoc/bin/swagger-jsdoc.js" "$@"
else
exec node "$basedir/../swagger-jsdoc/bin/swagger-jsdoc.js" "$@"
fi

17
backend/node_modules/.bin/swagger-jsdoc.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\swagger-jsdoc\bin\swagger-jsdoc.js" %*

28
backend/node_modules/.bin/swagger-jsdoc.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../swagger-jsdoc/bin/swagger-jsdoc.js" $args
} else {
& "$basedir/node$exe" "$basedir/../swagger-jsdoc/bin/swagger-jsdoc.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../swagger-jsdoc/bin/swagger-jsdoc.js" $args
} else {
& "node$exe" "$basedir/../swagger-jsdoc/bin/swagger-jsdoc.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/uuid generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../uuid/dist/bin/uuid" "$@"
else
exec node "$basedir/../uuid/dist/bin/uuid" "$@"
fi

17
backend/node_modules/.bin/uuid.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\uuid\dist\bin\uuid" %*

28
backend/node_modules/.bin/uuid.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../uuid/dist/bin/uuid" $args
} else {
& "$basedir/node$exe" "$basedir/../uuid/dist/bin/uuid" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../uuid/dist/bin/uuid" $args
} else {
& "node$exe" "$basedir/../uuid/dist/bin/uuid" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/z-schema generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../z-schema/bin/z-schema" "$@"
else
exec node "$basedir/../z-schema/bin/z-schema" "$@"
fi

17
backend/node_modules/.bin/z-schema.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\z-schema\bin\z-schema" %*

28
backend/node_modules/.bin/z-schema.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../z-schema/bin/z-schema" $args
} else {
& "$basedir/node$exe" "$basedir/../z-schema/bin/z-schema" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../z-schema/bin/z-schema" $args
} else {
& "node$exe" "$basedir/../z-schema/bin/z-schema" $args
}
$ret=$LASTEXITCODE
}
exit $ret

2884
backend/node_modules/.package-lock.json generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 James Messinger
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,162 @@
JSON Schema $Ref Parser
============================
#### Parse, Resolve, and Dereference JSON Schema $ref pointers
[![Build Status](https://github.com/APIDevTools/json-schema-ref-parser/workflows/CI-CD/badge.svg?branch=master)](https://github.com/APIDevTools/json-schema-ref-parser/actions)
[![Coverage Status](https://coveralls.io/repos/github/APIDevTools/json-schema-ref-parser/badge.svg?branch=master)](https://coveralls.io/github/APIDevTools/json-schema-ref-parser)
[![npm](https://img.shields.io/npm/v/@apidevtools/json-schema-ref-parser.svg)](https://www.npmjs.com/package/@apidevtools/json-schema-ref-parser)
[![Dependencies](https://david-dm.org/APIDevTools/json-schema-ref-parser.svg)](https://david-dm.org/APIDevTools/json-schema-ref-parser)
[![License](https://img.shields.io/npm/l/@apidevtools/json-schema-ref-parser.svg)](LICENSE)
[![Buy us a tree](https://img.shields.io/badge/Treeware-%F0%9F%8C%B3-lightgreen)](https://plant.treeware.earth/APIDevTools/json-schema-ref-parser)
[![OS and Browser Compatibility](https://apitools.dev/img/badges/ci-badges-with-ie.svg)](https://github.com/APIDevTools/json-schema-ref-parser/actions)
The Problem:
--------------------------
You've got a JSON Schema with `$ref` pointers to other files and/or URLs. Maybe you know all the referenced files ahead of time. Maybe you don't. Maybe some are local files, and others are remote URLs. Maybe they are a mix of JSON and YAML format. Maybe some of the files contain cross-references to each other.
```javascript
{
"definitions": {
"person": {
// references an external file
"$ref": "schemas/people/Bruce-Wayne.json"
},
"place": {
// references a sub-schema in an external file
"$ref": "schemas/places.yaml#/definitions/Gotham-City"
},
"thing": {
// references a URL
"$ref": "http://wayne-enterprises.com/things/batmobile"
},
"color": {
// references a value in an external file via an internal reference
"$ref": "#/definitions/thing/properties/colors/black-as-the-night"
}
}
}
```
The Solution:
--------------------------
JSON Schema $Ref Parser is a full [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03) and [JSON Pointer](https://tools.ietf.org/html/rfc6901) implementation that crawls even the most complex [JSON Schemas](http://json-schema.org/latest/json-schema-core.html) and gives you simple, straightforward JavaScript objects.
- Use **JSON** or **YAML** schemas — or even a mix of both!
- Supports `$ref` pointers to external files and URLs, as well as [custom sources](https://apitools.dev/json-schema-ref-parser/docs/plugins/resolvers.html) such as databases
- Can [bundle](https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#bundlepath-options-callback) multiple files into a single schema that only has _internal_ `$ref` pointers
- Can [dereference](https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#dereferencepath-options-callback) your schema, producing a plain-old JavaScript object that's easy to work with
- Supports [circular references](https://apitools.dev/json-schema-ref-parser/docs/#circular-refs), nested references, back-references, and cross-references between files
- Maintains object reference equality — `$ref` pointers to the same value always resolve to the same object instance
- Tested in Node v10, v12, & v14, and all major web browsers on Windows, Mac, and Linux
Example
--------------------------
```javascript
$RefParser.dereference(mySchema, (err, schema) => {
if (err) {
console.error(err);
}
else {
// `schema` is just a normal JavaScript object that contains your entire JSON Schema,
// including referenced files, combined into a single object
console.log(schema.definitions.person.properties.firstName);
}
})
```
Or use `async`/`await` syntax instead. The following example is the same as above:
```javascript
try {
let schema = await $RefParser.dereference(mySchema);
console.log(schema.definitions.person.properties.firstName);
}
catch(err) {
console.error(err);
}
```
For more detailed examples, please see the [API Documentation](https://apitools.dev/json-schema-ref-parser/docs/)
Installation
--------------------------
Install using [npm](https://docs.npmjs.com/about-npm/):
```bash
npm install @apidevtools/json-schema-ref-parser
```
Usage
--------------------------
When using JSON Schema $Ref Parser in Node.js apps, you'll probably want to use **CommonJS** syntax:
```javascript
const $RefParser = require("@apidevtools/json-schema-ref-parser");
```
When using a transpiler such as [Babel](https://babeljs.io/) or [TypeScript](https://www.typescriptlang.org/), or a bundler such as [Webpack](https://webpack.js.org/) or [Rollup](https://rollupjs.org/), you can use **ECMAScript modules** syntax instead:
```javascript
import $RefParser from "@apidevtools/json-schema-ref-parser";
```
Browser support
--------------------------
JSON Schema $Ref Parser supports recent versions of every major web browser. Older browsers may require [Babel](https://babeljs.io/) and/or [polyfills](https://babeljs.io/docs/en/next/babel-polyfill).
To use JSON Schema $Ref Parser in a browser, you'll need to use a bundling tool such as [Webpack](https://webpack.js.org/), [Rollup](https://rollupjs.org/), [Parcel](https://parceljs.org/), or [Browserify](http://browserify.org/). Some bundlers may require a bit of configuration, such as setting `browser: true` in [rollup-plugin-resolve](https://github.com/rollup/rollup-plugin-node-resolve).
API Documentation
--------------------------
Full API documentation is available [right here](https://apitools.dev/json-schema-ref-parser/docs/)
Contributing
--------------------------
I welcome any contributions, enhancements, and bug-fixes. [Open an issue](https://github.com/APIDevTools/json-schema-ref-parser/issues) on GitHub and [submit a pull request](https://github.com/APIDevTools/json-schema-ref-parser/pulls).
#### Building/Testing
To build/test the project locally on your computer:
1. __Clone this repo__<br>
`git clone https://github.com/APIDevTools/json-schema-ref-parser.git`
2. __Install dependencies__<br>
`npm install`
3. __Run the tests__<br>
`npm test`
License
--------------------------
JSON Schema $Ref Parser is 100% free and open-source, under the [MIT license](LICENSE). Use it however you want.
This package is [Treeware](http://treeware.earth). If you use it in production, then we ask that you [**buy the world a tree**](https://plant.treeware.earth/APIDevTools/json-schema-ref-parser) to thank us for our work. By contributing to the Treeware forest youll be creating employment for local families and restoring wildlife habitats.
Big Thanks To
--------------------------
Thanks to these awesome companies for their support of Open Source developers ❤
[![Stoplight](https://svgshare.com/i/TK5.svg)](https://stoplight.io/?utm_source=github&utm_medium=readme&utm_campaign=json_schema_ref_parser)
[![SauceLabs](https://jstools.dev/img/badges/sauce-labs.svg)](https://saucelabs.com)
[![Coveralls](https://jstools.dev/img/badges/coveralls.svg)](https://coveralls.io)

View File

@ -0,0 +1,261 @@
"use strict";
const $Ref = require("./ref");
const Pointer = require("./pointer");
const url = require("./util/url");
module.exports = bundle;
/**
* Bundles all external JSON references into the main JSON schema, thus resulting in a schema that
* only has *internal* references, not any *external* references.
* This method mutates the JSON schema object, adding new references and re-mapping existing ones.
*
* @param {$RefParser} parser
* @param {$RefParserOptions} options
*/
function bundle (parser, options) {
// console.log('Bundling $ref pointers in %s', parser.$refs._root$Ref.path);
// Build an inventory of all $ref pointers in the JSON Schema
let inventory = [];
crawl(parser, "schema", parser.$refs._root$Ref.path + "#", "#", 0, inventory, parser.$refs, options);
// Remap all $ref pointers
remap(inventory);
}
/**
* Recursively crawls the given value, and inventories all JSON references.
*
* @param {object} parent - The object containing the value to crawl. If the value is not an object or array, it will be ignored.
* @param {string} key - The property key of `parent` to be crawled
* @param {string} path - The full path of the property being crawled, possibly with a JSON Pointer in the hash
* @param {string} pathFromRoot - The path of the property being crawled, from the schema root
* @param {object[]} inventory - An array of already-inventoried $ref pointers
* @param {$Refs} $refs
* @param {$RefParserOptions} options
*/
function crawl (parent, key, path, pathFromRoot, indirections, inventory, $refs, options) {
let obj = key === null ? parent : parent[key];
if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj)) {
if ($Ref.isAllowed$Ref(obj)) {
inventory$Ref(parent, key, path, pathFromRoot, indirections, inventory, $refs, options);
}
else {
// Crawl the object in a specific order that's optimized for bundling.
// This is important because it determines how `pathFromRoot` gets built,
// which later determines which keys get dereferenced and which ones get remapped
let keys = Object.keys(obj)
.sort((a, b) => {
// Most people will expect references to be bundled into the the "definitions" property,
// so we always crawl that property first, if it exists.
if (a === "definitions") {
return -1;
}
else if (b === "definitions") {
return 1;
}
else {
// Otherwise, crawl the keys based on their length.
// This produces the shortest possible bundled references
return a.length - b.length;
}
});
// eslint-disable-next-line no-shadow
for (let key of keys) {
let keyPath = Pointer.join(path, key);
let keyPathFromRoot = Pointer.join(pathFromRoot, key);
let value = obj[key];
if ($Ref.isAllowed$Ref(value)) {
inventory$Ref(obj, key, path, keyPathFromRoot, indirections, inventory, $refs, options);
}
else {
crawl(obj, key, keyPath, keyPathFromRoot, indirections, inventory, $refs, options);
}
}
}
}
}
/**
* Inventories the given JSON Reference (i.e. records detailed information about it so we can
* optimize all $refs in the schema), and then crawls the resolved value.
*
* @param {object} $refParent - The object that contains a JSON Reference as one of its keys
* @param {string} $refKey - The key in `$refParent` that is a JSON Reference
* @param {string} path - The full path of the JSON Reference at `$refKey`, possibly with a JSON Pointer in the hash
* @param {string} pathFromRoot - The path of the JSON Reference at `$refKey`, from the schema root
* @param {object[]} inventory - An array of already-inventoried $ref pointers
* @param {$Refs} $refs
* @param {$RefParserOptions} options
*/
function inventory$Ref ($refParent, $refKey, path, pathFromRoot, indirections, inventory, $refs, options) {
let $ref = $refKey === null ? $refParent : $refParent[$refKey];
let $refPath = url.resolve(path, $ref.$ref);
let pointer = $refs._resolve($refPath, pathFromRoot, options);
if (pointer === null) {
return;
}
let depth = Pointer.parse(pathFromRoot).length;
let file = url.stripHash(pointer.path);
let hash = url.getHash(pointer.path);
let external = file !== $refs._root$Ref.path;
let extended = $Ref.isExtended$Ref($ref);
indirections += pointer.indirections;
let existingEntry = findInInventory(inventory, $refParent, $refKey);
if (existingEntry) {
// This $Ref has already been inventoried, so we don't need to process it again
if (depth < existingEntry.depth || indirections < existingEntry.indirections) {
removeFromInventory(inventory, existingEntry);
}
else {
return;
}
}
inventory.push({
$ref, // The JSON Reference (e.g. {$ref: string})
parent: $refParent, // The object that contains this $ref pointer
key: $refKey, // The key in `parent` that is the $ref pointer
pathFromRoot, // The path to the $ref pointer, from the JSON Schema root
depth, // How far from the JSON Schema root is this $ref pointer?
file, // The file that the $ref pointer resolves to
hash, // The hash within `file` that the $ref pointer resolves to
value: pointer.value, // The resolved value of the $ref pointer
circular: pointer.circular, // Is this $ref pointer DIRECTLY circular? (i.e. it references itself)
extended, // Does this $ref extend its resolved value? (i.e. it has extra properties, in addition to "$ref")
external, // Does this $ref pointer point to a file other than the main JSON Schema file?
indirections, // The number of indirect references that were traversed to resolve the value
});
// Recursively crawl the resolved value
if (!existingEntry) {
crawl(pointer.value, null, pointer.path, pathFromRoot, indirections + 1, inventory, $refs, options);
}
}
/**
* Re-maps every $ref pointer, so that they're all relative to the root of the JSON Schema.
* Each referenced value is dereferenced EXACTLY ONCE. All subsequent references to the same
* value are re-mapped to point to the first reference.
*
* @example:
* {
* first: { $ref: somefile.json#/some/part },
* second: { $ref: somefile.json#/another/part },
* third: { $ref: somefile.json },
* fourth: { $ref: somefile.json#/some/part/sub/part }
* }
*
* In this example, there are four references to the same file, but since the third reference points
* to the ENTIRE file, that's the only one we need to dereference. The other three can just be
* remapped to point inside the third one.
*
* On the other hand, if the third reference DIDN'T exist, then the first and second would both need
* to be dereferenced, since they point to different parts of the file. The fourth reference does NOT
* need to be dereferenced, because it can be remapped to point inside the first one.
*
* @param {object[]} inventory
*/
function remap (inventory) {
// Group & sort all the $ref pointers, so they're in the order that we need to dereference/remap them
inventory.sort((a, b) => {
if (a.file !== b.file) {
// Group all the $refs that point to the same file
return a.file < b.file ? -1 : +1;
}
else if (a.hash !== b.hash) {
// Group all the $refs that point to the same part of the file
return a.hash < b.hash ? -1 : +1;
}
else if (a.circular !== b.circular) {
// If the $ref points to itself, then sort it higher than other $refs that point to this $ref
return a.circular ? -1 : +1;
}
else if (a.extended !== b.extended) {
// If the $ref extends the resolved value, then sort it lower than other $refs that don't extend the value
return a.extended ? +1 : -1;
}
else if (a.indirections !== b.indirections) {
// Sort direct references higher than indirect references
return a.indirections - b.indirections;
}
else if (a.depth !== b.depth) {
// Sort $refs by how close they are to the JSON Schema root
return a.depth - b.depth;
}
else {
// Determine how far each $ref is from the "definitions" property.
// Most people will expect references to be bundled into the the "definitions" property if possible.
let aDefinitionsIndex = a.pathFromRoot.lastIndexOf("/definitions");
let bDefinitionsIndex = b.pathFromRoot.lastIndexOf("/definitions");
if (aDefinitionsIndex !== bDefinitionsIndex) {
// Give higher priority to the $ref that's closer to the "definitions" property
return bDefinitionsIndex - aDefinitionsIndex;
}
else {
// All else is equal, so use the shorter path, which will produce the shortest possible reference
return a.pathFromRoot.length - b.pathFromRoot.length;
}
}
});
let file, hash, pathFromRoot;
for (let entry of inventory) {
// console.log('Re-mapping $ref pointer "%s" at %s', entry.$ref.$ref, entry.pathFromRoot);
if (!entry.external) {
// This $ref already resolves to the main JSON Schema file
entry.$ref.$ref = entry.hash;
}
else if (entry.file === file && entry.hash === hash) {
// This $ref points to the same value as the prevous $ref, so remap it to the same path
entry.$ref.$ref = pathFromRoot;
}
else if (entry.file === file && entry.hash.indexOf(hash + "/") === 0) {
// This $ref points to a sub-value of the prevous $ref, so remap it beneath that path
entry.$ref.$ref = Pointer.join(pathFromRoot, Pointer.parse(entry.hash.replace(hash, "#")));
}
else {
// We've moved to a new file or new hash
file = entry.file;
hash = entry.hash;
pathFromRoot = entry.pathFromRoot;
// This is the first $ref to point to this value, so dereference the value.
// Any other $refs that point to the same value will point to this $ref instead
entry.$ref = entry.parent[entry.key] = $Ref.dereference(entry.$ref, entry.value);
if (entry.circular) {
// This $ref points to itself
entry.$ref.$ref = entry.pathFromRoot;
}
}
// console.log(' new value: %s', (entry.$ref && entry.$ref.$ref) ? entry.$ref.$ref : '[object Object]');
}
}
/**
* TODO
*/
function findInInventory (inventory, $refParent, $refKey) {
for (let i = 0; i < inventory.length; i++) {
let existingEntry = inventory[i];
if (existingEntry.parent === $refParent && existingEntry.key === $refKey) {
return existingEntry;
}
}
}
function removeFromInventory (inventory, entry) {
let index = inventory.indexOf(entry);
inventory.splice(index, 1);
}

View File

@ -0,0 +1,205 @@
"use strict";
const $Ref = require("./ref");
const Pointer = require("./pointer");
const { ono } = require("@jsdevtools/ono");
const url = require("./util/url");
module.exports = dereference;
/**
* Crawls the JSON schema, finds all JSON references, and dereferences them.
* This method mutates the JSON schema object, replacing JSON references with their resolved value.
*
* @param {$RefParser} parser
* @param {$RefParserOptions} options
*/
function dereference (parser, options) {
// console.log('Dereferencing $ref pointers in %s', parser.$refs._root$Ref.path);
let dereferenced = crawl(parser.schema, parser.$refs._root$Ref.path, "#", new Set(), new Set(), new Map(), parser.$refs, options);
parser.$refs.circular = dereferenced.circular;
parser.schema = dereferenced.value;
}
/**
* Recursively crawls the given value, and dereferences any JSON references.
*
* @param {*} obj - The value to crawl. If it's not an object or array, it will be ignored.
* @param {string} path - The full path of `obj`, possibly with a JSON Pointer in the hash
* @param {string} pathFromRoot - The path of `obj` from the schema root
* @param {Set<object>} parents - An array of the parent objects that have already been dereferenced
* @param {Set<object>} processedObjects - An array of all the objects that have already been processed
* @param {Map<string,object>} dereferencedCache - An map of all the dereferenced objects
* @param {$Refs} $refs
* @param {$RefParserOptions} options
* @returns {{value: object, circular: boolean}}
*/
function crawl (obj, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options) {
let dereferenced;
let result = {
value: obj,
circular: false
};
let isExcludedPath = options.dereference.excludedPathMatcher;
if (options.dereference.circular === "ignore" || !processedObjects.has(obj)) {
if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj) && !isExcludedPath(pathFromRoot)) {
parents.add(obj);
processedObjects.add(obj);
if ($Ref.isAllowed$Ref(obj, options)) {
dereferenced = dereference$Ref(obj, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options);
result.circular = dereferenced.circular;
result.value = dereferenced.value;
}
else {
for (const key of Object.keys(obj)) {
let keyPath = Pointer.join(path, key);
let keyPathFromRoot = Pointer.join(pathFromRoot, key);
if (isExcludedPath(keyPathFromRoot)) {
continue;
}
let value = obj[key];
let circular = false;
if ($Ref.isAllowed$Ref(value, options)) {
dereferenced = dereference$Ref(value, keyPath, keyPathFromRoot, parents, processedObjects, dereferencedCache, $refs, options);
circular = dereferenced.circular;
// Avoid pointless mutations; breaks frozen objects to no profit
if (obj[key] !== dereferenced.value) {
obj[key] = dereferenced.value;
}
}
else {
if (!parents.has(value)) {
dereferenced = crawl(value, keyPath, keyPathFromRoot, parents, processedObjects, dereferencedCache, $refs, options);
circular = dereferenced.circular;
// Avoid pointless mutations; breaks frozen objects to no profit
if (obj[key] !== dereferenced.value) {
obj[key] = dereferenced.value;
}
}
else {
circular = foundCircularReference(keyPath, $refs, options);
}
}
// Set the "isCircular" flag if this or any other property is circular
result.circular = result.circular || circular;
}
}
parents.delete(obj);
}
}
return result;
}
/**
* Dereferences the given JSON Reference, and then crawls the resulting value.
*
* @param {{$ref: string}} $ref - The JSON Reference to resolve
* @param {string} path - The full path of `$ref`, possibly with a JSON Pointer in the hash
* @param {string} pathFromRoot - The path of `$ref` from the schema root
* @param {Set<object>} parents - An array of the parent objects that have already been dereferenced
* @param {Set<object>} processedObjects - An array of all the objects that have already been dereferenced
* @param {Map<string,object>} dereferencedCache - An map of all the dereferenced objects
* @param {$Refs} $refs
* @param {$RefParserOptions} options
* @returns {{value: object, circular: boolean}}
*/
function dereference$Ref ($ref, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options) {
// console.log('Dereferencing $ref pointer "%s" at %s', $ref.$ref, path);
let $refPath = url.resolve(path, $ref.$ref);
const cache = dereferencedCache.get($refPath);
if (cache) {
const refKeys = Object.keys($ref);
if (refKeys.length > 1) {
const extraKeys = {};
for (let key of refKeys) {
if (key !== "$ref" && !(key in cache.value)) {
extraKeys[key] = $ref[key];
}
}
return {
circular: cache.circular,
value: Object.assign({}, cache.value, extraKeys),
};
}
return cache;
}
let pointer = $refs._resolve($refPath, path, options);
if (pointer === null) {
return {
circular: false,
value: null,
};
}
// Check for circular references
let directCircular = pointer.circular;
let circular = directCircular || parents.has(pointer.value);
circular && foundCircularReference(path, $refs, options);
// Dereference the JSON reference
let dereferencedValue = $Ref.dereference($ref, pointer.value);
// Crawl the dereferenced value (unless it's circular)
if (!circular) {
// Determine if the dereferenced value is circular
let dereferenced = crawl(dereferencedValue, pointer.path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options);
circular = dereferenced.circular;
dereferencedValue = dereferenced.value;
}
if (circular && !directCircular && options.dereference.circular === "ignore") {
// The user has chosen to "ignore" circular references, so don't change the value
dereferencedValue = $ref;
}
if (directCircular) {
// The pointer is a DIRECT circular reference (i.e. it references itself).
// So replace the $ref path with the absolute path from the JSON Schema root
dereferencedValue.$ref = pathFromRoot;
}
const dereferencedObject = {
circular,
value: dereferencedValue
};
// only cache if no extra properties than $ref
if (Object.keys($ref).length === 1) {
dereferencedCache.set($refPath, dereferencedObject);
}
return dereferencedObject;
}
/**
* Called when a circular reference is found.
* It sets the {@link $Refs#circular} flag, and throws an error if options.dereference.circular is false.
*
* @param {string} keyPath - The JSON Reference path of the circular reference
* @param {$Refs} $refs
* @param {$RefParserOptions} options
* @returns {boolean} - always returns true, to indicate that a circular reference was found
*/
function foundCircularReference (keyPath, $refs, options) {
$refs.circular = true;
if (!options.dereference.circular) {
throw ono.reference(`Circular $ref pointer found at ${keyPath}`);
}
return true;
}

View File

@ -0,0 +1,487 @@
import { JSONSchema4, JSONSchema4Type, JSONSchema6, JSONSchema6Type, JSONSchema7, JSONSchema7Type } from "json-schema";
export = $RefParser;
/**
* This is the default export of JSON Schema $Ref Parser. You can creates instances of this class using new $RefParser(), or you can just call its static methods.
*
* See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html
*/
declare class $RefParser {
/**
* The `schema` property is the parsed/bundled/dereferenced JSON Schema object. This is the same value that is passed to the callback function (or Promise) when calling the parse, bundle, or dereference methods.
*
* See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#schema
*/
public schema: $RefParser.JSONSchema;
/**
* The $refs property is a `$Refs` object, which lets you access all of the externally-referenced files in the schema, as well as easily get and set specific values in the schema using JSON pointers.
*
* This is the same value that is passed to the callback function (or Promise) when calling the `resolve` method.
*
* See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#refs
*/
public $refs: $RefParser.$Refs;
/**
* Dereferences all `$ref` pointers in the JSON Schema, replacing each reference with its resolved value. This results in a schema object that does not contain any `$ref` pointers. Instead, it's a normal JavaScript object tree that can easily be crawled and used just like any other JavaScript object. This is great for programmatic usage, especially when using tools that don't understand JSON references.
*
* The dereference method maintains object reference equality, meaning that all `$ref` pointers that point to the same object will be replaced with references to the same object. Again, this is great for programmatic usage, but it does introduce the risk of circular references, so be careful if you intend to serialize the schema using `JSON.stringify()`. Consider using the bundle method instead, which does not create circular references.
*
* See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#dereferenceschema-options-callback
*
* @param schema A JSON Schema object, or the file path or URL of a JSON Schema file. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the dereferenced schema object
*/
public dereference(schema: string | $RefParser.JSONSchema, callback: $RefParser.SchemaCallback): void;
public dereference(schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.SchemaCallback): void;
public dereference(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.SchemaCallback): void;
public dereference(schema: string | $RefParser.JSONSchema): Promise<$RefParser.JSONSchema>;
public dereference(schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.JSONSchema>;
public dereference(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.JSONSchema>;
/**
* Dereferences all `$ref` pointers in the JSON Schema, replacing each reference with its resolved value. This results in a schema object that does not contain any `$ref` pointers. Instead, it's a normal JavaScript object tree that can easily be crawled and used just like any other JavaScript object. This is great for programmatic usage, especially when using tools that don't understand JSON references.
*
* The dereference method maintains object reference equality, meaning that all `$ref` pointers that point to the same object will be replaced with references to the same object. Again, this is great for programmatic usage, but it does introduce the risk of circular references, so be careful if you intend to serialize the schema using `JSON.stringify()`. Consider using the bundle method instead, which does not create circular references.
*
* See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#dereferenceschema-options-callback
*
* @param schema A JSON Schema object, or the file path or URL of a JSON Schema file. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the dereferenced schema object
*/
public static dereference(schema: string | $RefParser.JSONSchema, callback: $RefParser.SchemaCallback): void;
public static dereference(schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.SchemaCallback): void;
public static dereference(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.SchemaCallback): void;
public static dereference(schema: string | $RefParser.JSONSchema): Promise<$RefParser.JSONSchema>;
public static dereference(schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.JSONSchema>;
public static dereference(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.JSONSchema>;
/**
* Bundles all referenced files/URLs into a single schema that only has internal `$ref` pointers. This lets you split-up your schema however you want while you're building it, but easily combine all those files together when it's time to package or distribute the schema to other people. The resulting schema size will be small, since it will still contain internal JSON references rather than being fully-dereferenced.
*
* This also eliminates the risk of circular references, so the schema can be safely serialized using `JSON.stringify()`.
*
* See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#bundleschema-options-callback
*
* @param schema A JSON Schema object, or the file path or URL of a JSON Schema file. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the bundled schema object
*/
public bundle(schema: string | $RefParser.JSONSchema, callback: $RefParser.SchemaCallback): void;
public bundle(schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.SchemaCallback): void;
public bundle(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.SchemaCallback): void;
public bundle(schema: string | $RefParser.JSONSchema): Promise<$RefParser.JSONSchema>;
public bundle(schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.JSONSchema>;
public bundle(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.JSONSchema>;
/**
* Bundles all referenced files/URLs into a single schema that only has internal `$ref` pointers. This lets you split-up your schema however you want while you're building it, but easily combine all those files together when it's time to package or distribute the schema to other people. The resulting schema size will be small, since it will still contain internal JSON references rather than being fully-dereferenced.
*
* This also eliminates the risk of circular references, so the schema can be safely serialized using `JSON.stringify()`.
*
* See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#bundleschema-options-callback
*
* @param schema A JSON Schema object, or the file path or URL of a JSON Schema file. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the bundled schema object
*/
public static bundle(schema: string | $RefParser.JSONSchema, callback: $RefParser.SchemaCallback): void;
public static bundle(schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.SchemaCallback): void;
public static bundle(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.SchemaCallback): void;
public static bundle(schema: string | $RefParser.JSONSchema): Promise<$RefParser.JSONSchema>;
public static bundle(schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.JSONSchema>;
public static bundle(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.JSONSchema>;
/**
* *This method is used internally by other methods, such as `bundle` and `dereference`. You probably won't need to call this method yourself.*
*
* Parses the given JSON Schema file (in JSON or YAML format), and returns it as a JavaScript object. This method `does not` resolve `$ref` pointers or dereference anything. It simply parses one file and returns it.
*
* See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#parseschema-options-callback
*
* @param schema A JSON Schema object, or the file path or URL of a JSON Schema file. The path can be absolute or relative. In Node, the path is relative to `process.cwd()`. In the browser, it's relative to the URL of the page.
* @param options (optional)
* @param callback (optional) A callback that will receive the parsed schema object, or an error
*/
public parse(schema: string | $RefParser.JSONSchema, callback: $RefParser.SchemaCallback): void;
public parse(schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.SchemaCallback): void;
public parse(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.SchemaCallback): void;
public parse(schema: string | $RefParser.JSONSchema): Promise<$RefParser.JSONSchema>;
public parse(schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.JSONSchema>;
public parse(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.JSONSchema>;
/**
* *This method is used internally by other methods, such as `bundle` and `dereference`. You probably won't need to call this method yourself.*
*
* Parses the given JSON Schema file (in JSON or YAML format), and returns it as a JavaScript object. This method `does not` resolve `$ref` pointers or dereference anything. It simply parses one file and returns it.
*
* See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#parseschema-options-callback
*
* @param schema A JSON Schema object, or the file path or URL of a JSON Schema file. The path can be absolute or relative. In Node, the path is relative to `process.cwd()`. In the browser, it's relative to the URL of the page.
* @param options (optional)
* @param callback (optional) A callback that will receive the parsed schema object, or an error
*/
public static parse(schema: string | $RefParser.JSONSchema, callback: $RefParser.SchemaCallback): void;
public static parse(schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.SchemaCallback): void;
public static parse(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.SchemaCallback): void;
public static parse(schema: string | $RefParser.JSONSchema): Promise<$RefParser.JSONSchema>;
public static parse(schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.JSONSchema>;
public static parse(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.JSONSchema>;
/**
* *This method is used internally by other methods, such as `bundle` and `dereference`. You probably won't need to call this method yourself.*
*
* Resolves all JSON references (`$ref` pointers) in the given JSON Schema file. If it references any other files/URLs, then they will be downloaded and resolved as well. This method **does not** dereference anything. It simply gives you a `$Refs` object, which is a map of all the resolved references and their values.
*
* See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#resolveschema-options-callback
*
* @param schema A JSON Schema object, or the file path or URL of a JSON Schema file. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive a `$Refs` object
*/
public resolve(schema: string | $RefParser.JSONSchema, callback: $RefParser.$RefsCallback): void;
public resolve(schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.$RefsCallback): void;
public resolve(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.$RefsCallback): void;
public resolve(schema: string | $RefParser.JSONSchema): Promise<$RefParser.$Refs>;
public resolve(schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.$Refs>;
public resolve(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.$Refs>;
/**
* *This method is used internally by other methods, such as `bundle` and `dereference`. You probably won't need to call this method yourself.*
*
* Resolves all JSON references (`$ref` pointers) in the given JSON Schema file. If it references any other files/URLs, then they will be downloaded and resolved as well. This method **does not** dereference anything. It simply gives you a `$Refs` object, which is a map of all the resolved references and their values.
*
* See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#resolveschema-options-callback
*
* @param schema A JSON Schema object, or the file path or URL of a JSON Schema file. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive a `$Refs` object
*/
public static resolve(schema: string | $RefParser.JSONSchema, callback: $RefParser.$RefsCallback): void;
public static resolve(schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.$RefsCallback): void;
public static resolve(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options, callback: $RefParser.$RefsCallback): void;
public static resolve(schema: string | $RefParser.JSONSchema): Promise<$RefParser.$Refs>;
public static resolve(schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.$Refs>;
public static resolve(baseUrl: string, schema: string | $RefParser.JSONSchema, options: $RefParser.Options): Promise<$RefParser.$Refs>;
}
// eslint-disable-next-line no-redeclare
declare namespace $RefParser {
export type JSONSchema = JSONSchema4 | JSONSchema6 | JSONSchema7;
export type SchemaCallback = (err: Error | null, schema?: JSONSchema) => any;
export type $RefsCallback = (err: Error | null, $refs?: $Refs) => any;
/**
* See https://apitools.dev/json-schema-ref-parser/docs/options.html
*/
export interface Options {
/**
* The `parse` options determine how different types of files will be parsed.
*
* JSON Schema `$Ref` Parser comes with built-in JSON, YAML, plain-text, and binary parsers, any of which you can configure or disable. You can also add your own custom parsers if you want.
*/
parse?: {
json?: ParserOptions | boolean;
yaml?: ParserOptions | boolean;
text?: (ParserOptions & { encoding?: string }) | boolean;
[key: string]: ParserOptions | boolean | undefined;
};
/**
* The `resolve` options control how JSON Schema $Ref Parser will resolve file paths and URLs, and how those files will be read/downloaded.
*
* JSON Schema `$Ref` Parser comes with built-in support for HTTP and HTTPS, as well as support for local files (when running in Node.js). You can configure or disable either of these built-in resolvers. You can also add your own custom resolvers if you want.
*/
resolve?: {
/**
* Determines whether external $ref pointers will be resolved. If this option is disabled, then external `$ref` pointers will simply be ignored.
*/
external?: boolean;
file?: Partial<ResolverOptions> | boolean;
http?: HTTPResolverOptions | boolean;
} & {
[key: string]: Partial<ResolverOptions> | HTTPResolverOptions | boolean | undefined;
};
/**
* By default, JSON Schema $Ref Parser throws the first error it encounters. Setting `continueOnError` to `true`
* causes it to keep processing as much as possible and then throw a single error that contains all errors
* that were encountered.
*/
continueOnError?: boolean;
/**
* The `dereference` options control how JSON Schema `$Ref` Parser will dereference `$ref` pointers within the JSON schema.
*/
dereference?: {
/**
* Determines whether circular `$ref` pointers are handled.
*
* If set to `false`, then a `ReferenceError` will be thrown if the schema contains any circular references.
*
* If set to `"ignore"`, then circular references will simply be ignored. No error will be thrown, but the `$Refs.circular` property will still be set to `true`.
*/
circular?: boolean | "ignore";
/**
* A function, called for each path, which can return true to stop this path and all
* subpaths from being dereferenced further. This is useful in schemas where some
* subpaths contain literal $ref keys that should not be dereferenced.
*/
excludedPathMatcher?(path: string): boolean;
};
}
export interface HTTPResolverOptions extends Partial<ResolverOptions> {
/**
* You can specify any HTTP headers that should be sent when downloading files. For example, some servers may require you to set the `Accept` or `Referrer` header.
*/
headers?: object;
/**
* The amount of time (in milliseconds) to wait for a response from the server when downloading files. The default is 5 seconds.
*/
timeout?: number;
/**
* The maximum number of HTTP redirects to follow per file. The default is 5. To disable automatic following of redirects, set this to zero.
*/
redirects?: number;
/**
* Set this to `true` if you're downloading files from a CORS-enabled server that requires authentication
*/
withCredentials?: boolean;
}
/**
* JSON Schema `$Ref` Parser comes with built-in resolvers for HTTP and HTTPS URLs, as well as local filesystem paths (when running in Node.js). You can add your own custom resolvers to support additional protocols, or even replace any of the built-in resolvers with your own custom implementation.
*
* See https://apitools.dev/json-schema-ref-parser/docs/plugins/resolvers.html
*/
export interface ResolverOptions {
/**
* All resolvers have an order property, even the built-in resolvers. If you don't specify an order property, then your resolver will run last. Specifying `order: 1`, like we did in this example, will make your resolver run first. Or you can squeeze your resolver in-between some of the built-in resolvers. For example, `order: 101` would make it run after the file resolver, but before the HTTP resolver. You can see the order of all the built-in resolvers by looking at their source code.
*
* The order property and canRead property are related to each other. For each file that JSON Schema $Ref Parser needs to resolve, it first determines which resolvers can read that file by checking their canRead property. If only one resolver matches a file, then only that one resolver is called, regardless of its order. If multiple resolvers match a file, then those resolvers are tried in order until one of them successfully reads the file. Once a resolver successfully reads the file, the rest of the resolvers are skipped.
*/
order?: number;
/**
* The `canRead` property tells JSON Schema `$Ref` Parser what kind of files your resolver can read. In this example, we've simply specified a regular expression that matches "mogodb://" URLs, but we could have used a simple boolean, or even a function with custom logic to determine which files to resolve. Here are examples of each approach:
*/
canRead: boolean | RegExp | string | string[] | ((file: FileInfo) => boolean);
/**
* This is where the real work of a resolver happens. The `read` method accepts the same file info object as the `canRead` function, but rather than returning a boolean value, the `read` method should return the contents of the file. The file contents should be returned in as raw a form as possible, such as a string or a byte array. Any further parsing or processing should be done by parsers.
*
* Unlike the `canRead` function, the `read` method can also be asynchronous. This might be important if your resolver needs to read data from a database or some other external source. You can return your asynchronous value using either an ES6 Promise or a Node.js-style error-first callback. Of course, if your resolver has the ability to return its data synchronously, then that's fine too. Here are examples of all three approaches:
*/
read(
file: FileInfo,
callback?: (error: Error | null, data: string | null) => any
): string | Buffer | JSONSchema | Promise<string | Buffer | JSONSchema>;
}
export interface ParserOptions {
/**
* Parsers run in a specific order, relative to other parsers. For example, a parser with `order: 5` will run before a parser with `order: 10`. If a parser is unable to successfully parse a file, then the next parser is tried, until one succeeds or they all fail.
*
* You can change the order in which parsers run, which is useful if you know that most of your referenced files will be a certain type, or if you add your own custom parser that you want to run first.
*/
order?: number;
/**
* All of the built-in parsers allow empty files by default. The JSON and YAML parsers will parse empty files as `undefined`. The text parser will parse empty files as an empty string. The binary parser will parse empty files as an empty byte array.
*
* You can set `allowEmpty: false` on any parser, which will cause an error to be thrown if a file empty.
*/
allowEmpty?: boolean;
/**
* Determines which parsers will be used for which files.
*
* A regular expression can be used to match files by their full path. A string (or array of strings) can be used to match files by their file extension. Or a function can be used to perform more complex matching logic. See the custom parser docs for details.
*/
canParse?: boolean | RegExp | string | string[] | ((file: FileInfo) => boolean);
/**
* This is where the real work of a parser happens. The `parse` method accepts the same file info object as the `canParse` function, but rather than returning a boolean value, the `parse` method should return a JavaScript representation of the file contents. For our CSV parser, that is a two-dimensional array of lines and values. For your parser, it might be an object, a string, a custom class, or anything else.
*
* Unlike the `canParse` function, the `parse` method can also be asynchronous. This might be important if your parser needs to retrieve data from a database or if it relies on an external HTTP service to return the parsed value. You can return your asynchronous value via a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or a Node.js-style error-first callback. Here are examples of both approaches:
*/
parse(
file: FileInfo,
callback?: (error: Error | null, data: string | null) => any
): unknown | Promise<unknown>;
}
/**
* JSON Schema `$Ref` Parser supports plug-ins, such as resolvers and parsers. These plug-ins can have methods such as `canRead()`, `read()`, `canParse()`, and `parse()`. All of these methods accept the same object as their parameter: an object containing information about the file being read or parsed.
*
* The file info object currently only consists of a few properties, but it may grow in the future if plug-ins end up needing more information.
*
* See https://apitools.dev/json-schema-ref-parser/docs/plugins/file-info-object.html
*/
export interface FileInfo {
/**
* The full URL of the file. This could be any type of URL, including "http://", "https://", "file://", "ftp://", "mongodb://", or even a local filesystem path (when running in Node.js).
*/
url: string;
/**
* The lowercase file extension, such as ".json", ".yaml", ".txt", etc.
*/
extension: string;
/**
* The raw file contents, in whatever form they were returned by the resolver that read the file.
*/
data: string | Buffer;
}
/**
* When you call the resolve method, the value that gets passed to the callback function (or Promise) is a $Refs object. This same object is accessible via the parser.$refs property of $RefParser objects.
*
* This object is a map of JSON References and their resolved values. It also has several convenient helper methods that make it easy for you to navigate and manipulate the JSON References.
*
* See https://apitools.dev/json-schema-ref-parser/docs/refs.html
*/
export class $Refs {
/**
* This property is true if the schema contains any circular references. You may want to check this property before serializing the dereferenced schema as JSON, since JSON.stringify() does not support circular references by default.
*
* See https://apitools.dev/json-schema-ref-parser/docs/refs.html#circular
*/
public circular: boolean;
/**
* Returns the paths/URLs of all the files in your schema (including the main schema file).
*
* See https://apitools.dev/json-schema-ref-parser/docs/refs.html#pathstypes
*
* @param types (optional) Optionally only return certain types of paths ("file", "http", etc.)
*/
public paths(...types: string[]): string[]
/**
* Returns a map of paths/URLs and their correspond values.
*
* See https://apitools.dev/json-schema-ref-parser/docs/refs.html#valuestypes
*
* @param types (optional) Optionally only return values from certain locations ("file", "http", etc.)
*/
public values(...types: string[]): { [url: string]: $RefParser.JSONSchema }
/**
* Returns `true` if the given path exists in the schema; otherwise, returns `false`
*
* See https://apitools.dev/json-schema-ref-parser/docs/refs.html#existsref
*
* @param $ref The JSON Reference path, optionally with a JSON Pointer in the hash
*/
public exists($ref: string): boolean
/**
* Gets the value at the given path in the schema. Throws an error if the path does not exist.
*
* See https://apitools.dev/json-schema-ref-parser/docs/refs.html#getref
*
* @param $ref The JSON Reference path, optionally with a JSON Pointer in the hash
*/
public get($ref: string): JSONSchema4Type | JSONSchema6Type | JSONSchema7Type
/**
* Sets the value at the given path in the schema. If the property, or any of its parents, don't exist, they will be created.
*
* @param $ref The JSON Reference path, optionally with a JSON Pointer in the hash
* @param value The value to assign. Can be anything (object, string, number, etc.)
*/
public set($ref: string, value: JSONSchema4Type | JSONSchema6Type | JSONSchema7Type): void
}
export type JSONParserErrorType = "EUNKNOWN" | "EPARSER" | "EUNMATCHEDPARSER" | "ERESOLVER" | "EUNMATCHEDRESOLVER" | "EMISSINGPOINTER" | "EINVALIDPOINTER";
export class JSONParserError extends Error {
public constructor(message: string, source: string);
public readonly name: string;
public readonly message: string;
public readonly source: string;
public readonly path: Array<string | number>;
public readonly errors: string;
public readonly code: JSONParserErrorType;
}
export class JSONParserErrorGroup extends Error {
/**
* List of all errors
*
* See https://github.com/APIDevTools/json-schema-ref-parser/blob/master/docs/ref-parser.md#errors
*/
public readonly errors: Array<$RefParser.JSONParserError | $RefParser.InvalidPointerError | $RefParser.ResolverError | $RefParser.ParserError | $RefParser.MissingPointerError | $RefParser.UnmatchedParserError | $RefParser.UnmatchedResolverError>;
/**
* The fields property is a `$RefParser` instance
*
* See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html
*/
public readonly files: $RefParser;
/**
* User friendly message containing the total amount of errors, as well as the absolute path to the source document
*/
public readonly message: string;
}
export class ParserError extends JSONParserError {
public constructor(message: string, source: string);
public readonly name = "ParserError";
public readonly code = "EPARSER";
}
export class UnmatchedParserError extends JSONParserError {
public constructor(source: string);
public readonly name = "UnmatchedParserError";
public readonly code = "EUNMATCHEDPARSER";
}
export class ResolverError extends JSONParserError {
public constructor(ex: Error | NodeJS.ErrnoException, source: string);
public readonly name = "ResolverError";
public readonly code = "ERESOLVER";
public readonly ioErrorCode?: string;
}
export class UnmatchedResolverError extends JSONParserError {
public constructor(source: string);
public readonly name = "UnmatchedResolverError";
public readonly code = "EUNMATCHEDRESOLVER";
}
export class MissingPointerError extends JSONParserError {
public constructor(token: string | number, source: string);
public readonly name = "MissingPointerError";
public readonly code = "EMISSINGPOINTER";
}
export class InvalidPointerError extends JSONParserError {
public constructor(pointer: string, source: string);
public readonly name = "InvalidPointerError";
public readonly code = "EINVALIDPOINTER";
}
}

View File

@ -0,0 +1,283 @@
/* eslint-disable no-unused-vars */
"use strict";
const $Refs = require("./refs");
const _parse = require("./parse");
const normalizeArgs = require("./normalize-args");
const resolveExternal = require("./resolve-external");
const _bundle = require("./bundle");
const _dereference = require("./dereference");
const url = require("./util/url");
const { JSONParserError, InvalidPointerError, MissingPointerError, ResolverError, ParserError, UnmatchedParserError, UnmatchedResolverError, isHandledError, JSONParserErrorGroup } = require("./util/errors");
const maybe = require("call-me-maybe");
const { ono } = require("@jsdevtools/ono");
module.exports = $RefParser;
module.exports.default = $RefParser;
module.exports.JSONParserError = JSONParserError;
module.exports.InvalidPointerError = InvalidPointerError;
module.exports.MissingPointerError = MissingPointerError;
module.exports.ResolverError = ResolverError;
module.exports.ParserError = ParserError;
module.exports.UnmatchedParserError = UnmatchedParserError;
module.exports.UnmatchedResolverError = UnmatchedResolverError;
/**
* This class parses a JSON schema, builds a map of its JSON references and their resolved values,
* and provides methods for traversing, manipulating, and dereferencing those references.
*
* @constructor
*/
function $RefParser () {
/**
* The parsed (and possibly dereferenced) JSON schema object
*
* @type {object}
* @readonly
*/
this.schema = null;
/**
* The resolved JSON references
*
* @type {$Refs}
* @readonly
*/
this.$refs = new $Refs();
}
/**
* Parses the given JSON schema.
* This method does not resolve any JSON references.
* It just reads a single file in JSON or YAML format, and parse it as a JavaScript object.
*
* @param {string} [path] - The file path or URL of the JSON schema
* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed
* @param {function} [callback] - An error-first callback. The second parameter is the parsed JSON schema object.
* @returns {Promise} - The returned promise resolves with the parsed JSON schema object.
*/
$RefParser.parse = function parse (path, schema, options, callback) {
let Class = this; // eslint-disable-line consistent-this
let instance = new Class();
return instance.parse.apply(instance, arguments);
};
/**
* Parses the given JSON schema.
* This method does not resolve any JSON references.
* It just reads a single file in JSON or YAML format, and parse it as a JavaScript object.
*
* @param {string} [path] - The file path or URL of the JSON schema
* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed
* @param {function} [callback] - An error-first callback. The second parameter is the parsed JSON schema object.
* @returns {Promise} - The returned promise resolves with the parsed JSON schema object.
*/
$RefParser.prototype.parse = async function parse (path, schema, options, callback) {
let args = normalizeArgs(arguments);
let promise;
if (!args.path && !args.schema) {
let err = ono(`Expected a file path, URL, or object. Got ${args.path || args.schema}`);
return maybe(args.callback, Promise.reject(err));
}
// Reset everything
this.schema = null;
this.$refs = new $Refs();
// If the path is a filesystem path, then convert it to a URL.
// NOTE: According to the JSON Reference spec, these should already be URLs,
// but, in practice, many people use local filesystem paths instead.
// So we're being generous here and doing the conversion automatically.
// This is not intended to be a 100% bulletproof solution.
// If it doesn't work for your use-case, then use a URL instead.
let pathType = "http";
if (url.isFileSystemPath(args.path)) {
args.path = url.fromFileSystemPath(args.path);
pathType = "file";
}
// Resolve the absolute path of the schema
args.path = url.resolve(url.cwd(), args.path);
if (args.schema && typeof args.schema === "object") {
// A schema object was passed-in.
// So immediately add a new $Ref with the schema object as its value
let $ref = this.$refs._add(args.path);
$ref.value = args.schema;
$ref.pathType = pathType;
promise = Promise.resolve(args.schema);
}
else {
// Parse the schema file/url
promise = _parse(args.path, this.$refs, args.options);
}
let me = this;
try {
let result = await promise;
if (result !== null && typeof result === "object" && !Buffer.isBuffer(result)) {
me.schema = result;
return maybe(args.callback, Promise.resolve(me.schema));
}
else if (args.options.continueOnError) {
me.schema = null; // it's already set to null at line 79, but let's set it again for the sake of readability
return maybe(args.callback, Promise.resolve(me.schema));
}
else {
throw ono.syntax(`"${me.$refs._root$Ref.path || result}" is not a valid JSON Schema`);
}
}
catch (err) {
if (!args.options.continueOnError || !isHandledError(err)) {
return maybe(args.callback, Promise.reject(err));
}
if (this.$refs._$refs[url.stripHash(args.path)]) {
this.$refs._$refs[url.stripHash(args.path)].addError(err);
}
return maybe(args.callback, Promise.resolve(null));
}
};
/**
* Parses the given JSON schema and resolves any JSON references, including references in
* externally-referenced files.
*
* @param {string} [path] - The file path or URL of the JSON schema
* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed and resolved
* @param {function} [callback]
* - An error-first callback. The second parameter is a {@link $Refs} object containing the resolved JSON references
*
* @returns {Promise}
* The returned promise resolves with a {@link $Refs} object containing the resolved JSON references
*/
$RefParser.resolve = function resolve (path, schema, options, callback) {
let Class = this; // eslint-disable-line consistent-this
let instance = new Class();
return instance.resolve.apply(instance, arguments);
};
/**
* Parses the given JSON schema and resolves any JSON references, including references in
* externally-referenced files.
*
* @param {string} [path] - The file path or URL of the JSON schema
* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed and resolved
* @param {function} [callback]
* - An error-first callback. The second parameter is a {@link $Refs} object containing the resolved JSON references
*
* @returns {Promise}
* The returned promise resolves with a {@link $Refs} object containing the resolved JSON references
*/
$RefParser.prototype.resolve = async function resolve (path, schema, options, callback) {
let me = this;
let args = normalizeArgs(arguments);
try {
await this.parse(args.path, args.schema, args.options);
await resolveExternal(me, args.options);
finalize(me);
return maybe(args.callback, Promise.resolve(me.$refs));
}
catch (err) {
return maybe(args.callback, Promise.reject(err));
}
};
/**
* Parses the given JSON schema, resolves any JSON references, and bundles all external references
* into the main JSON schema. This produces a JSON schema that only has *internal* references,
* not any *external* references.
*
* @param {string} [path] - The file path or URL of the JSON schema
* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced
* @param {function} [callback] - An error-first callback. The second parameter is the bundled JSON schema object
* @returns {Promise} - The returned promise resolves with the bundled JSON schema object.
*/
$RefParser.bundle = function bundle (path, schema, options, callback) {
let Class = this; // eslint-disable-line consistent-this
let instance = new Class();
return instance.bundle.apply(instance, arguments);
};
/**
* Parses the given JSON schema, resolves any JSON references, and bundles all external references
* into the main JSON schema. This produces a JSON schema that only has *internal* references,
* not any *external* references.
*
* @param {string} [path] - The file path or URL of the JSON schema
* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced
* @param {function} [callback] - An error-first callback. The second parameter is the bundled JSON schema object
* @returns {Promise} - The returned promise resolves with the bundled JSON schema object.
*/
$RefParser.prototype.bundle = async function bundle (path, schema, options, callback) {
let me = this;
let args = normalizeArgs(arguments);
try {
await this.resolve(args.path, args.schema, args.options);
_bundle(me, args.options);
finalize(me);
return maybe(args.callback, Promise.resolve(me.schema));
}
catch (err) {
return maybe(args.callback, Promise.reject(err));
}
};
/**
* Parses the given JSON schema, resolves any JSON references, and dereferences the JSON schema.
* That is, all JSON references are replaced with their resolved values.
*
* @param {string} [path] - The file path or URL of the JSON schema
* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced
* @param {function} [callback] - An error-first callback. The second parameter is the dereferenced JSON schema object
* @returns {Promise} - The returned promise resolves with the dereferenced JSON schema object.
*/
$RefParser.dereference = function dereference (path, schema, options, callback) {
let Class = this; // eslint-disable-line consistent-this
let instance = new Class();
return instance.dereference.apply(instance, arguments);
};
/**
* Parses the given JSON schema, resolves any JSON references, and dereferences the JSON schema.
* That is, all JSON references are replaced with their resolved values.
*
* @param {string} [path] - The file path or URL of the JSON schema
* @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
* @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced
* @param {function} [callback] - An error-first callback. The second parameter is the dereferenced JSON schema object
* @returns {Promise} - The returned promise resolves with the dereferenced JSON schema object.
*/
$RefParser.prototype.dereference = async function dereference (path, schema, options, callback) {
let me = this;
let args = normalizeArgs(arguments);
try {
await this.resolve(args.path, args.schema, args.options);
_dereference(me, args.options);
finalize(me);
return maybe(args.callback, Promise.resolve(me.schema));
}
catch (err) {
return maybe(args.callback, Promise.reject(err));
}
};
function finalize (parser) {
const errors = JSONParserErrorGroup.getParserErrors(parser);
if (errors.length > 0) {
throw new JSONParserErrorGroup(parser);
}
}

View File

@ -0,0 +1,53 @@
"use strict";
const Options = require("./options");
module.exports = normalizeArgs;
/**
* Normalizes the given arguments, accounting for optional args.
*
* @param {Arguments} args
* @returns {object}
*/
function normalizeArgs (args) {
let path, schema, options, callback;
args = Array.prototype.slice.call(args);
if (typeof args[args.length - 1] === "function") {
// The last parameter is a callback function
callback = args.pop();
}
if (typeof args[0] === "string") {
// The first parameter is the path
path = args[0];
if (typeof args[2] === "object") {
// The second parameter is the schema, and the third parameter is the options
schema = args[1];
options = args[2];
}
else {
// The second parameter is the options
schema = undefined;
options = args[1];
}
}
else {
// The first parameter is the schema
path = "";
schema = args[0];
options = args[1];
}
if (!(options instanceof Options)) {
options = new Options(options);
}
return {
path,
schema,
options,
callback
};
}

View File

@ -0,0 +1,130 @@
/* eslint lines-around-comment: [2, {beforeBlockComment: false}] */
"use strict";
const jsonParser = require("./parsers/json");
const yamlParser = require("./parsers/yaml");
const textParser = require("./parsers/text");
const binaryParser = require("./parsers/binary");
const fileResolver = require("./resolvers/file");
const httpResolver = require("./resolvers/http");
module.exports = $RefParserOptions;
/**
* Options that determine how JSON schemas are parsed, resolved, and dereferenced.
*
* @param {object|$RefParserOptions} [options] - Overridden options
* @constructor
*/
function $RefParserOptions (options) {
merge(this, $RefParserOptions.defaults);
merge(this, options);
}
$RefParserOptions.defaults = {
/**
* Determines how different types of files will be parsed.
*
* You can add additional parsers of your own, replace an existing one with
* your own implementation, or disable any parser by setting it to false.
*/
parse: {
json: jsonParser,
yaml: yamlParser,
text: textParser,
binary: binaryParser,
},
/**
* Determines how JSON References will be resolved.
*
* You can add additional resolvers of your own, replace an existing one with
* your own implementation, or disable any resolver by setting it to false.
*/
resolve: {
file: fileResolver,
http: httpResolver,
/**
* Determines whether external $ref pointers will be resolved.
* If this option is disabled, then none of above resolvers will be called.
* Instead, external $ref pointers will simply be ignored.
*
* @type {boolean}
*/
external: true,
},
/**
* By default, JSON Schema $Ref Parser throws the first error it encounters. Setting `continueOnError` to `true`
* causes it to keep processing as much as possible and then throw a single error that contains all errors
* that were encountered.
*/
continueOnError: false,
/**
* Determines the types of JSON references that are allowed.
*/
dereference: {
/**
* Dereference circular (recursive) JSON references?
* If false, then a {@link ReferenceError} will be thrown if a circular reference is found.
* If "ignore", then circular references will not be dereferenced.
*
* @type {boolean|string}
*/
circular: true,
/**
* A function, called for each path, which can return true to stop this path and all
* subpaths from being dereferenced further. This is useful in schemas where some
* subpaths contain literal $ref keys that should not be dereferenced.
*
* @type {function}
*/
excludedPathMatcher: () => false
},
};
/**
* Merges the properties of the source object into the target object.
*
* @param {object} target - The object that we're populating
* @param {?object} source - The options that are being merged
* @returns {object}
*/
function merge (target, source) {
if (isMergeable(source)) {
let keys = Object.keys(source);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
let sourceSetting = source[key];
let targetSetting = target[key];
if (isMergeable(sourceSetting)) {
// It's a nested object, so merge it recursively
target[key] = merge(targetSetting || {}, sourceSetting);
}
else if (sourceSetting !== undefined) {
// It's a scalar value, function, or array. No merging necessary. Just overwrite the target value.
target[key] = sourceSetting;
}
}
}
return target;
}
/**
* Determines whether the given value can be merged,
* or if it is a scalar value that should just override the target value.
*
* @param {*} val
* @returns {Boolean}
*/
function isMergeable (val) {
return val &&
(typeof val === "object") &&
!Array.isArray(val) &&
!(val instanceof RegExp) &&
!(val instanceof Date);
}

View File

@ -0,0 +1,164 @@
"use strict";
const { ono } = require("@jsdevtools/ono");
const url = require("./util/url");
const plugins = require("./util/plugins");
const { ResolverError, ParserError, UnmatchedParserError, UnmatchedResolverError, isHandledError } = require("./util/errors");
module.exports = parse;
/**
* Reads and parses the specified file path or URL.
*
* @param {string} path - This path MUST already be resolved, since `read` doesn't know the resolution context
* @param {$Refs} $refs
* @param {$RefParserOptions} options
*
* @returns {Promise}
* The promise resolves with the parsed file contents, NOT the raw (Buffer) contents.
*/
async function parse (path, $refs, options) {
// Remove the URL fragment, if any
path = url.stripHash(path);
// Add a new $Ref for this file, even though we don't have the value yet.
// This ensures that we don't simultaneously read & parse the same file multiple times
let $ref = $refs._add(path);
// This "file object" will be passed to all resolvers and parsers.
let file = {
url: path,
extension: url.getExtension(path),
};
// Read the file and then parse the data
try {
const resolver = await readFile(file, options, $refs);
$ref.pathType = resolver.plugin.name;
file.data = resolver.result;
const parser = await parseFile(file, options, $refs);
$ref.value = parser.result;
return parser.result;
}
catch (err) {
if (isHandledError(err)) {
$ref.value = err;
}
throw err;
}
}
/**
* Reads the given file, using the configured resolver plugins
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @param {$RefParserOptions} options
*
* @returns {Promise}
* The promise resolves with the raw file contents and the resolver that was used.
*/
function readFile (file, options, $refs) {
return new Promise(((resolve, reject) => {
// console.log('Reading %s', file.url);
// Find the resolvers that can read this file
let resolvers = plugins.all(options.resolve);
resolvers = plugins.filter(resolvers, "canRead", file);
// Run the resolvers, in order, until one of them succeeds
plugins.sort(resolvers);
plugins.run(resolvers, "read", file, $refs)
.then(resolve, onError);
function onError (err) {
if (!err && options.continueOnError) {
// No resolver could be matched
reject(new UnmatchedResolverError(file.url));
}
else if (!err || !("error" in err)) {
// Throw a generic, friendly error.
reject(ono.syntax(`Unable to resolve $ref pointer "${file.url}"`));
}
// Throw the original error, if it's one of our own (user-friendly) errors.
else if (err.error instanceof ResolverError) {
reject(err.error);
}
else {
reject(new ResolverError(err, file.url));
}
}
}));
}
/**
* Parses the given file's contents, using the configured parser plugins.
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
* @param {$RefParserOptions} options
*
* @returns {Promise}
* The promise resolves with the parsed file contents and the parser that was used.
*/
function parseFile (file, options, $refs) {
return new Promise(((resolve, reject) => {
// console.log('Parsing %s', file.url);
// Find the parsers that can read this file type.
// If none of the parsers are an exact match for this file, then we'll try ALL of them.
// This handles situations where the file IS a supported type, just with an unknown extension.
let allParsers = plugins.all(options.parse);
let filteredParsers = plugins.filter(allParsers, "canParse", file);
let parsers = filteredParsers.length > 0 ? filteredParsers : allParsers;
// Run the parsers, in order, until one of them succeeds
plugins.sort(parsers);
plugins.run(parsers, "parse", file, $refs)
.then(onParsed, onError);
function onParsed (parser) {
if (!parser.plugin.allowEmpty && isEmpty(parser.result)) {
reject(ono.syntax(`Error parsing "${file.url}" as ${parser.plugin.name}. \nParsed value is empty`));
}
else {
resolve(parser);
}
}
function onError (err) {
if (!err && options.continueOnError) {
// No resolver could be matched
reject(new UnmatchedParserError(file.url));
}
else if (!err || !("error" in err)) {
reject(ono.syntax(`Unable to parse ${file.url}`));
}
else if (err.error instanceof ParserError) {
reject(err.error);
}
else {
reject(new ParserError(err.error.message, file.url));
}
}
}));
}
/**
* Determines whether the parsed value is "empty".
*
* @param {*} value
* @returns {boolean}
*/
function isEmpty (value) {
return value === undefined ||
(typeof value === "object" && Object.keys(value).length === 0) ||
(typeof value === "string" && value.trim().length === 0) ||
(Buffer.isBuffer(value) && value.length === 0);
}

View File

@ -0,0 +1,55 @@
"use strict";
let BINARY_REGEXP = /\.(jpeg|jpg|gif|png|bmp|ico)$/i;
module.exports = {
/**
* The order that this parser will run, in relation to other parsers.
*
* @type {number}
*/
order: 400,
/**
* Whether to allow "empty" files (zero bytes).
*
* @type {boolean}
*/
allowEmpty: true,
/**
* Determines whether this parser can parse a given file reference.
* Parsers that return true will be tried, in order, until one successfully parses the file.
* Parsers that return false will be skipped, UNLESS all parsers returned false, in which case
* every parser will be tried.
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
* @returns {boolean}
*/
canParse (file) {
// Use this parser if the file is a Buffer, and has a known binary extension
return Buffer.isBuffer(file.data) && BINARY_REGEXP.test(file.url);
},
/**
* Parses the given data as a Buffer (byte array).
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
* @returns {Buffer}
*/
parse (file) {
if (Buffer.isBuffer(file.data)) {
return file.data;
}
else {
// This will reject if data is anything other than a string or typed array
return Buffer.from(file.data);
}
}
};

View File

@ -0,0 +1,63 @@
"use strict";
const { ParserError } = require("../util/errors");
module.exports = {
/**
* The order that this parser will run, in relation to other parsers.
*
* @type {number}
*/
order: 100,
/**
* Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects.
*
* @type {boolean}
*/
allowEmpty: true,
/**
* Determines whether this parser can parse a given file reference.
* Parsers that match will be tried, in order, until one successfully parses the file.
* Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case
* every parser will be tried.
*
* @type {RegExp|string|string[]|function}
*/
canParse: ".json",
/**
* Parses the given file as JSON
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
* @returns {Promise}
*/
async parse (file) { // eslint-disable-line require-await
let data = file.data;
if (Buffer.isBuffer(data)) {
data = data.toString();
}
if (typeof data === "string") {
if (data.trim().length === 0) {
return; // This mirrors the YAML behavior
}
else {
try {
return JSON.parse(data);
}
catch (e) {
throw new ParserError(e.message, file.url);
}
}
}
else {
// data is already a JavaScript value (object, array, number, null, NaN, etc.)
return data;
}
}
};

View File

@ -0,0 +1,66 @@
"use strict";
const { ParserError } = require("../util/errors");
let TEXT_REGEXP = /\.(txt|htm|html|md|xml|js|min|map|css|scss|less|svg)$/i;
module.exports = {
/**
* The order that this parser will run, in relation to other parsers.
*
* @type {number}
*/
order: 300,
/**
* Whether to allow "empty" files (zero bytes).
*
* @type {boolean}
*/
allowEmpty: true,
/**
* The encoding that the text is expected to be in.
*
* @type {string}
*/
encoding: "utf8",
/**
* Determines whether this parser can parse a given file reference.
* Parsers that return true will be tried, in order, until one successfully parses the file.
* Parsers that return false will be skipped, UNLESS all parsers returned false, in which case
* every parser will be tried.
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
* @returns {boolean}
*/
canParse (file) {
// Use this parser if the file is a string or Buffer, and has a known text-based extension
return (typeof file.data === "string" || Buffer.isBuffer(file.data)) && TEXT_REGEXP.test(file.url);
},
/**
* Parses the given file as text
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
* @returns {string}
*/
parse (file) {
if (typeof file.data === "string") {
return file.data;
}
else if (Buffer.isBuffer(file.data)) {
return file.data.toString(this.encoding);
}
else {
throw new ParserError("data is not text", file.url);
}
}
};

View File

@ -0,0 +1,60 @@
"use strict";
const { ParserError } = require("../util/errors");
const yaml = require("js-yaml");
const { JSON_SCHEMA } = require("js-yaml");
module.exports = {
/**
* The order that this parser will run, in relation to other parsers.
*
* @type {number}
*/
order: 200,
/**
* Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects.
*
* @type {boolean}
*/
allowEmpty: true,
/**
* Determines whether this parser can parse a given file reference.
* Parsers that match will be tried, in order, until one successfully parses the file.
* Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case
* every parser will be tried.
*
* @type {RegExp|string[]|function}
*/
canParse: [".yaml", ".yml", ".json"], // JSON is valid YAML
/**
* Parses the given file as YAML
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
* @returns {Promise}
*/
async parse (file) { // eslint-disable-line require-await
let data = file.data;
if (Buffer.isBuffer(data)) {
data = data.toString();
}
if (typeof data === "string") {
try {
return yaml.load(data, { schema: JSON_SCHEMA });
}
catch (e) {
throw new ParserError(e.message, file.url);
}
}
else {
// data is already a JavaScript value (object, array, number, null, NaN, etc.)
return data;
}
}
};

View File

@ -0,0 +1,295 @@
"use strict";
module.exports = Pointer;
const $Ref = require("./ref");
const url = require("./util/url");
const { JSONParserError, InvalidPointerError, MissingPointerError, isHandledError } = require("./util/errors");
const slashes = /\//g;
const tildes = /~/g;
const escapedSlash = /~1/g;
const escapedTilde = /~0/g;
/**
* This class represents a single JSON pointer and its resolved value.
*
* @param {$Ref} $ref
* @param {string} path
* @param {string} [friendlyPath] - The original user-specified path (used for error messages)
* @constructor
*/
function Pointer ($ref, path, friendlyPath) {
/**
* The {@link $Ref} object that contains this {@link Pointer} object.
* @type {$Ref}
*/
this.$ref = $ref;
/**
* The file path or URL, containing the JSON pointer in the hash.
* This path is relative to the path of the main JSON schema file.
* @type {string}
*/
this.path = path;
/**
* The original path or URL, used for error messages.
* @type {string}
*/
this.originalPath = friendlyPath || path;
/**
* The value of the JSON pointer.
* Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays).
* @type {?*}
*/
this.value = undefined;
/**
* Indicates whether the pointer references itself.
* @type {boolean}
*/
this.circular = false;
/**
* The number of indirect references that were traversed to resolve the value.
* Resolving a single pointer may require resolving multiple $Refs.
* @type {number}
*/
this.indirections = 0;
}
/**
* Resolves the value of a nested property within the given object.
*
* @param {*} obj - The object that will be crawled
* @param {$RefParserOptions} options
* @param {string} pathFromRoot - the path of place that initiated resolving
*
* @returns {Pointer}
* Returns a JSON pointer whose {@link Pointer#value} is the resolved value.
* If resolving this value required resolving other JSON references, then
* the {@link Pointer#$ref} and {@link Pointer#path} will reflect the resolution path
* of the resolved value.
*/
Pointer.prototype.resolve = function (obj, options, pathFromRoot) {
let tokens = Pointer.parse(this.path, this.originalPath);
// Crawl the object, one token at a time
this.value = unwrapOrThrow(obj);
for (let i = 0; i < tokens.length; i++) {
if (resolveIf$Ref(this, options)) {
// The $ref path has changed, so append the remaining tokens to the path
this.path = Pointer.join(this.path, tokens.slice(i));
}
if (typeof this.value === "object" && this.value !== null && "$ref" in this.value) {
return this;
}
let token = tokens[i];
if (this.value[token] === undefined || this.value[token] === null) {
this.value = null;
throw new MissingPointerError(token, decodeURI(this.originalPath));
}
else {
this.value = this.value[token];
}
}
// Resolve the final value
if (!this.value || this.value.$ref && url.resolve(this.path, this.value.$ref) !== pathFromRoot) {
resolveIf$Ref(this, options);
}
return this;
};
/**
* Sets the value of a nested property within the given object.
*
* @param {*} obj - The object that will be crawled
* @param {*} value - the value to assign
* @param {$RefParserOptions} options
*
* @returns {*}
* Returns the modified object, or an entirely new object if the entire object is overwritten.
*/
Pointer.prototype.set = function (obj, value, options) {
let tokens = Pointer.parse(this.path);
let token;
if (tokens.length === 0) {
// There are no tokens, replace the entire object with the new value
this.value = value;
return value;
}
// Crawl the object, one token at a time
this.value = unwrapOrThrow(obj);
for (let i = 0; i < tokens.length - 1; i++) {
resolveIf$Ref(this, options);
token = tokens[i];
if (this.value && this.value[token] !== undefined) {
// The token exists
this.value = this.value[token];
}
else {
// The token doesn't exist, so create it
this.value = setValue(this, token, {});
}
}
// Set the value of the final token
resolveIf$Ref(this, options);
token = tokens[tokens.length - 1];
setValue(this, token, value);
// Return the updated object
return obj;
};
/**
* Parses a JSON pointer (or a path containing a JSON pointer in the hash)
* and returns an array of the pointer's tokens.
* (e.g. "schema.json#/definitions/person/name" => ["definitions", "person", "name"])
*
* The pointer is parsed according to RFC 6901
* {@link https://tools.ietf.org/html/rfc6901#section-3}
*
* @param {string} path
* @param {string} [originalPath]
* @returns {string[]}
*/
Pointer.parse = function (path, originalPath) {
// Get the JSON pointer from the path's hash
let pointer = url.getHash(path).substr(1);
// If there's no pointer, then there are no tokens,
// so return an empty array
if (!pointer) {
return [];
}
// Split into an array
pointer = pointer.split("/");
// Decode each part, according to RFC 6901
for (let i = 0; i < pointer.length; i++) {
pointer[i] = decodeURIComponent(pointer[i].replace(escapedSlash, "/").replace(escapedTilde, "~"));
}
if (pointer[0] !== "") {
throw new InvalidPointerError(pointer, originalPath === undefined ? path : originalPath);
}
return pointer.slice(1);
};
/**
* Creates a JSON pointer path, by joining one or more tokens to a base path.
*
* @param {string} base - The base path (e.g. "schema.json#/definitions/person")
* @param {string|string[]} tokens - The token(s) to append (e.g. ["name", "first"])
* @returns {string}
*/
Pointer.join = function (base, tokens) {
// Ensure that the base path contains a hash
if (base.indexOf("#") === -1) {
base += "#";
}
// Append each token to the base path
tokens = Array.isArray(tokens) ? tokens : [tokens];
for (let i = 0; i < tokens.length; i++) {
let token = tokens[i];
// Encode the token, according to RFC 6901
base += "/" + encodeURIComponent(token.replace(tildes, "~0").replace(slashes, "~1"));
}
return base;
};
/**
* If the given pointer's {@link Pointer#value} is a JSON reference,
* then the reference is resolved and {@link Pointer#value} is replaced with the resolved value.
* In addition, {@link Pointer#path} and {@link Pointer#$ref} are updated to reflect the
* resolution path of the new value.
*
* @param {Pointer} pointer
* @param {$RefParserOptions} options
* @returns {boolean} - Returns `true` if the resolution path changed
*/
function resolveIf$Ref (pointer, options) {
// Is the value a JSON reference? (and allowed?)
if ($Ref.isAllowed$Ref(pointer.value, options)) {
let $refPath = url.resolve(pointer.path, pointer.value.$ref);
if ($refPath === pointer.path) {
// The value is a reference to itself, so there's nothing to do.
pointer.circular = true;
}
else {
let resolved = pointer.$ref.$refs._resolve($refPath, pointer.path, options);
if (resolved === null) {
return false;
}
pointer.indirections += resolved.indirections + 1;
if ($Ref.isExtended$Ref(pointer.value)) {
// This JSON reference "extends" the resolved value, rather than simply pointing to it.
// So the resolved path does NOT change. Just the value does.
pointer.value = $Ref.dereference(pointer.value, resolved.value);
return false;
}
else {
// Resolve the reference
pointer.$ref = resolved.$ref;
pointer.path = resolved.path;
pointer.value = resolved.value;
}
return true;
}
}
}
/**
* Sets the specified token value of the {@link Pointer#value}.
*
* The token is evaluated according to RFC 6901.
* {@link https://tools.ietf.org/html/rfc6901#section-4}
*
* @param {Pointer} pointer - The JSON Pointer whose value will be modified
* @param {string} token - A JSON Pointer token that indicates how to modify `obj`
* @param {*} value - The value to assign
* @returns {*} - Returns the assigned value
*/
function setValue (pointer, token, value) {
if (pointer.value && typeof pointer.value === "object") {
if (token === "-" && Array.isArray(pointer.value)) {
pointer.value.push(value);
}
else {
pointer.value[token] = value;
}
}
else {
throw new JSONParserError(`Error assigning $ref pointer "${pointer.path}". \nCannot set "${token}" of a non-object.`);
}
return value;
}
function unwrapOrThrow (value) {
if (isHandledError(value)) {
throw value;
}
return value;
}

View File

@ -0,0 +1,294 @@
"use strict";
module.exports = $Ref;
const Pointer = require("./pointer");
const { InvalidPointerError, isHandledError, normalizeError } = require("./util/errors");
const { safePointerToPath, stripHash, getHash } = require("./util/url");
/**
* This class represents a single JSON reference and its resolved value.
*
* @class
*/
function $Ref () {
/**
* The file path or URL of the referenced file.
* This path is relative to the path of the main JSON schema file.
*
* This path does NOT contain document fragments (JSON pointers). It always references an ENTIRE file.
* Use methods such as {@link $Ref#get}, {@link $Ref#resolve}, and {@link $Ref#exists} to get
* specific JSON pointers within the file.
*
* @type {string}
*/
this.path = undefined;
/**
* The resolved value of the JSON reference.
* Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays).
*
* @type {?*}
*/
this.value = undefined;
/**
* The {@link $Refs} object that contains this {@link $Ref} object.
*
* @type {$Refs}
*/
this.$refs = undefined;
/**
* Indicates the type of {@link $Ref#path} (e.g. "file", "http", etc.)
*
* @type {?string}
*/
this.pathType = undefined;
/**
* List of all errors. Undefined if no errors.
*
* @type {Array<JSONParserError | ResolverError | ParserError | MissingPointerError>}
*/
this.errors = undefined;
}
/**
* Pushes an error to errors array.
*
* @param {Array<JSONParserError | JSONParserErrorGroup>} err - The error to be pushed
* @returns {void}
*/
$Ref.prototype.addError = function (err) {
if (this.errors === undefined) {
this.errors = [];
}
const existingErrors = this.errors.map(({ footprint }) => footprint);
// the path has been almost certainly set at this point,
// but just in case something went wrong, normalizeError injects path if necessary
// moreover, certain errors might point at the same spot, so filter them out to reduce noise
if (Array.isArray(err.errors)) {
this.errors.push(...err.errors
.map(normalizeError)
.filter(({ footprint }) => !existingErrors.includes(footprint)),
);
}
else if (!existingErrors.includes(err.footprint)) {
this.errors.push(normalizeError(err));
}
};
/**
* Determines whether the given JSON reference exists within this {@link $Ref#value}.
*
* @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash
* @param {$RefParserOptions} options
* @returns {boolean}
*/
$Ref.prototype.exists = function (path, options) {
try {
this.resolve(path, options);
return true;
}
catch (e) {
return false;
}
};
/**
* Resolves the given JSON reference within this {@link $Ref#value} and returns the resolved value.
*
* @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash
* @param {$RefParserOptions} options
* @returns {*} - Returns the resolved value
*/
$Ref.prototype.get = function (path, options) {
return this.resolve(path, options).value;
};
/**
* Resolves the given JSON reference within this {@link $Ref#value}.
*
* @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash
* @param {$RefParserOptions} options
* @param {string} friendlyPath - The original user-specified path (used for error messages)
* @param {string} pathFromRoot - The path of `obj` from the schema root
* @returns {Pointer | null}
*/
$Ref.prototype.resolve = function (path, options, friendlyPath, pathFromRoot) {
let pointer = new Pointer(this, path, friendlyPath);
try {
return pointer.resolve(this.value, options, pathFromRoot);
}
catch (err) {
if (!options || !options.continueOnError || !isHandledError(err)) {
throw err;
}
if (err.path === null) {
err.path = safePointerToPath(getHash(pathFromRoot));
}
if (err instanceof InvalidPointerError) {
// this is a special case - InvalidPointerError is thrown when dereferencing external file,
// but the issue is caused by the source file that referenced the file that undergoes dereferencing
err.source = decodeURI(stripHash(pathFromRoot));
}
this.addError(err);
return null;
}
};
/**
* Sets the value of a nested property within this {@link $Ref#value}.
* If the property, or any of its parents don't exist, they will be created.
*
* @param {string} path - The full path of the property to set, optionally with a JSON pointer in the hash
* @param {*} value - The value to assign
*/
$Ref.prototype.set = function (path, value) {
let pointer = new Pointer(this, path);
this.value = pointer.set(this.value, value);
};
/**
* Determines whether the given value is a JSON reference.
*
* @param {*} value - The value to inspect
* @returns {boolean}
*/
$Ref.is$Ref = function (value) {
return value && typeof value === "object" && typeof value.$ref === "string" && value.$ref.length > 0;
};
/**
* Determines whether the given value is an external JSON reference.
*
* @param {*} value - The value to inspect
* @returns {boolean}
*/
$Ref.isExternal$Ref = function (value) {
return $Ref.is$Ref(value) && value.$ref[0] !== "#";
};
/**
* Determines whether the given value is a JSON reference, and whether it is allowed by the options.
* For example, if it references an external file, then options.resolve.external must be true.
*
* @param {*} value - The value to inspect
* @param {$RefParserOptions} options
* @returns {boolean}
*/
$Ref.isAllowed$Ref = function (value, options) {
if ($Ref.is$Ref(value)) {
if (value.$ref.substr(0, 2) === "#/" || value.$ref === "#") {
// It's a JSON Pointer reference, which is always allowed
return true;
}
else if (value.$ref[0] !== "#" && (!options || options.resolve.external)) {
// It's an external reference, which is allowed by the options
return true;
}
}
};
/**
* Determines whether the given value is a JSON reference that "extends" its resolved value.
* That is, it has extra properties (in addition to "$ref"), so rather than simply pointing to
* an existing value, this $ref actually creates a NEW value that is a shallow copy of the resolved
* value, plus the extra properties.
*
* @example:
* {
* person: {
* properties: {
* firstName: { type: string }
* lastName: { type: string }
* }
* }
* employee: {
* properties: {
* $ref: #/person/properties
* salary: { type: number }
* }
* }
* }
*
* In this example, "employee" is an extended $ref, since it extends "person" with an additional
* property (salary). The result is a NEW value that looks like this:
*
* {
* properties: {
* firstName: { type: string }
* lastName: { type: string }
* salary: { type: number }
* }
* }
*
* @param {*} value - The value to inspect
* @returns {boolean}
*/
$Ref.isExtended$Ref = function (value) {
return $Ref.is$Ref(value) && Object.keys(value).length > 1;
};
/**
* Returns the resolved value of a JSON Reference.
* If necessary, the resolved value is merged with the JSON Reference to create a new object
*
* @example:
* {
* person: {
* properties: {
* firstName: { type: string }
* lastName: { type: string }
* }
* }
* employee: {
* properties: {
* $ref: #/person/properties
* salary: { type: number }
* }
* }
* }
*
* When "person" and "employee" are merged, you end up with the following object:
*
* {
* properties: {
* firstName: { type: string }
* lastName: { type: string }
* salary: { type: number }
* }
* }
*
* @param {object} $ref - The JSON reference object (the one with the "$ref" property)
* @param {*} resolvedValue - The resolved value, which can be any type
* @returns {*} - Returns the dereferenced value
*/
$Ref.dereference = function ($ref, resolvedValue) {
if (resolvedValue && typeof resolvedValue === "object" && $Ref.isExtended$Ref($ref)) {
let merged = {};
for (let key of Object.keys($ref)) {
if (key !== "$ref") {
merged[key] = $ref[key];
}
}
for (let key of Object.keys(resolvedValue)) {
if (!(key in merged)) {
merged[key] = resolvedValue[key];
}
}
return merged;
}
else {
// Completely replace the original reference with the resolved value
return resolvedValue;
}
};

View File

@ -0,0 +1,197 @@
"use strict";
const { ono } = require("@jsdevtools/ono");
const $Ref = require("./ref");
const url = require("./util/url");
module.exports = $Refs;
/**
* This class is a map of JSON references and their resolved values.
*/
function $Refs () {
/**
* Indicates whether the schema contains any circular references.
*
* @type {boolean}
*/
this.circular = false;
/**
* A map of paths/urls to {@link $Ref} objects
*
* @type {object}
* @protected
*/
this._$refs = {};
/**
* The {@link $Ref} object that is the root of the JSON schema.
*
* @type {$Ref}
* @protected
*/
this._root$Ref = null;
}
/**
* Returns the paths of all the files/URLs that are referenced by the JSON schema,
* including the schema itself.
*
* @param {...string|string[]} [types] - Only return paths of the given types ("file", "http", etc.)
* @returns {string[]}
*/
$Refs.prototype.paths = function (types) { // eslint-disable-line no-unused-vars
let paths = getPaths(this._$refs, arguments);
return paths.map((path) => {
return path.decoded;
});
};
/**
* Returns the map of JSON references and their resolved values.
*
* @param {...string|string[]} [types] - Only return references of the given types ("file", "http", etc.)
* @returns {object}
*/
$Refs.prototype.values = function (types) { // eslint-disable-line no-unused-vars
let $refs = this._$refs;
let paths = getPaths($refs, arguments);
return paths.reduce((obj, path) => {
obj[path.decoded] = $refs[path.encoded].value;
return obj;
}, {});
};
/**
* Returns a POJO (plain old JavaScript object) for serialization as JSON.
*
* @returns {object}
*/
$Refs.prototype.toJSON = $Refs.prototype.values;
/**
* Determines whether the given JSON reference exists.
*
* @param {string} path - The path being resolved, optionally with a JSON pointer in the hash
* @param {$RefParserOptions} [options]
* @returns {boolean}
*/
$Refs.prototype.exists = function (path, options) {
try {
this._resolve(path, "", options);
return true;
}
catch (e) {
return false;
}
};
/**
* Resolves the given JSON reference and returns the resolved value.
*
* @param {string} path - The path being resolved, with a JSON pointer in the hash
* @param {$RefParserOptions} [options]
* @returns {*} - Returns the resolved value
*/
$Refs.prototype.get = function (path, options) {
return this._resolve(path, "", options).value;
};
/**
* Sets the value of a nested property within this {@link $Ref#value}.
* If the property, or any of its parents don't exist, they will be created.
*
* @param {string} path - The path of the property to set, optionally with a JSON pointer in the hash
* @param {*} value - The value to assign
*/
$Refs.prototype.set = function (path, value) {
let absPath = url.resolve(this._root$Ref.path, path);
let withoutHash = url.stripHash(absPath);
let $ref = this._$refs[withoutHash];
if (!$ref) {
throw ono(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`);
}
$ref.set(absPath, value);
};
/**
* Creates a new {@link $Ref} object and adds it to this {@link $Refs} object.
*
* @param {string} path - The file path or URL of the referenced file
*/
$Refs.prototype._add = function (path) {
let withoutHash = url.stripHash(path);
let $ref = new $Ref();
$ref.path = withoutHash;
$ref.$refs = this;
this._$refs[withoutHash] = $ref;
this._root$Ref = this._root$Ref || $ref;
return $ref;
};
/**
* Resolves the given JSON reference.
*
* @param {string} path - The path being resolved, optionally with a JSON pointer in the hash
* @param {string} pathFromRoot - The path of `obj` from the schema root
* @param {$RefParserOptions} [options]
* @returns {Pointer}
* @protected
*/
$Refs.prototype._resolve = function (path, pathFromRoot, options) {
let absPath = url.resolve(this._root$Ref.path, path);
let withoutHash = url.stripHash(absPath);
let $ref = this._$refs[withoutHash];
if (!$ref) {
throw ono(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`);
}
return $ref.resolve(absPath, options, path, pathFromRoot);
};
/**
* Returns the specified {@link $Ref} object, or undefined.
*
* @param {string} path - The path being resolved, optionally with a JSON pointer in the hash
* @returns {$Ref|undefined}
* @protected
*/
$Refs.prototype._get$Ref = function (path) {
path = url.resolve(this._root$Ref.path, path);
let withoutHash = url.stripHash(path);
return this._$refs[withoutHash];
};
/**
* Returns the encoded and decoded paths keys of the given object.
*
* @param {object} $refs - The object whose keys are URL-encoded paths
* @param {...string|string[]} [types] - Only return paths of the given types ("file", "http", etc.)
* @returns {object[]}
*/
function getPaths ($refs, types) {
let paths = Object.keys($refs);
// Filter the paths by type
types = Array.isArray(types[0]) ? types[0] : Array.prototype.slice.call(types);
if (types.length > 0 && types[0]) {
paths = paths.filter((key) => {
return types.indexOf($refs[key].pathType) !== -1;
});
}
// Decode local filesystem paths
return paths.map((path) => {
return {
encoded: path,
decoded: $refs[path].pathType === "file" ? url.toFileSystemPath(path, true) : path
};
});
}

View File

@ -0,0 +1,129 @@
"use strict";
const $Ref = require("./ref");
const Pointer = require("./pointer");
const parse = require("./parse");
const url = require("./util/url");
const { isHandledError } = require("./util/errors");
module.exports = resolveExternal;
/**
* Crawls the JSON schema, finds all external JSON references, and resolves their values.
* This method does not mutate the JSON schema. The resolved values are added to {@link $RefParser#$refs}.
*
* NOTE: We only care about EXTERNAL references here. INTERNAL references are only relevant when dereferencing.
*
* @param {$RefParser} parser
* @param {$RefParserOptions} options
*
* @returns {Promise}
* The promise resolves once all JSON references in the schema have been resolved,
* including nested references that are contained in externally-referenced files.
*/
function resolveExternal (parser, options) {
if (!options.resolve.external) {
// Nothing to resolve, so exit early
return Promise.resolve();
}
try {
// console.log('Resolving $ref pointers in %s', parser.$refs._root$Ref.path);
let promises = crawl(parser.schema, parser.$refs._root$Ref.path + "#", parser.$refs, options);
return Promise.all(promises);
}
catch (e) {
return Promise.reject(e);
}
}
/**
* Recursively crawls the given value, and resolves any external JSON references.
*
* @param {*} obj - The value to crawl. If it's not an object or array, it will be ignored.
* @param {string} path - The full path of `obj`, possibly with a JSON Pointer in the hash
* @param {$Refs} $refs
* @param {$RefParserOptions} options
* @param {Set} seen - Internal.
*
* @returns {Promise[]}
* Returns an array of promises. There will be one promise for each JSON reference in `obj`.
* If `obj` does not contain any JSON references, then the array will be empty.
* If any of the JSON references point to files that contain additional JSON references,
* then the corresponding promise will internally reference an array of promises.
*/
function crawl (obj, path, $refs, options, seen) {
seen = seen || new Set();
let promises = [];
if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj) && !seen.has(obj)) {
seen.add(obj); // Track previously seen objects to avoid infinite recursion
if ($Ref.isExternal$Ref(obj)) {
promises.push(resolve$Ref(obj, path, $refs, options));
}
else {
for (let key of Object.keys(obj)) {
let keyPath = Pointer.join(path, key);
let value = obj[key];
if ($Ref.isExternal$Ref(value)) {
promises.push(resolve$Ref(value, keyPath, $refs, options));
}
else {
promises = promises.concat(crawl(value, keyPath, $refs, options, seen));
}
}
}
}
return promises;
}
/**
* Resolves the given JSON Reference, and then crawls the resulting value.
*
* @param {{$ref: string}} $ref - The JSON Reference to resolve
* @param {string} path - The full path of `$ref`, possibly with a JSON Pointer in the hash
* @param {$Refs} $refs
* @param {$RefParserOptions} options
*
* @returns {Promise}
* The promise resolves once all JSON references in the object have been resolved,
* including nested references that are contained in externally-referenced files.
*/
async function resolve$Ref ($ref, path, $refs, options) {
// console.log('Resolving $ref pointer "%s" at %s', $ref.$ref, path);
let resolvedPath = url.resolve(path, $ref.$ref);
let withoutHash = url.stripHash(resolvedPath);
// Do we already have this $ref?
$ref = $refs._$refs[withoutHash];
if ($ref) {
// We've already parsed this $ref, so use the existing value
return Promise.resolve($ref.value);
}
// Parse the $referenced file/url
try {
const result = await parse(resolvedPath, $refs, options);
// Crawl the parsed value
// console.log('Resolving $ref pointers in %s', withoutHash);
let promises = crawl(result, withoutHash + "#", $refs, options);
return Promise.all(promises);
}
catch (err) {
if (!options.continueOnError || !isHandledError(err)) {
throw err;
}
if ($refs._$refs[withoutHash]) {
err.source = decodeURI(url.stripHash(path));
err.path = url.safePointerToPath(url.getHash(path));
}
return [];
}
}

View File

@ -0,0 +1,64 @@
"use strict";
const fs = require("fs");
const { ono } = require("@jsdevtools/ono");
const url = require("../util/url");
const { ResolverError } = require("../util/errors");
module.exports = {
/**
* The order that this resolver will run, in relation to other resolvers.
*
* @type {number}
*/
order: 100,
/**
* Determines whether this resolver can read a given file reference.
* Resolvers that return true will be tried, in order, until one successfully resolves the file.
* Resolvers that return false will not be given a chance to resolve the file.
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @returns {boolean}
*/
canRead (file) {
return url.isFileSystemPath(file.url);
},
/**
* Reads the given file and returns its raw contents as a Buffer.
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @returns {Promise<Buffer>}
*/
read (file) {
return new Promise(((resolve, reject) => {
let path;
try {
path = url.toFileSystemPath(file.url);
}
catch (err) {
reject(new ResolverError(ono.uri(err, `Malformed URI: ${file.url}`), file.url));
}
// console.log('Opening file: %s', path);
try {
fs.readFile(path, (err, data) => {
if (err) {
reject(new ResolverError(ono(err, `Error opening file "${path}"`), path));
}
else {
resolve(data);
}
});
}
catch (err) {
reject(new ResolverError(ono(err, `Error opening file "${path}"`), path));
}
}));
}
};

View File

@ -0,0 +1,180 @@
"use strict";
const http = require("http");
const https = require("https");
const { ono } = require("@jsdevtools/ono");
const url = require("../util/url");
const { ResolverError } = require("../util/errors");
module.exports = {
/**
* The order that this resolver will run, in relation to other resolvers.
*
* @type {number}
*/
order: 200,
/**
* HTTP headers to send when downloading files.
*
* @example:
* {
* "User-Agent": "JSON Schema $Ref Parser",
* Accept: "application/json"
* }
*
* @type {object}
*/
headers: null,
/**
* HTTP request timeout (in milliseconds).
*
* @type {number}
*/
timeout: 5000, // 5 seconds
/**
* The maximum number of HTTP redirects to follow.
* To disable automatic following of redirects, set this to zero.
*
* @type {number}
*/
redirects: 5,
/**
* The `withCredentials` option of XMLHttpRequest.
* Set this to `true` if you're downloading files from a CORS-enabled server that requires authentication
*
* @type {boolean}
*/
withCredentials: false,
/**
* Determines whether this resolver can read a given file reference.
* Resolvers that return true will be tried in order, until one successfully resolves the file.
* Resolvers that return false will not be given a chance to resolve the file.
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @returns {boolean}
*/
canRead (file) {
return url.isHttp(file.url);
},
/**
* Reads the given URL and returns its raw contents as a Buffer.
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @returns {Promise<Buffer>}
*/
read (file) {
let u = url.parse(file.url);
if (process.browser && !u.protocol) {
// Use the protocol of the current page
u.protocol = url.parse(location.href).protocol;
}
return download(u, this);
}
};
/**
* Downloads the given file.
*
* @param {Url|string} u - The url to download (can be a parsed {@link Url} object)
* @param {object} httpOptions - The `options.resolve.http` object
* @param {number} [redirects] - The redirect URLs that have already been followed
*
* @returns {Promise<Buffer>}
* The promise resolves with the raw downloaded data, or rejects if there is an HTTP error.
*/
function download (u, httpOptions, redirects) {
return new Promise(((resolve, reject) => {
u = url.parse(u);
redirects = redirects || [];
redirects.push(u.href);
get(u, httpOptions)
.then((res) => {
if (res.statusCode >= 400) {
throw ono({ status: res.statusCode }, `HTTP ERROR ${res.statusCode}`);
}
else if (res.statusCode >= 300) {
if (redirects.length > httpOptions.redirects) {
reject(new ResolverError(ono({ status: res.statusCode },
`Error downloading ${redirects[0]}. \nToo many redirects: \n ${redirects.join(" \n ")}`)));
}
else if (!res.headers.location) {
throw ono({ status: res.statusCode }, `HTTP ${res.statusCode} redirect with no location header`);
}
else {
// console.log('HTTP %d redirect %s -> %s', res.statusCode, u.href, res.headers.location);
let redirectTo = url.resolve(u, res.headers.location);
download(redirectTo, httpOptions, redirects).then(resolve, reject);
}
}
else {
resolve(res.body || Buffer.alloc(0));
}
})
.catch((err) => {
reject(new ResolverError(ono(err, `Error downloading ${u.href}`), u.href));
});
}));
}
/**
* Sends an HTTP GET request.
*
* @param {Url} u - A parsed {@link Url} object
* @param {object} httpOptions - The `options.resolve.http` object
*
* @returns {Promise<Response>}
* The promise resolves with the HTTP Response object.
*/
function get (u, httpOptions) {
return new Promise(((resolve, reject) => {
// console.log('GET', u.href);
let protocol = u.protocol === "https:" ? https : http;
let req = protocol.get({
hostname: u.hostname,
port: u.port,
path: u.path,
auth: u.auth,
protocol: u.protocol,
headers: httpOptions.headers || {},
withCredentials: httpOptions.withCredentials
});
if (typeof req.setTimeout === "function") {
req.setTimeout(httpOptions.timeout);
}
req.on("timeout", () => {
req.abort();
});
req.on("error", reject);
req.once("response", (res) => {
res.body = Buffer.alloc(0);
res.on("data", (data) => {
res.body = Buffer.concat([res.body, Buffer.from(data)]);
});
res.on("error", reject);
res.on("end", () => {
resolve(res);
});
});
}));
}

Some files were not shown because too many files have changed in this diff Show More