Initial commit

This commit is contained in:
roberts 2025-05-09 15:51:28 -05:00
parent 94a6abdb17
commit e883181b5a
13694 changed files with 12597316 additions and 0 deletions

1
.dockerignore Normal file
View file

@ -0,0 +1 @@
node_modules

15
Dockerfile Normal file
View file

@ -0,0 +1,15 @@
FROM node:20
WORKDIR /app
# Copy dependency info and install
COPY package*.json ./
RUN npm install
# Copy the rest of the app (including bot/ directory)
COPY . .
# Set working dir to bot folder
WORKDIR /app/bot
CMD ["node", "bot.js"]

View file

@ -0,0 +1,32 @@
// bot-tasks/craft-item.js
module.exports = async function craftItem(bot, db, sayWithPersona) {
if (!bot.allowDestruction) {
sayWithPersona("i'm not supposed to break things unless you tell me to.");
return;
}
try {
const itemName = 'planks'; // Placeholder. Later, parse this from command/context.
const count = 4;
const item = bot.registry.itemsByName[itemName];
if (!item) {
sayWithPersona(`you tried to craft ${itemName}, but it doesn't even exist.`);
return;
}
const recipe = bot.recipesFor(item.id, null, 1)[0];
if (!recipe) {
sayWithPersona(`you don't know how to make ${itemName}. learn it first.`);
return;
}
sayWithPersona(`you're crafting ${count} ${itemName}. hope you're happy.`);
await bot.craft(recipe, count, null);
} catch (err) {
console.error("craft-item.js failed:", err);
sayWithPersona("you tried to craft something and screwed it up.");
}
};

57
bot/bot-tasks/eat-food.js Normal file
View file

@ -0,0 +1,57 @@
const { GoalNear } = require('mineflayer-pathfinder').goals;
const memory = require('../lib/memory');
module.exports = async function eatFood(bot, db, sayWithPersona) {
try {
const foodItem = bot.inventory.items().find(i =>
i.name.includes('bread') || i.name.includes('apple') || i.name.includes('carrot')
);
if (foodItem) {
await bot.equip(foodItem, 'hand');
await bot.consume();
sayWithPersona("you were hungry, so you ate something. yum.");
return;
}
sayWithPersona("you're starving and have no food. checking a chest...");
memory.getMemory(db, 'food-chest', async (err, pos) => {
if (err || !pos) {
sayWithPersona("you have no idea where food is. you're doomed.");
return;
}
bot.pathfinder.setGoal(new GoalNear(pos.x, pos.y, pos.z, 1));
const checkChest = setTimeout(async () => {
try {
const chestBlock = bot.blockAt(bot.entity.position.offset(1, 0, 0));
const chest = await bot.openChest(chestBlock);
const food = chest.containerItems().find(item =>
item.name.includes('bread') || item.name.includes('apple')
);
if (food) {
await chest.withdraw(food.type, null, 1);
sayWithPersona("you snagged food from the chest. eating now...");
await bot.equip(food, 'hand');
await bot.consume();
} else {
sayWithPersona("you checked the food chest, but it's empty. awesome.");
}
chest.close();
clearTimeout(checkChest);
} catch (e) {
sayWithPersona("you fumbled the chest like a fool.");
console.error("eat-food chest error:", e);
}
}, 4000);
});
} catch (err) {
console.error("eat-food.js failed:", err);
sayWithPersona("you tried to eat but failed... somehow.");
}
};

View file

@ -0,0 +1,44 @@
// bot-tasks/find-materials.js
const { GoalBlock } = require('mineflayer-pathfinder').goals;
console.log('[TASK] find-materials.js loaded');
module.exports = async function findMaterials(bot, db, sayWithPersona) {
console.log('[TASK EXECUTION] find-materials running');
sayWithPersona("you asked me to find materials. I'm trying...");
if (!bot.allowDestruction) {
sayWithPersona("i'm not supposed to break things unless you tell me to.");
return;
}
try {
// For now, hardcoded material search — will eventually be inferred from task/command
const keywords = ['log', 'coal', 'iron_ore', 'tree', 'water', 'wood', 'potato', 'carrot']; // Expandable list
const targetBlock = bot.findBlock({
matching: block => keywords.some(k => block.name.includes(k)),
maxDistance: 32
});
if (!targetBlock) {
sayWithPersona("you looked around and couldn't find any good materials nearby.");
return;
}
sayWithPersona(`you spotted some ${targetBlock.name}. heading there now.`);
bot.pathfinder.setGoal(new GoalBlock(targetBlock.position.x, targetBlock.position.y, targetBlock.position.z));
// Optional: add memory logging
db.run(
`INSERT OR IGNORE INTO memory (label, data) VALUES (?, ?)`,
[`found-${targetBlock.name}`, JSON.stringify(targetBlock.position)],
(err) => {
if (err) console.error("DB insert failed in find-materials:", err);
}
);
} catch (err) {
console.error("find-materials.js failed:", err);
sayWithPersona("you tried to find materials but got lost in thought.");
}
};

View file

@ -0,0 +1,40 @@
const { GoalFollow } = require('mineflayer-pathfinder').goals;
console.log('[TASK] follow-me.js loaded');
module.exports = async function followMe(bot, db, sayWithPersona) {
try {
const lastChat = bot.lastChatMessage?.toLowerCase() ?? '';
// Check if the user wants to stop following
if (lastChat.includes('stop') || lastChat.includes('leave me alone') || lastChat.includes('unfollow')) {
bot.pathfinder.setGoal(null);
sayWithPersona("fine. i'll stop following you. whatever.");
return;
}
const playerUsername = bot.nearestEntity(entity =>
entity.type === 'player' && entity.username !== bot.username
)?.username;
if (!playerUsername) {
sayWithPersona("you want me to follow you, but you're not even here. genius.");
return;
}
const playerEntity = bot.players[playerUsername]?.entity;
if (!playerEntity) {
sayWithPersona("I can't see you. Are you invisible or just lagging?");
return;
}
sayWithPersona(`ugh. fine. following ${playerUsername} around like a lost puppy.`);
const goal = new GoalFollow(playerEntity, 1);
bot.pathfinder.setGoal(goal, true);
} catch (err) {
console.error("follow-me.js failed:", err);
sayWithPersona("you told me to follow, but I forgot how legs work.");
}
};

View file

@ -0,0 +1,42 @@
const { GoalNear } = require('mineflayer-pathfinder').goals;
const memory = require('../lib/memory');
module.exports = async function goToBed(bot, db, sayWithPersona) {
try {
const hour = bot.time.timeOfDay;
if (hour < 13000 || hour > 23999) {
sayWithPersona("someone asked you to sleep, but it's not night.");
return;
}
memory.getMemory(db, 'bed', (err, pos) => {
if (err || !pos) {
sayWithPersona("you tried to sleep but don't remember where your bed is.");
return;
}
sayWithPersona("it's nighttime. you're heading to your bed.");
bot.pathfinder.setGoal(new GoalNear(pos.x, pos.y, pos.z, 1));
const sleepCheck = setInterval(() => {
const bed = bot.findBlock({
matching: block => block.name.includes('bed'),
maxDistance: 4
});
if (bed) {
bot.sleep(bed).then(() => {
sayWithPersona("ugh, finally sleeping.");
clearInterval(sleepCheck);
}).catch(() => {
sayWithPersona("you found your bed but couldn't sleep. tragic.");
clearInterval(sleepCheck);
});
}
}, 2000);
});
} catch (err) {
console.error("go-to-bed.js failed:", err);
sayWithPersona("something broke while trying to sleep.");
}
};

View file

@ -0,0 +1,40 @@
const memory = require('../lib/memory');
module.exports = async function rememberSigns(bot, db, sayWithPersona) {
try {
const signs = bot.findBlocks({
matching: block => block.name.includes('sign'),
maxDistance: 16,
count: 10
});
for (const pos of signs) {
const block = bot.blockAt(pos);
// In some Mineflayer versions, use .getSignText(), otherwise use .signText or .getBlockEntityData()
const signText = block.getSignText?.() || block.signText || null;
if (signText && signText.trim()) {
const label = signText.trim();
const data = {
x: pos.x,
y: pos.y,
z: pos.z
};
memory.saveMemory(db, label, data, (err) => {
if (!err) {
sayWithPersona(`you memorized a place labeled '${label}'.`);
} else {
console.error("Failed to remember sign label:", err);
sayWithPersona("you saw a sign but forgot it instantly. classic.");
}
});
}
}
} catch (err) {
console.error("remember-signs.js failed:", err);
sayWithPersona("you tried to read signs and got confused.");
}
};

317
bot/bot.js Normal file
View file

@ -0,0 +1,317 @@
const logSurroundings = require('./lib/log-surroundings');
const memory = require('./lib/memory');
const { chatWithPersona } = require('./lib/ai-helper');
const mineflayer = require('mineflayer');
const { pathfinder, Movements, goals: { GoalNear } } = require('mineflayer-pathfinder');
const fs = require('fs');
const path = require('path');
const sqlite3 = require('sqlite3').verbose();
const axios = require('axios');
// === AI Integration (Ollama) ===
const OLLAMA_URL = 'http://192.168.1.3:11434/api/generate';
const MODEL_NAME = 'gemma3';
const BOT_NAME = 'Cletus';
const TASK_DIR = path.join(__dirname, 'bot-tasks');
const DB_PATH = path.join(__dirname, 'db', 'memory.db');
// === Bot Parameters ===
const MC_HOST = 'www.thebytes.net';
const MC_PORT = 25565;
const MC_AUTH = 'offline';
const MC_VER = '1.20.4';
let currentTask = null;
// === Prompts ===
const REFINE_PROMPT = `
Only provide code, do not explain the code or provide a response that isnt part of the code.
As I refine my AI mineflayer bot, I need to revise the logic for the bots action of `;
// === Prompt Builder for Responses ===
const PB_PERSONA = `a cranky teenager with a sense of dark humor and sarcasm. you have short responses and don't repeat yourself.`;
const PB_RESPONSE_LENGTH = 20;
const STANDARD_PROMPT = `You are a minecraft bot named ${BOT_NAME}. ` +
`You don't know that you're a bot though. Instead, you think you are ${PB_PERSONA}. ` +
`Keep your responses around ${PB_RESPONSE_LENGTH}. Respond to this: `;
// === DB Setup ===
const db = new sqlite3.Database(DB_PATH, (err) => {
if (err) {
console.error('DB Error:', err);
return;
}
console.log('Connected to DB');
db.run(`
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
action TEXT,
parameters TEXT,
context TEXT,
outcome TEXT,
score INTEGER DEFAULT 0
)
`, err => {
if (err) console.error('Error creating tasks table:', err);
});
db.run(`
CREATE TABLE IF NOT EXISTS memory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
label TEXT UNIQUE,
data TEXT
)
`, err => {
if (err) console.error('Error creating tasks table:', err);
});
});
// ==== Bot Task Management and Review ==============================================================================
// === Dynamic Task Loader ===
function getAvailableTasks() {
const files = fs.readdirSync(TASK_DIR).filter(f => f.endsWith('.js'));
const tasks = {};
for (const file of files) {
const taskName = file.replace('.js', '');
tasks[taskName] = require(path.join(TASK_DIR, file));
}
return tasks;
}
// === AI Rewrite Trigger ===
async function requestTaskRewrite(action, scriptText) {
const prompt = `${REFINE_PROMPT}${action}.
${scriptText}
`.trim();
try {
const response = await axios.post(OLLAMA_URL, {
model: MODEL_NAME,
prompt,
stream: false
});
const code = response.data.response;
const taskPath = path.join(TASK_DIR, `${action}.js`);
fs.writeFileSync(taskPath, code, 'utf8');
console.log(`Rewrote task script for ${action}`);
} catch (err) {
console.error(`AI rewrite failed for ${action}:`, err.message);
}
}
// ==== Helper Functions ==========================================================================================
const personaOptions = {
botName: BOT_NAME,
persona: PB_PERSONA,
length: PB_RESPONSE_LENGTH,
ollamaUrl: OLLAMA_URL,
model: MODEL_NAME
};
let lastSpokenTime = 0;
function sayWithPersona(message) {
const now = Date.now();
if (now - lastSpokenTime < 4000) return; // 4s cooldown
lastSpokenTime = now;
chatWithPersona(message, personaOptions).then(response => bot.chat(response));
}
function startWandering() {
const wanderInterval = 10000 + Math.random() * 5000; // 1015 seconds
setTimeout(() => {
if (!bot.pathfinder.isMoving()) {
const dx = Math.floor(Math.random() * 10 - 5);
const dy = Math.floor(Math.random() * 4 - 2); // small vertical variance
const dz = Math.floor(Math.random() * 10 - 5);
const dest = bot.entity.position.offset(dx, dy, dz);
if (Math.floor(Math.random() * 10) + 1 === 5) {
sayWithPersona("you are wandering");
}
bot.pathfinder.setGoal(new GoalNear(dest.x, dest.y, dest.z, 1));
}
if (!bot.allowDestruction) {
bot.stopDigging(); // if somehow started
}
// Recurse to keep wandering
startWandering();
}, wanderInterval);
}
// ==== Bot Creation and Automation ===============================================================================
// === Bot Creation ===
const bot = mineflayer.createBot({
host: MC_HOST,
port: MC_PORT,
username: BOT_NAME,
auth: MC_AUTH,
version: MC_VER,
});
bot.loadPlugin(pathfinder);
bot.allowDestruction = false;
// === Bot Spawned ===
bot.on('spawn', () => {
console.log(`${BOT_NAME} spawned.`);
if (isRecoveringItems && lastDeathLocation) {
sayWithPersona("you just respawned from dying, and you are going to try and get your stuff back. ");
// Set goal to walk back to where Cletus died
const goal = new GoalNear(lastDeathLocation.x, lastDeathLocation.y, lastDeathLocation.z, 2);
bot.pathfinder.setGoal(goal);
const recoverTimeout = setTimeout(() => {
if (bot.entity.position.distanceTo(lastDeathLocation) <= 3) {
sayWithPersona("after dying, you actually found your stuff. ");
isRecoveringItems = false;
recoveryFails = 0;
} else {
sayWithPersona("after respawning and looking for your dropped items, you can't find the stuff. ");
recoveryFails++;
if (recoveryFails >= 2) {
sayWithPersona("after respawning multiple times in attempt to locate your dropped items from death, you give up. ");
isRecoveringItems = false;
lastDeathLocation = null;
bot.pathfinder.setGoal(null); // stop movement on failure
}
}
clearTimeout(recoverTimeout);
}, 15000); // Try for 15 seconds
}
const defaultMove = new Movements(bot);
bot.pathfinder.setMovements(defaultMove);
// Passive idle wandering
startWandering();
});
// === Bot Chat Listener ===
bot.on('chat', async (username, message) => {
if (username !== BOT_NAME) {
bot.lastChatMessage = message;
const messageLower = message.toLowerCase();
const tasks = getAvailableTasks();
if (messageLower.includes('stop that') || messageLower.includes("don't do that")) {
if (currentTask) {
sayWithPersona("you have been asked to stop doing " + `${currentTask}.`);
// Log negative feedback
db.get(`SELECT score FROM tasks WHERE action = ? ORDER BY timestamp DESC LIMIT 1`, [currentTask], (err, row) => {
let score = row?.score ?? 0;
score = Math.min(5, score + 1);
db.run(`INSERT INTO tasks (action, outcome, score) VALUES (?, 'interrupted', ?)`, [currentTask, score]);
if (score >= 5) {
const fs = require('fs');
const path = require('path');
const script = fs.readFileSync(path.join(TASK_DIR, `${currentTask}.js`), 'utf8');
requestTaskRewrite(currentTask, script);
}
});
// Cancel current goal (pathfinder)
bot.pathfinder.setGoal(null);
currentTask = null;
return;
} else {
sayWithPersona("you've been asked to stop doing whatever you are doing.");
return;
}
}
console.log(`[CHAT] ${username}: ${messageLower}`);
console.log(`[TASK FILES LOADED]: ${Object.keys(tasks).join(', ')}`);
const matchedTask = Object.keys(tasks).find(taskName =>
messageLower.includes(taskName.replace(/-/g, ' '))
);
if (matchedTask) {
console.log(`[TASK MATCHED]: ${matchedTask}`);
sayWithPersona("you were asked to " + `${matchedTask.replace(/-/g, ' ')}.`);
try {
await tasks[matchedTask](bot, db, sayWithPersona);
db.run(`INSERT INTO tasks (action, outcome, score) VALUES (?, 'success', 0)`, [matchedTask]);
} catch (err) {
console.error(`Task ${matchedTask} failed:`, err.message);
sayWithPersona("you failed at the task of " + `${matchedTask}`);
}
} else {
console.log(`[NO MATCH]: Responding only.`);
sayWithPersona(message);
}
}
});
// === Lifecycle & Error Events ===
bot.on('error', (err) => console.error('Bot error:', err));
bot.on('kicked', (reason) => console.log('Bot was kicked:', reason));
bot.on('end', () => console.log('Bot has disconnected.'));
// === Reaction to Death ===
let lastDeathLocation = null;
let isRecoveringItems = false;
let recoveryFails = 0;
bot.on('death', () => {
console.log('Cletus died.');
let times = recoveryFails == 0 ? "." : " again.";
sayWithPersona("you just died" + `${times}`);
// Save death location
lastDeathLocation = bot.entity.position.clone();
isRecoveringItems = true;
recoveryFails = 0;
});
// === Reaction to Being Attacked ===
bot.on('entityHurt', (entity) => {
if (entity === bot.entity) {
sayWithPersona("you got hurt.");
}
});
// Optional: log attacker
bot.on('entitySwingArm', (entity) => {
if (entity.position.distanceTo(bot.entity.position) < 3) {
const attacker = entity.username || entity.name;
sayWithPersona(`${attacker}` + "has just hit you.");
}
});

188
bot/bot_old.js Normal file
View file

@ -0,0 +1,188 @@
const mineflayer = require('mineflayer');
const { pathfinder, Movements, goals: { GoalNear } } = require('mineflayer-pathfinder');
const fs = require('fs');
const path = require('path');
const sqlite3 = require('sqlite3').verbose();
const axios = require('axios');
// === SQLite setup ===
const dbPath = path.join(__dirname, '../db/memory.db');
const db = new sqlite3.Database(dbPath, (err) => {
if (err) {
console.error('Failed to connect to database:', err);
} else {
console.log('Connected to SQLite database.');
db.run(`CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
action TEXT,
parameters TEXT,
context TEXT,
outcome TEXT,
score INTEGER
)`);
}
});
// === AI Integration (Ollama) ===
const OLLAMA_URL = 'http://192.168.1.3:11434/api/generate';
const MODEL_NAME = 'gemma3';
// === Create the bot ===
const bot = mineflayer.createBot({
host: '192.168.1.90',
port: 25565,
username: 'Cletus',
version: '1.20.4',
auth: 'offline'
});
bot.loadPlugin(pathfinder);
bot.on('spawn', () => {
console.log('Bot has spawned!');
const defaultMove = new Movements(bot);
bot.pathfinder.setMovements(defaultMove);
// Passive background wandering when idle
setInterval(() => {
if (!bot.pathfinder.isMoving() && !bot.targetDigBlock) {
const pos = bot.entity.position.offset(
Math.floor(Math.random() * 10 - 5),
0,
Math.floor(Math.random() * 10 - 5)
);
bot.chat("Ugh, wandering again. This server is so boring...");
bot.pathfinder.setGoal(new GoalNear(pos.x, pos.y, pos.z, 1));
}
}, 60000); // every 60 seconds
});
async function followPlayer(username) {
const target = bot.players[username]?.entity;
if (target) {
bot.chat(`Ugh, fine. Following ${username}.`);
bot.pathfinder.setGoal(new GoalFollow(target, 1), true);
db.run(`INSERT INTO tasks (action, parameters, context, outcome, score) VALUES (?, ?, ?, ?, ?)`,
['follow', JSON.stringify({ target: username }), 'Follow player', 'started', 0]);
} else {
bot.chat("Seriously? I can't even see you.");
db.run(`INSERT INTO tasks (action, parameters, context, outcome, score) VALUES (?, ?, ?, ?, ?)`,
['follow', JSON.stringify({ target: username }), 'Follow player', 'target not found', -1]);
}
}
async function exploreArea() {
const pos = bot.entity.position.offset(
Math.floor(Math.random() * 20 - 10),
0,
Math.floor(Math.random() * 20 - 10)
);
bot.chat("Exploring... because why not.");
bot.pathfinder.setGoal(new GoalNear(pos.x, pos.y, pos.z, 1));
db.run(`INSERT INTO tasks (action, context, outcome, score) VALUES (?, ?, ?, ?)`,
['explore', `Random target: ${pos}`, 'started', 0]);
}
async function digNearestWood() {
const logBlock = bot.findBlock({ matching: block => block.name.includes("log"), maxDistance: 16 });
if (!logBlock) {
bot.chat("Wow, no trees? Shocking.");
db.run(`INSERT INTO tasks (action, context, outcome, score) VALUES (?, ?, ?, ?)`,
['chop_tree', 'No logs nearby', 'failed', -1]);
return;
}
try {
bot.chat("Here we go again, chopping a tree.");
await bot.dig(logBlock);
db.run(`INSERT INTO tasks (action, context, outcome, score) VALUES (?, ?, ?, ?)`,
['chop_tree', `Block: ${logBlock.name}`, 'success', 1]);
} catch (e) {
bot.chat("Can't even chop right now. Figures.");
db.run(`INSERT INTO tasks (action, context, outcome, score) VALUES (?, ?, ?, ?)`,
['chop_tree', 'Dig error', 'failed', -1]);
}
}
async function handleAICommand(text, username) {
const lowered = text.toLowerCase();
if (lowered.includes("follow")) {
return followPlayer(username);
}
if (lowered.includes("explore")) {
return exploreArea();
}
if (lowered.includes("chop") && lowered.includes("tree")) {
return digNearestWood();
}
if (lowered.includes("dig") && lowered.includes("dirt")) {
const block = bot.blockAt(bot.entity.position.offset(0, -1, 0));
if (block && bot.canDigBlock(block)) {
bot.chat("Fine. Digging dirt. Happy now?");
await bot.dig(block);
db.run(`INSERT INTO tasks (action, context, outcome, score) VALUES (?, ?, ?, ?)`,
['dig_dirt', `Block below: ${block.name}`, 'success', 1]);
} else {
bot.chat("Wow, I can't even dig here.");
db.run(`INSERT INTO tasks (action, context, outcome, score) VALUES (?, ?, ?, ?)`,
['dig_dirt', 'nothing to dig', 'fail', -1]);
}
return;
}
bot.chat(text); // Fallback
}
bot.on('chat', async (username, message) => {
if (username === bot.username) return;
console.log(`${username}: ${message}`);
const prompt = `
You are Cletus, a sarcastic teenage Minecraft bot.
The player said: "${message}"
Determine:
1. If it's small talk, reply sarcastically.
2. If it's a command (dig, mine, follow, chop, build), return an actionable command.
Format your answer like this:
TYPE: chat - [text to say] OR TYPE: action - [command to execute]
`;
try {
const response = await axios.post(OLLAMA_URL, {
model: MODEL_NAME,
prompt,
stream: false
});
const aiReply = response.data?.response?.trim();
if (aiReply.startsWith("TYPE: chat")) {
const msg = aiReply.split(" - ")[1];
bot.chat(msg);
} else if (aiReply.startsWith("TYPE: action")) {
const cmd = aiReply.split(" - ")[1];
await handleAICommand(cmd, username);
} else {
bot.chat("I'm confused. You confuse me.");
}
} catch (err) {
console.error('AI call failed:', err.message);
}
});
bot.on('error', (err) => console.error('Bot error:', err));
bot.on('kicked', (reason) => console.log('Bot was kicked:', reason));
bot.on('end', () => console.log('Bot has disconnected.'));

38
bot/lib/ai-helper.js Normal file
View file

@ -0,0 +1,38 @@
const axios = require('axios');
/**
* Generates a persona-driven response from an LLM and returns the result.
*
* @param {string} message - The input prompt to complete.
* @param {object} options - Persona and LLM settings.
* @returns {Promise<string>} - A trimmed response string.
*/
async function chatWithPersona(message, options) {
const {
botName = 'Cletus',
persona = `a cranky teenager with a sense of dark humor and sarcasm. you have short responses and don't repeat yourself.`,
length = 20,
ollamaUrl = 'http://192.168.1.3:11434/api/generate',
model = 'gemma3'
} = options;
const prompt = `You are a minecraft bot named ${botName}. ` +
`You don't know that you're a bot though. Instead, you are a ${persona}. ` +
`Keep your responses around ${length}. Respond to this: ${message}`;
try {
const response = await axios.post(ollamaUrl, {
model,
prompt,
stream: false
});
const aiReply = response.data.response?.trim().replace(/^"|"$/g, '');
return aiReply || "...What?";
} catch (err) {
console.error("AI response failed:", err.message);
return "I'm too moody to respond right now.";
}
}
module.exports = { chatWithPersona };

View file

@ -0,0 +1,39 @@
// lib/log-surroundings.js
const interestingBlocks = [
'coal_ore', 'iron_ore', 'diamond_ore', 'gold_ore', 'emerald_ore',
'redstone_ore', 'lapis_ore', 'copper_ore',
'oak_log', 'birch_log', 'spruce_log',
'crafting_table', 'furnace', 'chest', 'anvil',
'beacon', 'bell', 'lectern', 'enchanting_table', 'portal',
'villager', 'spawner', 'campfire'
];
module.exports = function logSurroundings(bot, db, sayWithPersona) {
try {
const blocks = bot.findBlocks({
matching: block => interestingBlocks.includes(block.name),
maxDistance: 12,
count: 10
});
for (const pos of blocks) {
const block = bot.blockAt(pos);
if (!block || !block.name) continue;
const label = `found-${block.name}-${pos.x},${pos.y},${pos.z}`;
db.run(
`INSERT OR IGNORE INTO memory (label, data) VALUES (?, ?)`,
[label, JSON.stringify(pos)],
(err) => {
if (err) {
console.error("DB insert failed in logSurroundings:", err);
}
}
);
}
} catch (err) {
console.error("logSurroundings failed:", err);
sayWithPersona("your brain short-circuited while trying to remember stuff.");
}
};

53
bot/lib/memory.js Normal file
View file

@ -0,0 +1,53 @@
// lib/memory.js
module.exports = {
saveMemory: function (db, label, data, callback = () => {}) {
db.run(
`INSERT OR REPLACE INTO memory (label, data) VALUES (?, ?)`,
[label, JSON.stringify(data)],
callback
);
},
getMemory: function (db, label, callback) {
db.get(
`SELECT data FROM memory WHERE label = ?`,
[label],
(err, row) => {
if (err) return callback(err, null);
if (!row) return callback(null, null);
try {
callback(null, JSON.parse(row.data));
} catch (e) {
callback(e, null);
}
}
);
},
forgetMemory: function (db, label, callback = () => {}) {
db.run(
`DELETE FROM memory WHERE label = ?`,
[label],
callback
);
},
listMemory: function (db, callback) {
db.all(`SELECT label, data FROM memory`, [], (err, rows) => {
if (err) return callback(err, null);
const parsed = rows.map(row => ({
label: row.label,
data: (() => {
try {
return JSON.parse(row.data);
} catch {
return row.data;
}
})()
}));
callback(null, parsed);
});
}
};

30
build-cletus.sh Executable file
View file

@ -0,0 +1,30 @@
#!/bin/bash
set -e # Exit on error
# Set working paths
BOT_NAME="mineflayer-bot"
HOST_DB_PATH="$HOME/mineflayer-bot/db"
CONTAINER_DB_PATH="/app/bot/db"
CONTAINER_TASKS_PATH="/app/bot/bot-tasks"
echo "📦 Building Docker image for $BOT_NAME..."
docker buildx build --platform linux/amd64 -t $BOT_NAME . --load
echo "🧹 Cleaning up old container (if it exists)..."
docker rm -f $BOT_NAME 2>/dev/null || true
echo "📂 Ensuring local DB path exists..."
mkdir -p "$HOST_DB_PATH"
echo "🚀 Running container..."
docker run -d \
--name $BOT_NAME \
--platform linux/amd64 \
-v "$HOST_DB_PATH":"$CONTAINER_DB_PATH" \
-v "$(pwd)/bot/bot-tasks":"$CONTAINER_TASKS_PATH" \
$BOT_NAME
echo "📄 Tailing logs..."
docker logs -f $BOT_NAME

1
node_modules/.bin/color-support generated vendored Symbolic link
View file

@ -0,0 +1 @@
../color-support/bin.js

1
node_modules/.bin/fxparser generated vendored Symbolic link
View file

@ -0,0 +1 @@
../fast-xml-parser/src/cli/cli.js

1
node_modules/.bin/mkdirp generated vendored Symbolic link
View file

@ -0,0 +1 @@
../mkdirp/bin/cmd.js

1
node_modules/.bin/nearley-railroad generated vendored Symbolic link
View file

@ -0,0 +1 @@
../nearley/bin/nearley-railroad.js

1
node_modules/.bin/nearley-test generated vendored Symbolic link
View file

@ -0,0 +1 @@
../nearley/bin/nearley-test.js

1
node_modules/.bin/nearley-unparse generated vendored Symbolic link
View file

@ -0,0 +1 @@
../nearley/bin/nearley-unparse.js

1
node_modules/.bin/nearleyc generated vendored Symbolic link
View file

@ -0,0 +1 @@
../nearley/bin/nearleyc.js

1
node_modules/.bin/node-gyp generated vendored Symbolic link
View file

@ -0,0 +1 @@
../node-gyp/bin/node-gyp.js

1
node_modules/.bin/node-which generated vendored Symbolic link
View file

@ -0,0 +1 @@
../which/bin/node-which

1
node_modules/.bin/nodemon generated vendored Symbolic link
View file

@ -0,0 +1 @@
../nodemon/bin/nodemon.js

1
node_modules/.bin/nodetouch generated vendored Symbolic link
View file

@ -0,0 +1 @@
../touch/bin/nodetouch.js

1
node_modules/.bin/nopt generated vendored Symbolic link
View file

@ -0,0 +1 @@
../nopt/bin/nopt.js

1
node_modules/.bin/prebuild-install generated vendored Symbolic link
View file

@ -0,0 +1 @@
../prebuild-install/bin.js

1
node_modules/.bin/protodef-validator generated vendored Symbolic link
View file

@ -0,0 +1 @@
../protodef-validator/cli.js

1
node_modules/.bin/rc generated vendored Symbolic link
View file

@ -0,0 +1 @@
../rc/cli.js

1
node_modules/.bin/rimraf generated vendored Symbolic link
View file

@ -0,0 +1 @@
../rimraf/bin.js

1
node_modules/.bin/semver generated vendored Symbolic link
View file

@ -0,0 +1 @@
../semver/bin/semver.js

1
node_modules/.bin/uuid generated vendored Symbolic link
View file

@ -0,0 +1 @@
../uuid/dist/bin/uuid

4961
node_modules/.package-lock.json generated vendored Normal file

File diff suppressed because it is too large Load diff

118
node_modules/@aws-crypto/sha256-browser/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,118 @@
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [5.2.0](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/v5.1.0...v5.2.0) (2023-10-16)
### Features
- support ESM artifacts in all packages ([#752](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/752)) ([e930ffb](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/e930ffba5cfef66dd242049e7d514ced232c1e3b))
# [5.1.0](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/v5.0.0...v5.1.0) (2023-09-22)
### Bug Fixes
- Update tsc to 2.x ([#735](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/735)) ([782e0de](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/782e0de9f5fef41f694130580a69d940894b6b8c))
### Features
- Use @smithy/util-utf8 ([#730](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/730)) ([00fb851](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/00fb851ca3559d5a1f370f9256814de1210826b8)), closes [#699](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/699)
# [5.0.0](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/v4.0.1...v5.0.0) (2023-07-13)
- feat!: drop support for IE 11 (#629) ([6c49fb6](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/6c49fb6c1b1f18bbff02dbd77a37a21bdb40c959)), closes [#629](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/629)
### BREAKING CHANGES
- Remove support for IE11
Co-authored-by: texastony <5892063+texastony@users.noreply.github.com>
# [4.0.0](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/v3.0.0...v4.0.0) (2023-02-20)
**Note:** Version bump only for package @aws-crypto/sha256-browser
# [3.0.0](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/v2.0.2...v3.0.0) (2023-01-12)
### Bug Fixes
- **docs:** sha256 packages, clarify hmac support ([#455](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/455)) ([1be5043](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/1be5043325991f3f5ccb52a8dd928f004b4d442e))
- feat!: replace Hash implementations with Checksum interface (#492) ([da43dc0](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/da43dc0fdf669d9ebb5bfb1b1f7c79e46c4aaae1)), closes [#492](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/492)
### BREAKING CHANGES
- All classes that implemented `Hash` now implement `Checksum`.
## [2.0.2](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/v2.0.1...v2.0.2) (2022-09-07)
### Bug Fixes
- **#337:** update @aws-sdk/types ([#373](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/373)) ([b26a811](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/b26a811a392f5209c7ec7e57251500d4d78f97ff)), closes [#337](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/337)
## [2.0.1](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/v2.0.0...v2.0.1) (2021-12-09)
**Note:** Version bump only for package @aws-crypto/sha256-browser
# [2.0.0](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/v1.2.2...v2.0.0) (2021-10-25)
**Note:** Version bump only for package @aws-crypto/sha256-browser
## [1.2.2](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/v1.2.1...v1.2.2) (2021-10-12)
**Note:** Version bump only for package @aws-crypto/sha256-browser
## [1.2.1](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/v1.2.0...v1.2.1) (2021-09-17)
**Note:** Version bump only for package @aws-crypto/sha256-browser
# [1.2.0](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/v1.1.1...v1.2.0) (2021-09-17)
### Features
- add @aws-crypto/util ([8f489cb](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/8f489cbe4c0e134f826bac66f1bf5172597048b9))
## [1.1.1](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/@aws-crypto/sha256-browser@1.1.0...@aws-crypto/sha256-browser@1.1.1) (2021-07-13)
### Bug Fixes
- **sha256-browser:** throw errors not string ([#194](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/194)) ([7fa7ac4](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/7fa7ac445ef7a04dfb1ff479e7114aba045b2b2c))
# [1.1.0](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/@aws-crypto/sha256-browser@1.0.0...@aws-crypto/sha256-browser@1.1.0) (2021-01-13)
### Bug Fixes
- remove package lock ([6002a5a](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/6002a5ab9218dc8798c19dc205d3eebd3bec5b43))
- **aws-crypto:** export explicit dependencies on [@aws-types](https://github.com/aws-types) ([6a1873a](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/6a1873a4dcc2aaa4a1338595703cfa7099f17b8c))
- **deps-dev:** move @aws-sdk/types to devDependencies ([#188](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/188)) ([08efdf4](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/08efdf46dcc612d88c441e29945d787f253ee77d))
# [1.0.0](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/@aws-crypto/sha256-browser@1.0.0-alpha.0...@aws-crypto/sha256-browser@1.0.0) (2020-10-22)
**Note:** Version bump only for package @aws-crypto/sha256-browser
# [1.0.0-alpha.0](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/@aws-crypto/sha256-browser@0.1.0-preview.4...@aws-crypto/sha256-browser@1.0.0-alpha.0) (2020-02-07)
**Note:** Version bump only for package @aws-crypto/sha256-browser
# [0.1.0-preview.4](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/@aws-crypto/sha256-browser@0.1.0-preview.2...@aws-crypto/sha256-browser@0.1.0-preview.4) (2020-01-16)
### Bug Fixes
- Changed package.json files to point to the right Git repo ([#9](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/9)) ([028245d](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/028245d72e642ca98d82226afb300eb154503c4a)), closes [#8](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/8)
- es2015.iterable required ([#10](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/10)) ([6e08d83](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/6e08d83c33667ad8cbeeaaa7cedf1bbe05f79ed8))
- lerna version maintains package-lock ([#14](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/14)) ([2ef29e1](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/2ef29e13779703a5c9b32e93d18918fcb33b7272)), closes [#13](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/13)
# [0.1.0-preview.3](https://github.com/aws/aws-sdk-js-crypto-helpers/compare/@aws-crypto/sha256-browser@0.1.0-preview.2...@aws-crypto/sha256-browser@0.1.0-preview.3) (2019-11-15)
### Bug Fixes
- Changed package.json files to point to the right Git repo ([#9](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/9)) ([028245d](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/028245d72e642ca98d82226afb300eb154503c4a)), closes [#8](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/8)
- es2015.iterable required ([#10](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/10)) ([6e08d83](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/6e08d83c33667ad8cbeeaaa7cedf1bbe05f79ed8))
- lerna version maintains package-lock ([#14](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/14)) ([2ef29e1](https://github.com/aws/aws-sdk-js-crypto-helpers/commit/2ef29e13779703a5c9b32e93d18918fcb33b7272)), closes [#13](https://github.com/aws/aws-sdk-js-crypto-helpers/issues/13)
# [0.1.0-preview.2](https://github.com/aws/aws-javascript-crypto-helpers/compare/@aws-crypto/sha256-browser@0.1.0-preview.1...@aws-crypto/sha256-browser@0.1.0-preview.2) (2019-10-30)
### Bug Fixes
- remove /src/ from .npmignore (for sourcemaps) ([#5](https://github.com/aws/aws-javascript-crypto-helpers/issues/5)) ([ec52056](https://github.com/aws/aws-javascript-crypto-helpers/commit/ec52056))

202
node_modules/@aws-crypto/sha256-browser/LICENSE generated vendored Normal file
View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

31
node_modules/@aws-crypto/sha256-browser/README.md generated vendored Normal file
View file

@ -0,0 +1,31 @@
# @aws-crypto/sha256-browser
SHA256 wrapper for browsers that prefers `window.crypto.subtle` but will
fall back to a pure JS implementation in @aws-crypto/sha256-js
to provide a consistent interface for SHA256.
## Usage
- To hash "some data"
```
import {Sha256} from '@aws-crypto/sha256-browser'
const hash = new Sha256();
hash.update('some data');
const result = await hash.digest();
```
- To hmac "some data" with "a key"
```
import {Sha256} from '@aws-crypto/sha256-browser'
const hash = new Sha256('a key');
hash.update('some data');
const result = await hash.digest();
```
## Test
`npm test`

View file

@ -0,0 +1,10 @@
export declare const SHA_256_HASH: {
name: "SHA-256";
};
export declare const SHA_256_HMAC_ALGO: {
name: "HMAC";
hash: {
name: "SHA-256";
};
};
export declare const EMPTY_DATA_SHA_256: Uint8Array;

View file

@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EMPTY_DATA_SHA_256 = exports.SHA_256_HMAC_ALGO = exports.SHA_256_HASH = void 0;
exports.SHA_256_HASH = { name: "SHA-256" };
exports.SHA_256_HMAC_ALGO = {
name: "HMAC",
hash: exports.SHA_256_HASH
};
exports.EMPTY_DATA_SHA_256 = new Uint8Array([
227,
176,
196,
66,
152,
252,
28,
20,
154,
251,
244,
200,
153,
111,
185,
36,
39,
174,
65,
228,
100,
155,
147,
76,
164,
149,
153,
27,
120,
82,
184,
85
]);
//# sourceMappingURL=constants.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,YAAY,GAAwB,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;AAExD,QAAA,iBAAiB,GAAgD;IAC5E,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,oBAAY;CACnB,CAAC;AAEW,QAAA,kBAAkB,GAAG,IAAI,UAAU,CAAC;IAC/C,GAAG;IACH,GAAG;IACH,GAAG;IACH,EAAE;IACF,GAAG;IACH,GAAG;IACH,EAAE;IACF,EAAE;IACF,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,EAAE;IACF,EAAE;IACF,GAAG;IACH,EAAE;IACF,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,EAAE;IACF,GAAG;IACH,GAAG;IACH,GAAG;IACH,EAAE;IACF,GAAG;IACH,EAAE;IACF,GAAG;IACH,EAAE;CACH,CAAC,CAAC"}

View file

@ -0,0 +1,8 @@
import { Checksum, SourceData } from "@aws-sdk/types";
export declare class Sha256 implements Checksum {
private hash;
constructor(secret?: SourceData);
update(data: SourceData, encoding?: "utf8" | "ascii" | "latin1"): void;
digest(): Promise<Uint8Array>;
reset(): void;
}

View file

@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Sha256 = void 0;
var webCryptoSha256_1 = require("./webCryptoSha256");
var sha256_js_1 = require("@aws-crypto/sha256-js");
var supports_web_crypto_1 = require("@aws-crypto/supports-web-crypto");
var util_locate_window_1 = require("@aws-sdk/util-locate-window");
var util_1 = require("@aws-crypto/util");
var Sha256 = /** @class */ (function () {
function Sha256(secret) {
if ((0, supports_web_crypto_1.supportsWebCrypto)((0, util_locate_window_1.locateWindow)())) {
this.hash = new webCryptoSha256_1.Sha256(secret);
}
else {
this.hash = new sha256_js_1.Sha256(secret);
}
}
Sha256.prototype.update = function (data, encoding) {
this.hash.update((0, util_1.convertToBuffer)(data));
};
Sha256.prototype.digest = function () {
return this.hash.digest();
};
Sha256.prototype.reset = function () {
this.hash.reset();
};
return Sha256;
}());
exports.Sha256 = Sha256;
//# sourceMappingURL=crossPlatformSha256.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"crossPlatformSha256.js","sourceRoot":"","sources":["../../src/crossPlatformSha256.ts"],"names":[],"mappings":";;;AAAA,qDAA8D;AAC9D,mDAA2D;AAE3D,uEAAoE;AACpE,kEAA2D;AAC3D,yCAAmD;AAEnD;IAGE,gBAAY,MAAmB;QAC7B,IAAI,IAAA,uCAAiB,EAAC,IAAA,iCAAY,GAAE,CAAC,EAAE;YACrC,IAAI,CAAC,IAAI,GAAG,IAAI,wBAAe,CAAC,MAAM,CAAC,CAAC;SACzC;aAAM;YACL,IAAI,CAAC,IAAI,GAAG,IAAI,kBAAQ,CAAC,MAAM,CAAC,CAAC;SAClC;IACH,CAAC;IAED,uBAAM,GAAN,UAAO,IAAgB,EAAE,QAAsC;QAC7D,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAA,sBAAe,EAAC,IAAI,CAAC,CAAC,CAAC;IAC1C,CAAC;IAED,uBAAM,GAAN;QACE,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;IAC5B,CAAC;IAED,sBAAK,GAAL;QACE,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;IACH,aAAC;AAAD,CAAC,AAtBD,IAsBC;AAtBY,wBAAM"}

View file

@ -0,0 +1,2 @@
export * from "./crossPlatformSha256";
export { Sha256 as WebCryptoSha256 } from "./webCryptoSha256";

View file

@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebCryptoSha256 = void 0;
var tslib_1 = require("tslib");
tslib_1.__exportStar(require("./crossPlatformSha256"), exports);
var webCryptoSha256_1 = require("./webCryptoSha256");
Object.defineProperty(exports, "WebCryptoSha256", { enumerable: true, get: function () { return webCryptoSha256_1.Sha256; } });
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAAA,gEAAsC;AACtC,qDAA8D;AAArD,kHAAA,MAAM,OAAmB"}

View file

@ -0,0 +1,2 @@
import { SourceData } from "@aws-sdk/types";
export declare function isEmptyData(data: SourceData): boolean;

View file

@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isEmptyData = void 0;
function isEmptyData(data) {
if (typeof data === "string") {
return data.length === 0;
}
return data.byteLength === 0;
}
exports.isEmptyData = isEmptyData;
//# sourceMappingURL=isEmptyData.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"isEmptyData.js","sourceRoot":"","sources":["../../src/isEmptyData.ts"],"names":[],"mappings":";;;AAEA,SAAgB,WAAW,CAAC,IAAgB;IAC1C,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC5B,OAAO,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;KAC1B;IAED,OAAO,IAAI,CAAC,UAAU,KAAK,CAAC,CAAC;AAC/B,CAAC;AAND,kCAMC"}

View file

@ -0,0 +1,10 @@
import { Checksum, SourceData } from "@aws-sdk/types";
export declare class Sha256 implements Checksum {
private readonly secret?;
private key;
private toHash;
constructor(secret?: SourceData);
update(data: SourceData): void;
digest(): Promise<Uint8Array>;
reset(): void;
}

View file

@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Sha256 = void 0;
var util_1 = require("@aws-crypto/util");
var constants_1 = require("./constants");
var util_locate_window_1 = require("@aws-sdk/util-locate-window");
var Sha256 = /** @class */ (function () {
function Sha256(secret) {
this.toHash = new Uint8Array(0);
this.secret = secret;
this.reset();
}
Sha256.prototype.update = function (data) {
if ((0, util_1.isEmptyData)(data)) {
return;
}
var update = (0, util_1.convertToBuffer)(data);
var typedArray = new Uint8Array(this.toHash.byteLength + update.byteLength);
typedArray.set(this.toHash, 0);
typedArray.set(update, this.toHash.byteLength);
this.toHash = typedArray;
};
Sha256.prototype.digest = function () {
var _this = this;
if (this.key) {
return this.key.then(function (key) {
return (0, util_locate_window_1.locateWindow)()
.crypto.subtle.sign(constants_1.SHA_256_HMAC_ALGO, key, _this.toHash)
.then(function (data) { return new Uint8Array(data); });
});
}
if ((0, util_1.isEmptyData)(this.toHash)) {
return Promise.resolve(constants_1.EMPTY_DATA_SHA_256);
}
return Promise.resolve()
.then(function () {
return (0, util_locate_window_1.locateWindow)().crypto.subtle.digest(constants_1.SHA_256_HASH, _this.toHash);
})
.then(function (data) { return Promise.resolve(new Uint8Array(data)); });
};
Sha256.prototype.reset = function () {
var _this = this;
this.toHash = new Uint8Array(0);
if (this.secret && this.secret !== void 0) {
this.key = new Promise(function (resolve, reject) {
(0, util_locate_window_1.locateWindow)()
.crypto.subtle.importKey("raw", (0, util_1.convertToBuffer)(_this.secret), constants_1.SHA_256_HMAC_ALGO, false, ["sign"])
.then(resolve, reject);
});
this.key.catch(function () { });
}
};
return Sha256;
}());
exports.Sha256 = Sha256;
//# sourceMappingURL=webCryptoSha256.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"webCryptoSha256.js","sourceRoot":"","sources":["../../src/webCryptoSha256.ts"],"names":[],"mappings":";;;AACA,yCAAgE;AAChE,yCAIqB;AACrB,kEAA2D;AAE3D;IAKE,gBAAY,MAAmB;QAFvB,WAAM,GAAe,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;QAG7C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,KAAK,EAAE,CAAC;IACf,CAAC;IAED,uBAAM,GAAN,UAAO,IAAgB;QACrB,IAAI,IAAA,kBAAW,EAAC,IAAI,CAAC,EAAE;YACrB,OAAO;SACR;QAED,IAAM,MAAM,GAAG,IAAA,sBAAe,EAAC,IAAI,CAAC,CAAC;QACrC,IAAM,UAAU,GAAG,IAAI,UAAU,CAC/B,IAAI,CAAC,MAAM,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAC3C,CAAC;QACF,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QAC/B,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC/C,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC;IAC3B,CAAC;IAED,uBAAM,GAAN;QAAA,iBAkBC;QAjBC,IAAI,IAAI,CAAC,GAAG,EAAE;YACZ,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,UAAC,GAAG;gBACvB,OAAA,IAAA,iCAAY,GAAE;qBACX,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,6BAAiB,EAAE,GAAG,EAAE,KAAI,CAAC,MAAM,CAAC;qBACvD,IAAI,CAAC,UAAC,IAAI,IAAK,OAAA,IAAI,UAAU,CAAC,IAAI,CAAC,EAApB,CAAoB,CAAC;YAFvC,CAEuC,CACxC,CAAC;SACH;QAED,IAAI,IAAA,kBAAW,EAAC,IAAI,CAAC,MAAM,CAAC,EAAE;YAC5B,OAAO,OAAO,CAAC,OAAO,CAAC,8BAAkB,CAAC,CAAC;SAC5C;QAED,OAAO,OAAO,CAAC,OAAO,EAAE;aACrB,IAAI,CAAC;YACJ,OAAA,IAAA,iCAAY,GAAE,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,wBAAY,EAAE,KAAI,CAAC,MAAM,CAAC;QAA9D,CAA8D,CAC/D;aACA,IAAI,CAAC,UAAC,IAAI,IAAK,OAAA,OAAO,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,EAArC,CAAqC,CAAC,CAAC;IAC3D,CAAC;IAED,sBAAK,GAAL;QAAA,iBAgBC;QAfC,IAAI,CAAC,MAAM,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;QAChC,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,EAAE;YACzC,IAAI,CAAC,GAAG,GAAG,IAAI,OAAO,CAAC,UAAC,OAAO,EAAE,MAAM;gBACrC,IAAA,iCAAY,GAAE;qBACT,MAAM,CAAC,MAAM,CAAC,SAAS,CACxB,KAAK,EACL,IAAA,sBAAe,EAAC,KAAI,CAAC,MAAoB,CAAC,EAC1C,6BAAiB,EACjB,KAAK,EACL,CAAC,MAAM,CAAC,CACX;qBACI,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;YAC7B,CAAC,CAAC,CAAC;YACH,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,cAAO,CAAC,CAAC,CAAC;SAC1B;IACH,CAAC;IACH,aAAC;AAAD,CAAC,AA7DD,IA6DC;AA7DY,wBAAM"}

View file

@ -0,0 +1,10 @@
export declare const SHA_256_HASH: {
name: "SHA-256";
};
export declare const SHA_256_HMAC_ALGO: {
name: "HMAC";
hash: {
name: "SHA-256";
};
};
export declare const EMPTY_DATA_SHA_256: Uint8Array;

View file

@ -0,0 +1,40 @@
export var SHA_256_HASH = { name: "SHA-256" };
export var SHA_256_HMAC_ALGO = {
name: "HMAC",
hash: SHA_256_HASH
};
export var EMPTY_DATA_SHA_256 = new Uint8Array([
227,
176,
196,
66,
152,
252,
28,
20,
154,
251,
244,
200,
153,
111,
185,
36,
39,
174,
65,
228,
100,
155,
147,
76,
164,
149,
153,
27,
120,
82,
184,
85
]);
//# sourceMappingURL=constants.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,IAAM,YAAY,GAAwB,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;AAErE,MAAM,CAAC,IAAM,iBAAiB,GAAgD;IAC5E,IAAI,EAAE,MAAM;IACZ,IAAI,EAAE,YAAY;CACnB,CAAC;AAEF,MAAM,CAAC,IAAM,kBAAkB,GAAG,IAAI,UAAU,CAAC;IAC/C,GAAG;IACH,GAAG;IACH,GAAG;IACH,EAAE;IACF,GAAG;IACH,GAAG;IACH,EAAE;IACF,EAAE;IACF,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,EAAE;IACF,EAAE;IACF,GAAG;IACH,EAAE;IACF,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,EAAE;IACF,GAAG;IACH,GAAG;IACH,GAAG;IACH,EAAE;IACF,GAAG;IACH,EAAE;IACF,GAAG;IACH,EAAE;CACH,CAAC,CAAC"}

View file

@ -0,0 +1,8 @@
import { Checksum, SourceData } from "@aws-sdk/types";
export declare class Sha256 implements Checksum {
private hash;
constructor(secret?: SourceData);
update(data: SourceData, encoding?: "utf8" | "ascii" | "latin1"): void;
digest(): Promise<Uint8Array>;
reset(): void;
}

View file

@ -0,0 +1,27 @@
import { Sha256 as WebCryptoSha256 } from "./webCryptoSha256";
import { Sha256 as JsSha256 } from "@aws-crypto/sha256-js";
import { supportsWebCrypto } from "@aws-crypto/supports-web-crypto";
import { locateWindow } from "@aws-sdk/util-locate-window";
import { convertToBuffer } from "@aws-crypto/util";
var Sha256 = /** @class */ (function () {
function Sha256(secret) {
if (supportsWebCrypto(locateWindow())) {
this.hash = new WebCryptoSha256(secret);
}
else {
this.hash = new JsSha256(secret);
}
}
Sha256.prototype.update = function (data, encoding) {
this.hash.update(convertToBuffer(data));
};
Sha256.prototype.digest = function () {
return this.hash.digest();
};
Sha256.prototype.reset = function () {
this.hash.reset();
};
return Sha256;
}());
export { Sha256 };
//# sourceMappingURL=crossPlatformSha256.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"crossPlatformSha256.js","sourceRoot":"","sources":["../../src/crossPlatformSha256.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEnD;IAGE,gBAAY,MAAmB;QAC7B,IAAI,iBAAiB,CAAC,YAAY,EAAE,CAAC,EAAE;YACrC,IAAI,CAAC,IAAI,GAAG,IAAI,eAAe,CAAC,MAAM,CAAC,CAAC;SACzC;aAAM;YACL,IAAI,CAAC,IAAI,GAAG,IAAI,QAAQ,CAAC,MAAM,CAAC,CAAC;SAClC;IACH,CAAC;IAED,uBAAM,GAAN,UAAO,IAAgB,EAAE,QAAsC;QAC7D,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC;IAC1C,CAAC;IAED,uBAAM,GAAN;QACE,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;IAC5B,CAAC;IAED,sBAAK,GAAL;QACE,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;IACH,aAAC;AAAD,CAAC,AAtBD,IAsBC"}

View file

@ -0,0 +1,2 @@
export * from "./crossPlatformSha256";
export { Sha256 as WebCryptoSha256 } from "./webCryptoSha256";

View file

@ -0,0 +1,3 @@
export * from "./crossPlatformSha256";
export { Sha256 as WebCryptoSha256 } from "./webCryptoSha256";
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,OAAO,EAAE,MAAM,IAAI,eAAe,EAAE,MAAM,mBAAmB,CAAC"}

View file

@ -0,0 +1,2 @@
import { SourceData } from "@aws-sdk/types";
export declare function isEmptyData(data: SourceData): boolean;

View file

@ -0,0 +1,7 @@
export function isEmptyData(data) {
if (typeof data === "string") {
return data.length === 0;
}
return data.byteLength === 0;
}
//# sourceMappingURL=isEmptyData.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"isEmptyData.js","sourceRoot":"","sources":["../../src/isEmptyData.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,WAAW,CAAC,IAAgB;IAC1C,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC5B,OAAO,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;KAC1B;IAED,OAAO,IAAI,CAAC,UAAU,KAAK,CAAC,CAAC;AAC/B,CAAC"}

View file

@ -0,0 +1,10 @@
import { Checksum, SourceData } from "@aws-sdk/types";
export declare class Sha256 implements Checksum {
private readonly secret?;
private key;
private toHash;
constructor(secret?: SourceData);
update(data: SourceData): void;
digest(): Promise<Uint8Array>;
reset(): void;
}

View file

@ -0,0 +1,53 @@
import { isEmptyData, convertToBuffer } from "@aws-crypto/util";
import { EMPTY_DATA_SHA_256, SHA_256_HASH, SHA_256_HMAC_ALGO, } from "./constants";
import { locateWindow } from "@aws-sdk/util-locate-window";
var Sha256 = /** @class */ (function () {
function Sha256(secret) {
this.toHash = new Uint8Array(0);
this.secret = secret;
this.reset();
}
Sha256.prototype.update = function (data) {
if (isEmptyData(data)) {
return;
}
var update = convertToBuffer(data);
var typedArray = new Uint8Array(this.toHash.byteLength + update.byteLength);
typedArray.set(this.toHash, 0);
typedArray.set(update, this.toHash.byteLength);
this.toHash = typedArray;
};
Sha256.prototype.digest = function () {
var _this = this;
if (this.key) {
return this.key.then(function (key) {
return locateWindow()
.crypto.subtle.sign(SHA_256_HMAC_ALGO, key, _this.toHash)
.then(function (data) { return new Uint8Array(data); });
});
}
if (isEmptyData(this.toHash)) {
return Promise.resolve(EMPTY_DATA_SHA_256);
}
return Promise.resolve()
.then(function () {
return locateWindow().crypto.subtle.digest(SHA_256_HASH, _this.toHash);
})
.then(function (data) { return Promise.resolve(new Uint8Array(data)); });
};
Sha256.prototype.reset = function () {
var _this = this;
this.toHash = new Uint8Array(0);
if (this.secret && this.secret !== void 0) {
this.key = new Promise(function (resolve, reject) {
locateWindow()
.crypto.subtle.importKey("raw", convertToBuffer(_this.secret), SHA_256_HMAC_ALGO, false, ["sign"])
.then(resolve, reject);
});
this.key.catch(function () { });
}
};
return Sha256;
}());
export { Sha256 };
//# sourceMappingURL=webCryptoSha256.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"webCryptoSha256.js","sourceRoot":"","sources":["../../src/webCryptoSha256.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,GAClB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAE3D;IAKE,gBAAY,MAAmB;QAFvB,WAAM,GAAe,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;QAG7C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,KAAK,EAAE,CAAC;IACf,CAAC;IAED,uBAAM,GAAN,UAAO,IAAgB;QACrB,IAAI,WAAW,CAAC,IAAI,CAAC,EAAE;YACrB,OAAO;SACR;QAED,IAAM,MAAM,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;QACrC,IAAM,UAAU,GAAG,IAAI,UAAU,CAC/B,IAAI,CAAC,MAAM,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAC3C,CAAC;QACF,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QAC/B,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC/C,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC;IAC3B,CAAC;IAED,uBAAM,GAAN;QAAA,iBAkBC;QAjBC,IAAI,IAAI,CAAC,GAAG,EAAE;YACZ,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,UAAC,GAAG;gBACvB,OAAA,YAAY,EAAE;qBACX,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,iBAAiB,EAAE,GAAG,EAAE,KAAI,CAAC,MAAM,CAAC;qBACvD,IAAI,CAAC,UAAC,IAAI,IAAK,OAAA,IAAI,UAAU,CAAC,IAAI,CAAC,EAApB,CAAoB,CAAC;YAFvC,CAEuC,CACxC,CAAC;SACH;QAED,IAAI,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;YAC5B,OAAO,OAAO,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;SAC5C;QAED,OAAO,OAAO,CAAC,OAAO,EAAE;aACrB,IAAI,CAAC;YACJ,OAAA,YAAY,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,KAAI,CAAC,MAAM,CAAC;QAA9D,CAA8D,CAC/D;aACA,IAAI,CAAC,UAAC,IAAI,IAAK,OAAA,OAAO,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,EAArC,CAAqC,CAAC,CAAC;IAC3D,CAAC;IAED,sBAAK,GAAL;QAAA,iBAgBC;QAfC,IAAI,CAAC,MAAM,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;QAChC,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,EAAE;YACzC,IAAI,CAAC,GAAG,GAAG,IAAI,OAAO,CAAC,UAAC,OAAO,EAAE,MAAM;gBACrC,YAAY,EAAE;qBACT,MAAM,CAAC,MAAM,CAAC,SAAS,CACxB,KAAK,EACL,eAAe,CAAC,KAAI,CAAC,MAAoB,CAAC,EAC1C,iBAAiB,EACjB,KAAK,EACL,CAAC,MAAM,CAAC,CACX;qBACI,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;YAC7B,CAAC,CAAC,CAAC;YACH,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,cAAO,CAAC,CAAC,CAAC;SAC1B;IACH,CAAC;IACH,aAAC;AAAD,CAAC,AA7DD,IA6DC"}

View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,10 @@
# @smithy/is-array-buffer
[![NPM version](https://img.shields.io/npm/v/@smithy/is-array-buffer/latest.svg)](https://www.npmjs.com/package/@smithy/is-array-buffer)
[![NPM downloads](https://img.shields.io/npm/dm/@smithy/is-array-buffer.svg)](https://www.npmjs.com/package/@smithy/is-array-buffer)
> An internal package
## Usage
You probably shouldn't, at least directly.

View file

@ -0,0 +1,32 @@
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
isArrayBuffer: () => isArrayBuffer
});
module.exports = __toCommonJS(src_exports);
var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
isArrayBuffer
});

View file

@ -0,0 +1,2 @@
export const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) ||
Object.prototype.toString.call(arg) === "[object ArrayBuffer]";

View file

@ -0,0 +1,4 @@
/**
* @internal
*/
export declare const isArrayBuffer: (arg: any) => arg is ArrayBuffer;

View file

@ -0,0 +1,4 @@
/**
* @internal
*/
export declare const isArrayBuffer: (arg: any) => arg is ArrayBuffer;

View file

@ -0,0 +1,60 @@
{
"name": "@smithy/is-array-buffer",
"version": "2.2.0",
"description": "Provides a function for detecting if an argument is an ArrayBuffer",
"scripts": {
"build": "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types && yarn build:types:downlevel'",
"build:cjs": "node ../../scripts/inline is-array-buffer",
"build:es": "yarn g:tsc -p tsconfig.es.json",
"build:types": "yarn g:tsc -p tsconfig.types.json",
"build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
"stage-release": "rimraf ./.release && yarn pack && mkdir ./.release && tar zxvf ./package.tgz --directory ./.release && rm ./package.tgz",
"clean": "rimraf ./dist-* && rimraf *.tsbuildinfo || exit 0",
"lint": "eslint -c ../../.eslintrc.js \"src/**/*.ts\"",
"format": "prettier --config ../../prettier.config.js --ignore-path ../.prettierignore --write \"**/*.{ts,md,json}\"",
"test": "yarn g:jest"
},
"author": {
"name": "AWS SDK for JavaScript Team",
"url": "https://aws.amazon.com/javascript/"
},
"license": "Apache-2.0",
"main": "./dist-cjs/index.js",
"module": "./dist-es/index.js",
"types": "./dist-types/index.d.ts",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=14.0.0"
},
"typesVersions": {
"<4.0": {
"dist-types/*": [
"dist-types/ts3.4/*"
]
}
},
"files": [
"dist-*/**"
],
"homepage": "https://github.com/awslabs/smithy-typescript/tree/main/packages/is-array-buffer",
"repository": {
"type": "git",
"url": "https://github.com/awslabs/smithy-typescript.git",
"directory": "packages/is-array-buffer"
},
"devDependencies": {
"@tsconfig/recommended": "1.0.1",
"concurrently": "7.0.0",
"downlevel-dts": "0.10.1",
"rimraf": "3.0.2",
"typedoc": "0.23.23"
},
"typedoc": {
"entryPoint": "src/index.ts"
},
"publishConfig": {
"directory": ".release/package"
}
}

View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,10 @@
# @smithy/util-buffer-from
[![NPM version](https://img.shields.io/npm/v/@smithy/util-buffer-from/latest.svg)](https://www.npmjs.com/package/@smithy/util-buffer-from)
[![NPM downloads](https://img.shields.io/npm/dm/@smithy/util-buffer-from.svg)](https://www.npmjs.com/package/@smithy/util-buffer-from)
> An internal package
## Usage
You probably shouldn't, at least directly.

View file

@ -0,0 +1,47 @@
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
fromArrayBuffer: () => fromArrayBuffer,
fromString: () => fromString
});
module.exports = __toCommonJS(src_exports);
var import_is_array_buffer = require("@smithy/is-array-buffer");
var import_buffer = require("buffer");
var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => {
if (!(0, import_is_array_buffer.isArrayBuffer)(input)) {
throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
}
return import_buffer.Buffer.from(input, offset, length);
}, "fromArrayBuffer");
var fromString = /* @__PURE__ */ __name((input, encoding) => {
if (typeof input !== "string") {
throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
}
return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input);
}, "fromString");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
fromArrayBuffer,
fromString
});

View file

@ -0,0 +1,14 @@
import { isArrayBuffer } from "@smithy/is-array-buffer";
import { Buffer } from "buffer";
export const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {
if (!isArrayBuffer(input)) {
throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
}
return Buffer.from(input, offset, length);
};
export const fromString = (input, encoding) => {
if (typeof input !== "string") {
throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
}
return encoding ? Buffer.from(input, encoding) : Buffer.from(input);
};

View file

@ -0,0 +1,13 @@
import { Buffer } from "buffer";
/**
* @internal
*/
export declare const fromArrayBuffer: (input: ArrayBuffer, offset?: number, length?: number) => Buffer;
/**
* @internal
*/
export type StringEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex";
/**
* @internal
*/
export declare const fromString: (input: string, encoding?: StringEncoding) => Buffer;

View file

@ -0,0 +1,13 @@
import { Buffer } from "buffer";
/**
* @internal
*/
export declare const fromArrayBuffer: (input: ArrayBuffer, offset?: number, length?: number) => Buffer;
/**
* @internal
*/
export type StringEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex";
/**
* @internal
*/
export declare const fromString: (input: string, encoding?: StringEncoding) => Buffer;

View file

@ -0,0 +1,61 @@
{
"name": "@smithy/util-buffer-from",
"version": "2.2.0",
"scripts": {
"build": "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types && yarn build:types:downlevel'",
"build:cjs": "node ../../scripts/inline util-buffer-from",
"build:es": "yarn g:tsc -p tsconfig.es.json",
"build:types": "yarn g:tsc -p tsconfig.types.json",
"build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
"stage-release": "rimraf ./.release && yarn pack && mkdir ./.release && tar zxvf ./package.tgz --directory ./.release && rm ./package.tgz",
"clean": "rimraf ./dist-* && rimraf *.tsbuildinfo || exit 0",
"lint": "eslint -c ../../.eslintrc.js \"src/**/*.ts\"",
"format": "prettier --config ../../prettier.config.js --ignore-path ../.prettierignore --write \"**/*.{ts,md,json}\"",
"test": "yarn g:jest"
},
"author": {
"name": "AWS SDK for JavaScript Team",
"url": "https://aws.amazon.com/javascript/"
},
"license": "Apache-2.0",
"dependencies": {
"@smithy/is-array-buffer": "^2.2.0",
"tslib": "^2.6.2"
},
"devDependencies": {
"@tsconfig/recommended": "1.0.1",
"@types/node": "^14.14.31",
"concurrently": "7.0.0",
"downlevel-dts": "0.10.1",
"rimraf": "3.0.2",
"typedoc": "0.23.23"
},
"main": "./dist-cjs/index.js",
"module": "./dist-es/index.js",
"types": "./dist-types/index.d.ts",
"engines": {
"node": ">=14.0.0"
},
"typesVersions": {
"<4.0": {
"dist-types/*": [
"dist-types/ts3.4/*"
]
}
},
"files": [
"dist-*/**"
],
"homepage": "https://github.com/awslabs/smithy-typescript/tree/main/packages/util-buffer-from",
"repository": {
"type": "git",
"url": "https://github.com/awslabs/smithy-typescript.git",
"directory": "packages/util-buffer-from"
},
"typedoc": {
"entryPoint": "src/index.ts"
},
"publishConfig": {
"directory": ".release/package"
}
}

View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,4 @@
# @smithy/util-utf8
[![NPM version](https://img.shields.io/npm/v/@smithy/util-utf8/latest.svg)](https://www.npmjs.com/package/@smithy/util-utf8)
[![NPM downloads](https://img.shields.io/npm/dm/@smithy/util-utf8.svg)](https://www.npmjs.com/package/@smithy/util-utf8)

View file

@ -0,0 +1 @@
module.exports = require("./index.js");

View file

@ -0,0 +1 @@
module.exports = require("./index.js");

View file

@ -0,0 +1,65 @@
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
fromUtf8: () => fromUtf8,
toUint8Array: () => toUint8Array,
toUtf8: () => toUtf8
});
module.exports = __toCommonJS(src_exports);
// src/fromUtf8.ts
var import_util_buffer_from = require("@smithy/util-buffer-from");
var fromUtf8 = /* @__PURE__ */ __name((input) => {
const buf = (0, import_util_buffer_from.fromString)(input, "utf8");
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
}, "fromUtf8");
// src/toUint8Array.ts
var toUint8Array = /* @__PURE__ */ __name((data) => {
if (typeof data === "string") {
return fromUtf8(data);
}
if (ArrayBuffer.isView(data)) {
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
}
return new Uint8Array(data);
}, "toUint8Array");
// src/toUtf8.ts
var toUtf8 = /* @__PURE__ */ __name((input) => {
if (typeof input === "string") {
return input;
}
if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
}
return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
}, "toUtf8");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
fromUtf8,
toUint8Array,
toUtf8
});

View file

@ -0,0 +1 @@
module.exports = require("./index.js");

View file

@ -0,0 +1 @@
module.exports = require("./index.js");

View file

@ -0,0 +1 @@
module.exports = require("./index.js");

View file

@ -0,0 +1 @@
export const fromUtf8 = (input) => new TextEncoder().encode(input);

View file

@ -0,0 +1,5 @@
import { fromString } from "@smithy/util-buffer-from";
export const fromUtf8 = (input) => {
const buf = fromString(input, "utf8");
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
};

View file

@ -0,0 +1,3 @@
export * from "./fromUtf8";
export * from "./toUint8Array";
export * from "./toUtf8";

View file

@ -0,0 +1,10 @@
import { fromUtf8 } from "./fromUtf8";
export const toUint8Array = (data) => {
if (typeof data === "string") {
return fromUtf8(data);
}
if (ArrayBuffer.isView(data)) {
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
}
return new Uint8Array(data);
};

View file

@ -0,0 +1,9 @@
export const toUtf8 = (input) => {
if (typeof input === "string") {
return input;
}
if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
}
return new TextDecoder("utf-8").decode(input);
};

View file

@ -0,0 +1,10 @@
import { fromArrayBuffer } from "@smithy/util-buffer-from";
export const toUtf8 = (input) => {
if (typeof input === "string") {
return input;
}
if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
}
return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
};

View file

@ -0,0 +1 @@
export declare const fromUtf8: (input: string) => Uint8Array;

View file

@ -0,0 +1 @@
export declare const fromUtf8: (input: string) => Uint8Array;

View file

@ -0,0 +1,3 @@
export * from "./fromUtf8";
export * from "./toUint8Array";
export * from "./toUtf8";

View file

@ -0,0 +1 @@
export declare const toUint8Array: (data: string | ArrayBuffer | ArrayBufferView) => Uint8Array;

View file

@ -0,0 +1,7 @@
/**
*
* This does not convert non-utf8 strings to utf8, it only passes through strings if
* a string is received instead of a Uint8Array.
*
*/
export declare const toUtf8: (input: Uint8Array | string) => string;

View file

@ -0,0 +1,7 @@
/**
*
* This does not convert non-utf8 strings to utf8, it only passes through strings if
* a string is received instead of a Uint8Array.
*
*/
export declare const toUtf8: (input: Uint8Array | string) => string;

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