prefix
string | suffix
string | middle
string | formatted_text
string | file_path
string |
---|---|---|---|---|
import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr
|
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
|
(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
|
<|fim_prefix|>import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr<|fim_suffix|> exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
<|fim_middle|>(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
|
bin/release-note-generator.ts
|
import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to ente
|
ease Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
|
r your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Rel
|
<|fim_prefix|>import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to ente<|fim_suffix|>ease Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
<|fim_middle|>r your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Rel
|
bin/release-note-generator.ts
|
import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
|
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
|
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
|
<|fim_prefix|>import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
<|fim_suffix|> const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
<|fim_middle|> type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
|
bin/release-note-generator.ts
|
import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhance
|
nse',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
|
ments', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API respo
|
<|fim_prefix|>import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhance<|fim_suffix|>nse',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
<|fim_middle|>ments', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API respo
|
bin/release-note-generator.ts
|
import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead
|
}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
|
);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status
|
<|fim_prefix|>import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead<|fim_suffix|>}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
<|fim_middle|>);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status
|
bin/release-note-generator.ts
|
import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
|
`./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
|
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath =
|
<|fim_prefix|>import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
<|fim_suffix|>`./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
<|fim_middle|>{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath =
|
bin/release-note-generator.ts
|
import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an atte
|
.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
|
mpt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console
|
<|fim_prefix|>import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an atte<|fim_suffix|>.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
<|fim_middle|>mpt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console
|
bin/release-note-generator.ts
|
import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (exis
|
othing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
|
tsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If n
|
<|fim_prefix|>import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (exis<|fim_suffix|>othing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
<|fim_middle|>tsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If n
|
bin/release-note-generator.ts
|
import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
|
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
|
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
|
<|fim_prefix|>import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-release-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcoming-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {<|fim_suffix|> 'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
<|fim_middle|>
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
|
bin/release-note-generator.ts
|
import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-releas
|
ng-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
|
e-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcomi
|
<|fim_prefix|>import { exec } from 'node:child_process';
import { existsSync, writeFile } from 'node:fs';
import { exit } from 'node:process';
import prompts from 'prompts';
async function run() {
const username = await execAsync(
// eslint-disable-next-line rulesdir/typography
"gh api user --jq '.login'",
'To avoid having to enter your username, consider installing the official GitHub CLI (https://github.com/cli/cli) and logging in with `gh auth login`.',
);
const activePr = await getActivePr(username);
if (activePr) {
console.log(
`Found potentially matching PR ${activePr.number}: ${activePr.title}`,
);
}
const prNumber = activePr?.number ?? (await getNextPrNumber());
const result = await prompts([
{
name: 'githubUsername',
message: 'Comma-separated GitHub username(s)',
type: 'text',
initial: username,
},
{
name: 'pullRequestNumber',
message: 'PR Number',
type: 'number',
initial: prNumber,
},
{
name: 'releaseNoteType',
message: 'Release Note Type',
type: 'select',
choices: [
{ title: 'β¨ Features', value: 'Features' },
{ title: 'π Enhancements', value: 'Enhancements' },
{ title: 'π Bugfix', value: 'Bugfix' },
{ title: 'βοΈ Maintenance', value: 'Maintenance' },
],
},
{
name: 'oneLineSummary',
message: 'Brief Summary',
type: 'text',
initial: activePr?.title,
},
]);
if (
!result.githubUsername ||
!result.oneLineSummary ||
!result.releaseNoteType
) {
console.log('All questions must be answered. Exiting');
exit(1);
}
const fileContents = getFileContents(
result.releaseNoteType,
result.githubUsername,
result.oneLineSummary,
);
const filepath = `./upcoming-releas<|fim_suffix|>ng-release-notes/${prNumber}.md`,
);
}
});
}
// makes an attempt to find an existing open PR from <username>:<branch>
async function getActivePr(
username: string,
): Promise<{ number: number; title: string } | undefined> {
if (!username) {
return undefined;
}
const branchName = await execAsync('git rev-parse --abbrev-ref HEAD');
if (!branchName) {
return undefined;
}
const forkHead = `${username}:${branchName}`;
return getPrNumberFromHead(forkHead);
}
async function getPrNumberFromHead(
head: string,
): Promise<{ number: number; title: string } | undefined> {
try {
// head is a weird query parameter in this API call. If nothing matches, it
// will return as if the head query parameter doesn't exist. To get around
// this, we make the page size 2 and only return the number if the length.
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/pulls?state=open&per_page=2&head=' +
head,
);
if (!resp.ok) {
console.warn('error fetching from github pulls api:', resp.status);
return undefined;
}
const ghResponse = await resp.json();
if (ghResponse?.length === 1) {
return ghResponse[0];
} else {
return undefined;
}
} catch (e) {
console.warn('error fetching from github pulls api:', e);
}
}
async function getNextPrNumber(): Promise<number> {
try {
const resp = await fetch(
'https://api.github.com/repos/actualbudget/actual/issues?state=all&per_page=1',
);
if (!resp.ok) {
throw new Error(`API responded with status: ${resp.status}`);
}
const ghResponse = await resp.json();
const latestPrNumber = ghResponse?.[0]?.number;
if (!latestPrNumber) {
console.error(
'Could not find latest issue number in GitHub API response',
ghResponse,
);
exit(1);
}
return latestPrNumber + 1;
} catch (error) {
console.error('Failed to fetch next PR number:', error);
exit(1);
}
}
function getFileContents(type: string, username: string, summary: string) {
return `---
category: ${type}
<|fim_middle|>e-notes/${prNumber}.md`;
if (existsSync(filepath)) {
const { confirm } = await prompts({
name: 'confirm',
type: 'confirm',
message: `This will overwrite the existing release note ${filepath} Are you sure?`,
});
if (!confirm) {
console.log('Exiting');
exit(1);
}
}
writeFile(filepath, fileContents, err => {
if (err) {
console.error('Failed to write release note file:', err);
exit(1);
} else {
console.log(
`Release note generated successfully: ./upcomi
|
bin/release-note-generator.ts
|
import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetc
|
alApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
|
h').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
await actu
|
<|fim_prefix|>import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetc<|fim_suffix|>alApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
<|fim_middle|>h').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
await actu
|
packages/api/index.ts
|
import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globa
|
rt async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
|
lThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
expo
|
<|fim_prefix|>import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globa<|fim_suffix|>rt async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
<|fim_middle|>lThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
expo
|
packages/api/index.ts
|
import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
e
|
return import('node-fetch').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
|
xport * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
|
<|fim_prefix|>import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
e<|fim_suffix|> return import('node-fetch').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
<|fim_middle|>xport * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
|
packages/api/index.ts
|
import t
|
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
|
ype {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
|
<|fim_prefix|>import t<|fim_suffix|> };
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
<|fim_middle|>ype {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
|
packages/api/index.ts
|
import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (ac
|
etch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
|
tualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then(({ default: f
|
<|fim_prefix|>import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (ac<|fim_suffix|>etch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
<|fim_middle|>tualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then(({ default: f
|
packages/api/index.ts
|
import type {
RequestInfo as FetchIn
|
as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
|
fo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
)
|
<|fim_prefix|>import type {
RequestInfo as FetchIn<|fim_suffix|> as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
<|fim_middle|>fo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
)
|
packages/api/index.ts
|
import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as
|
function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
|
injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async
|
<|fim_prefix|>import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as <|fim_suffix|> function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
<|fim_middle|>injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async
|
packages/api/index.ts
|
import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
impor
|
rsion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
|
t * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVe
|
<|fim_prefix|>import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
impor<|fim_suffix|>rsion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
<|fim_middle|>t * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVe
|
packages/api/index.ts
|
import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then((
|
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
|
{ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
|
<|fim_prefix|>import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then((<|fim_suffix|>await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
<|fim_middle|>{ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.lib;
}
export async function shutdown() {
if (actualApp) {
|
packages/api/index.ts
|
import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit
|
lib;
}
export async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
|
),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.
|
<|fim_prefix|>import type {
RequestInfo as FetchInfo,
RequestInit as FetchInit,
} from 'node-fetch';
// loot-core types
import type { InitConfig } from 'loot-core/server/main';
// @ts-ignore: bundle not available until we build it
// eslint-disable-next-line import/extensions
import * as bundle from './app/bundle.api.js';
import * as injected from './injected';
import { validateNodeVersion } from './validateNodeVersion';
let actualApp: null | typeof bundle.lib;
export const internal = bundle.lib;
export * from './methods';
export * as utils from './utils';
export async function init(config: InitConfig = {}) {
if (actualApp) {
return;
}
validateNodeVersion();
if (!globalThis.fetch) {
globalThis.fetch = (url: URL | RequestInfo, init?: RequestInit) => {
return import('node-fetch').then(({ default: fetch }) =>
fetch(url as unknown as FetchInfo, init as unknown as FetchInit<|fim_suffix|>lib;
}
export async function shutdown() {
if (actualApp) {
await actualApp.send('sync');
await actualApp.send('close-budget');
actualApp = null;
}
}
<|fim_middle|>),
) as unknown as Promise<Response>;
};
}
await bundle.init(config);
actualApp = bundle.lib;
injected.override(bundle.lib.send);
return bundle.
|
packages/api/index.ts
|
// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export func
|
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t
|
tion deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
|
<|fim_prefix|>// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export func<|fim_suffix|>}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t<|fim_middle|>tion deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
|
packages/api/methods.ts
|
// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
|
port function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t
|
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
ex
|
<|fim_prefix|>// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
<|fim_suffix|>port function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t<|fim_middle|> return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
ex
|
packages/api/methods.ts
|
// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month
|
nsferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t
|
, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, tra
|
<|fim_prefix|>// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month<|fim_suffix|>nsferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t<|fim_middle|>, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, tra
|
packages/api/methods.ts
|
// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportT
|
alBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t
|
ransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initi
|
<|fim_prefix|>// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportT<|fim_suffix|>alBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t<|fim_middle|>ransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initi
|
packages/api/methods.ts
|
// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId,
|
function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t
|
startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export
|
<|fim_prefix|>// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId,<|fim_suffix|> function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t<|fim_middle|> startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export
|
packages/api/methods.ts
|
// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password?
|
on deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t
|
} = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export functi
|
<|fim_prefix|>// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? <|fim_suffix|>on deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t<|fim_middle|>} = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export functi
|
packages/api/methods.ts
|
// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as
|
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t
|
injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
|
<|fim_prefix|>// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as <|fim_suffix|>accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t<|fim_middle|>injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
|
packages/api/methods.ts
|
// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create
|
{ group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t
|
', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create',
|
<|fim_prefix|>// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create<|fim_suffix|> { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t<|fim_middle|>', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create',
|
packages/api/methods.ts
|
// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
|
{
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t
|
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value)
|
<|fim_prefix|>// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
<|fim_suffix|> {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen', { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-groups-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t<|fim_middle|> await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value)
|
packages/api/methods.ts
|
// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen'
|
s-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t
|
, { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-group
|
<|fim_prefix|>// @ts-strict-ignore
import type { Handlers } from 'loot-core/types/handlers';
import type { ImportTransactionEntity } from 'loot-core/types/models/import-transaction';
import * as injected from './injected';
export { q } from './app/query';
function send<K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> {
return injected.send(name, args);
}
export async function runImport(name, func) {
await send('api/start-import', { budgetName: name });
try {
await func();
} catch (e) {
await send('api/abort-import');
throw e;
}
await send('api/finish-import');
}
export async function loadBudget(budgetId) {
return send('api/load-budget', { id: budgetId });
}
export async function downloadBudget(syncId, { password }: { password? } = {}) {
return send('api/download-budget', { syncId, password });
}
export async function getBudgets() {
return send('api/get-budgets');
}
export async function sync() {
return send('api/sync');
}
export async function runBankSync(args?: { accountId: string }) {
return send('api/bank-sync', args);
}
export async function batchBudgetUpdates(func) {
await send('api/batch-budget-start');
try {
await func();
} finally {
await send('api/batch-budget-end');
}
}
/**
* @deprecated Please use `aqlQuery` instead.
* This function will be removed in a future release.
*/
export function runQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function aqlQuery(query) {
return send('api/query', { query: query.serialize() });
}
export function getBudgetMonths() {
return send('api/budget-months');
}
export function getBudgetMonth(month) {
return send('api/budget-month', { month });
}
export function setBudgetAmount(month, categoryId, value) {
return send('api/budget-set-amount', { month, categoryId, amount: value });
}
export function setBudgetCarryover(month, categoryId, flag) {
return send('api/budget-set-carryover', { month, categoryId, flag });
}
export function addTransactions(
accountId,
transactions,
{ learnCategories = false, runTransfers = false } = {},
) {
return send('api/transactions-add', {
accountId,
transactions,
learnCategories,
runTransfers,
});
}
export interface ImportTransactionsOpts {
defaultCleared?: boolean;
}
export function importTransactions(
accountId: string,
transactions: ImportTransactionEntity[],
opts: ImportTransactionsOpts = {
defaultCleared: true,
},
) {
return send('api/transactions-import', {
accountId,
transactions,
opts,
});
}
export function getTransactions(accountId, startDate, endDate) {
return send('api/transactions-get', { accountId, startDate, endDate });
}
export function updateTransaction(id, fields) {
return send('api/transaction-update', { id, fields });
}
export function deleteTransaction(id) {
return send('api/transaction-delete', { id });
}
export function getAccounts() {
return send('api/accounts-get');
}
export function createAccount(account, initialBalance?) {
return send('api/account-create', { account, initialBalance });
}
export function updateAccount(id, fields) {
return send('api/account-update', { id, fields });
}
export function closeAccount(id, transferAccountId?, transferCategoryId?) {
return send('api/account-close', {
id,
transferAccountId,
transferCategoryId,
});
}
export function reopenAccount(id) {
return send('api/account-reopen'<|fim_suffix|>s-get');
}
export function createCategoryGroup(group) {
return send('api/category-group-create', { group });
}
export function updateCategoryGroup(id, fields) {
return send('api/category-group-update', { id, fields });
}
export function deleteCategoryGroup(id, transferCategoryId?) {
return send('api/category-group-delete', { id, transferCategoryId });
}
export function getCategories() {
return send('api/categories-get', { grouped: false });
}
export function createCategory(category) {
return send('api/category-create', { category });
}
export function updateCategory(id, fields) {
return send('api/category-update', { id, fields });
}
export function deleteCategory(id, t<|fim_middle|>, { id });
}
export function deleteAccount(id) {
return send('api/account-delete', { id });
}
export function getAccountBalance(id, cutoff?) {
return send('api/account-balance', { id, cutoff });
}
export function getCategoryGroups() {
return send('api/category-group
|
packages/api/methods.ts
|
export default {
test: {
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stderr'):
|
;
|
boolean | void {
// print only console.error
return type === 'stderr';
},
},
}
|
<|fim_prefix|>export default {
test: {
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stderr'): <|fim_suffix|>;
<|fim_middle|>boolean | void {
// print only console.error
return type === 'stderr';
},
},
}
|
packages/api/vitest.config.ts
|
export default {
test: {
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void
|
{
// print only console.error
return type === 'stderr';
},
},
};
|
<|fim_prefix|>export default {
test: {
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void<|fim_suffix|>
<|fim_middle|> {
// print only console.error
return type === 'stderr';
},
},
};
|
packages/api/vitest.config.ts
|
|
export default {
test: {
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stderr'):
|
},
},
};
|
boolean | void {
// print only console.error
return type === 'stderr';
|
<|fim_prefix|>export default {
test: {
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stderr'): <|fim_suffix|>
},
},
};
<|fim_middle|>boolean | void {
// print only console.error
return type === 'stderr';
|
packages/api/vitest.config.ts
|
export default {
test: {
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stder
|
,
},
};
|
r'): boolean | void {
// print only console.error
return type === 'stderr';
}
|
<|fim_prefix|>export default {
test: {
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stder<|fim_suffix|>,
},
};
<|fim_middle|>r'): boolean | void {
// print only console.error
return type === 'stderr';
}
|
packages/api/vitest.config.ts
|
export default {
test: {
globals: true,
onConsoleLog(
|
= 'stderr';
},
},
};
|
log: string, type: 'stdout' | 'stderr'): boolean | void {
// print only console.error
return type ==
|
<|fim_prefix|>export default {
test: {
globals: true,
onConsoleLog(<|fim_suffix|>= 'stderr';
},
},
};
<|fim_middle|>log: string, type: 'stdout' | 'stderr'): boolean | void {
// print only console.error
return type ==
|
packages/api/vitest.config.ts
|
export default {
test: {
globals: true,
|
return type === 'stderr';
},
},
};
|
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void {
// print only console.error
|
<|fim_prefix|>export default {
test: {
globals: true,
<|fim_suffix|> return type === 'stderr';
},
},
};
<|fim_middle|>onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void {
// print only console.error
|
packages/api/vitest.config.ts
|
ex
|
{
// print only console.error
return type === 'stderr';
},
},
};
|
port default {
test: {
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void
|
<|fim_prefix|>ex<|fim_suffix|>{
// print only console.error
return type === 'stderr';
},
},
};
<|fim_middle|>port default {
test: {
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void
|
packages/api/vitest.config.ts
|
export default {
test: {
|
return type === 'stderr';
},
},
};
|
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void {
// print only console.error
|
<|fim_prefix|>export default {
test: {
<|fim_suffix|> return type === 'stderr';
},
},
};
<|fim_middle|>globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void {
// print only console.error
|
packages/api/vitest.config.ts
|
export default {
test: {
|
r';
},
},
};
|
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void {
// print only console.error
return type === 'stder
|
<|fim_prefix|>export default {
test: {<|fim_suffix|>r';
},
},
};
<|fim_middle|>
globals: true,
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void {
// print only console.error
return type === 'stder
|
packages/api/vitest.config.ts
|
export default {
test: {
globals: true,
|
},
},
};
|
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void {
// print only console.error
return type === 'stderr';
|
<|fim_prefix|>export default {
test: {
globals: true,
<|fim_suffix|> },
},
};
<|fim_middle|> onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void {
// print only console.error
return type === 'stderr';
|
packages/api/vitest.config.ts
|
// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
|
ries).to
|
const categoryId = await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(catego
|
<|fim_prefix|>// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
<|fim_suffix|>ries).to<|fim_middle|> const categoryId = await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(catego
|
packages/api/methods.test.ts
|
// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis
|
=> {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to
|
: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async ()
|
<|fim_prefix|>// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis<|fim_suffix|>=> {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to<|fim_middle|>: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async ()
|
packages/api/methods.test.ts
|
// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test categor
|
oup',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to
|
y group
const mainGroupId = await api.createCategoryGroup({
name: 'test-gr
|
<|fim_prefix|>// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test categor<|fim_suffix|>oup',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to<|fim_middle|>y group
const mainGroupId = await api.createCategoryGroup({
name: 'test-gr
|
packages/api/methods.test.ts
|
// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.create
|
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to
|
CategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
name: 'test-budget',
|
<|fim_prefix|>// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.create<|fim_suffix|>group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to<|fim_middle|>CategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
name: 'test-budget',
|
packages/api/methods.test.ts
|
// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
|
= await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to
|
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId
|
<|fim_prefix|>// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
<|fim_suffix|>= await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to<|fim_middle|> expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId
|
packages/api/methods.test.ts
|
// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive
|
yContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to
|
: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arra
|
<|fim_prefix|>// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive<|fim_suffix|>yContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to<|fim_middle|>: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arra
|
packages/api/methods.test.ts
|
// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3C
|
month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to
|
E28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth =
|
<|fim_prefix|>// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3C<|fim_suffix|> month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to<|fim_middle|>E28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth =
|
packages/api/methods.test.ts
|
// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async ()
|
expect(categories).to
|
=> {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
|
<|fim_prefix|>// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async ()<|fim_suffix|> expect(categories).to<|fim_middle|> => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
|
packages/api/methods.test.ts
|
// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
|
e group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to
|
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// updat
|
<|fim_prefix|>// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',<|fim_suffix|>e group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to<|fim_middle|>
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// updat
|
packages/api/methods.test.ts
|
// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
|
name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to
|
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
|
<|fim_prefix|>// @ts-strict-ignore
import * as fs from 'fs/promises';
import * as path from 'path';
import * as api from './index';
const budgetName = 'test-budget';
global.IS_TESTING = true;
beforeEach(async () => {
const budgetPath = path.join(__dirname, '/mocks/budgets/', budgetName);
await fs.rm(budgetPath, { force: true, recursive: true });
await createTestBudget('default-budget-template', budgetName);
await api.init({
dataDir: path.join(__dirname, '/mocks/budgets/'),
});
});
afterEach(async () => {
global.currentMonth = null;
await api.shutdown();
});
async function createTestBudget(templateName: string, name: string) {
const templatePath = path.join(
__dirname,
'/../loot-core/src/mocks/files',
templateName,
);
const budgetPath = path.join(__dirname, '/mocks/budgets/', name);
await fs.mkdir(budgetPath);
await fs.copyFile(
path.join(templatePath, 'metadata.json'),
path.join(budgetPath, 'metadata.json'),
);
await fs.copyFile(
path.join(templatePath, 'db.sqlite'),
path.join(budgetPath, 'db.sqlite'),
);
}
describe('API setup and teardown', () => {
// apis: loadBudget, getBudgetMonths
test('successfully loads budget', async () => {
await expect(api.loadBudget(budgetName)).resolves.toBeUndefined();
await expect(api.getBudgetMonths()).resolves.toMatchSnapshot();
});
});
describe('API CRUD operations', () => {
beforeEach(async () => {
// load test budget
await api.loadBudget(budgetName);
});
// api: getBudgets
test('getBudgets', async () => {
const budgets = await api.getBudgets();
expect(budgets).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'test-budget',
name: 'Default Test Db',
}),
]),
);
});
// apis: getCategoryGroups, createCategoryGroup, updateCategoryGroup, deleteCategoryGroup
test('CategoryGroups: successfully update category groups', async () => {
const month = '2023-10';
global.currentMonth = month;
// get existing category groups
const groups = await api.getCategoryGroups();
expect(groups).toEqual(
expect.arrayContaining([
expect.objectContaining({
hidden: false,
id: 'fc3825fd-b982-4b72-b768-5b30844cf832',
is_income: false,
name: 'Usual Expenses',
}),
expect.objectContaining({
hidden: false,
id: 'a137772f-cf2f-4089-9432-822d2ddc1466',
is_income: false,
name: 'Investments and Savings',
}),
expect.objectContaining({
hidden: false,
id: '2E1F5BDB-209B-43F9-AF2C-3CE28E380C00',
is_income: true,
name: 'Income',
}),
]),
);
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
let budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// update group
await api.updateCategoryGroup(mainGroupId, {
name: 'update-tests',
});
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
<|fim_suffix|> name: 'test-budget',
group_id: mainGroupId,
});
const categoryIdHidden = await api.createCategory({
name: 'test-budget-hidden',
group_id: mainGroupId,
hidden: true,
});
let categories = await api.getCategories();
expect(categories).to<|fim_middle|> expect.arrayContaining([
expect.objectContaining({
id: mainGroupId,
}),
]),
);
// delete group
await api.deleteCategoryGroup(mainGroupId);
budgetMonth = await api.getBudgetMonth(month);
expect(budgetMonth.categoryGroups).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
id: mainGroupId,
}),
]),
);
});
// apis: createCategory, getCategories, updateCategory, deleteCategory
test('Categories: successfully update categories', async () => {
const month = '2023-10';
global.currentMonth = month;
// create our test category group
const mainGroupId = await api.createCategoryGroup({
name: 'test-group',
});
const secondaryGroupId = await api.createCategoryGroup({
name: 'test-secondary-group',
});
const categoryId = await api.createCategory({
|
packages/api/methods.test.ts
|
import * as SyncPb from './proto/sync_pb';
export {
merkle,
getClock,
setClock,
makeCloc
|
SyncProtoBuf = SyncPb;
|
k,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Timestamp,
} from './crdt';
export const
|
<|fim_prefix|>import * as SyncPb from './proto/sync_pb';
export {
merkle,
getClock,
setClock,
makeCloc<|fim_suffix|>SyncProtoBuf = SyncPb;
<|fim_middle|>k,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Timestamp,
} from './crdt';
export const
|
packages/crdt/src/index.ts
|
import * as SyncPb from './proto/sync_pb';
export {
merkle,
getClock,
setClock,
makeClock,
makeCli
|
Pb;
|
entId,
serializeClock,
deserializeClock,
type Clock,
Timestamp,
} from './crdt';
export const SyncProtoBuf = Sync
|
<|fim_prefix|>import * as SyncPb from './proto/sync_pb';
export {
merkle,
getClock,
setClock,
makeClock,
makeCli<|fim_suffix|>Pb;
<|fim_middle|>entId,
serializeClock,
deserializeClock,
type Clock,
Timestamp,
} from './crdt';
export const SyncProtoBuf = Sync
|
packages/crdt/src/index.ts
|
import * as Sy
|
} from './crdt';
export const SyncProtoBuf = SyncPb;
|
ncPb from './proto/sync_pb';
export {
merkle,
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Timestamp,
|
<|fim_prefix|>import * as Sy<|fim_suffix|>} from './crdt';
export const SyncProtoBuf = SyncPb;
<|fim_middle|>ncPb from './proto/sync_pb';
export {
merkle,
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Timestamp,
|
packages/crdt/src/index.ts
|
import * as SyncPb from './proto/sync_pb';
export {
merkle,
getClock,
setClock,
makeClock,
makeClientId,
seriali
|
t SyncProtoBuf = SyncPb;
|
zeClock,
deserializeClock,
type Clock,
Timestamp,
} from './crdt';
export cons
|
<|fim_prefix|>import * as SyncPb from './proto/sync_pb';
export {
merkle,
getClock,
setClock,
makeClock,
makeClientId,
seriali<|fim_suffix|>t SyncProtoBuf = SyncPb;
<|fim_middle|>zeClock,
deserializeClock,
type Clock,
Timestamp,
} from './crdt';
export cons
|
packages/crdt/src/index.ts
|
import * as SyncPb from './proto/sync_pb';
export {
merkle,
getClock,
setClock,
m
|
;
|
akeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Timestamp,
} from './crdt';
export const SyncProtoBuf = SyncPb
|
<|fim_prefix|>import * as SyncPb from './proto/sync_pb';
export {
merkle,
getClock,
setClock,
m<|fim_suffix|>;
<|fim_middle|>akeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Timestamp,
} from './crdt';
export const SyncProtoBuf = SyncPb
|
packages/crdt/src/index.ts
|
import * as SyncPb from './proto/sync_pb';
e
|
,
Timestamp,
} from './crdt';
export const SyncProtoBuf = SyncPb;
|
xport {
merkle,
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock
|
<|fim_prefix|>import * as SyncPb from './proto/sync_pb';
e<|fim_suffix|>,
Timestamp,
} from './crdt';
export const SyncProtoBuf = SyncPb;
<|fim_middle|>xport {
merkle,
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock
|
packages/crdt/src/index.ts
|
import * as SyncPb from './proto/s
|
pe Clock,
Timestamp,
} from './crdt';
export const SyncProtoBuf = SyncPb;
|
ync_pb';
export {
merkle,
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
ty
|
<|fim_prefix|>import * as SyncPb from './proto/s<|fim_suffix|>pe Clock,
Timestamp,
} from './crdt';
export const SyncProtoBuf = SyncPb;
<|fim_middle|>ync_pb';
export {
merkle,
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
ty
|
packages/crdt/src/index.ts
|
import * as SyncPb from './proto/sync_pb';
export {
merkle,
getClock,
|
nst SyncProtoBuf = SyncPb;
|
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Timestamp,
} from './crdt';
export co
|
<|fim_prefix|>import * as SyncPb from './proto/sync_pb';
export {
merkle,
getClock,
<|fim_suffix|>nst SyncProtoBuf = SyncPb;
<|fim_middle|>setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Timestamp,
} from './crdt';
export co
|
packages/crdt/src/index.ts
|
import * as SyncPb from './proto/sync_pb';
export {
merkle,
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deseri
|
= SyncPb;
|
alizeClock,
type Clock,
Timestamp,
} from './crdt';
export const SyncProtoBuf
|
<|fim_prefix|>import * as SyncPb from './proto/sync_pb';
export {
merkle,
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deseri<|fim_suffix|>= SyncPb;
<|fim_middle|>alizeClock,
type Clock,
Timestamp,
} from './crdt';
export const SyncProtoBuf
|
packages/crdt/src/index.ts
|
import * as SyncPb from './proto/sync_pb
|
deserializeClock,
type Clock,
Timestamp,
} from './crdt';
export const SyncProtoBuf = SyncPb;
|
';
export {
merkle,
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
|
<|fim_prefix|>import * as SyncPb from './proto/sync_pb<|fim_suffix|> deserializeClock,
type Clock,
Timestamp,
} from './crdt';
export const SyncProtoBuf = SyncPb;
<|fim_middle|>';
export {
merkle,
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
|
packages/crdt/src/index.ts
|
import { Timestamp
|
uld parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
|
} from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('sho
|
<|fim_prefix|>import { Timestamp <|fim_suffix|>uld parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
<|fim_middle|>} from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('sho
|
packages/crdt/src/crdt/timestamp.test.ts
|
import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftEr
|
tamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
|
ror);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Times
|
<|fim_prefix|>import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftEr<|fim_suffix|>tamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
<|fim_middle|>ror);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Times
|
packages/crdt/src/crdt/timestamp.test.ts
|
import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01
|
{
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
|
-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function ()
|
<|fim_prefix|>import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01<|fim_suffix|> {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
<|fim_middle|>-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function ()
|
packages/crdt/src/crdt/timestamp.test.ts
|
import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.
|
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
|
now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
|
<|fim_prefix|>import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.<|fim_suffix|> }
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
<|fim_middle|>now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
|
packages/crdt/src/crdt/timestamp.test.ts
|
import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
|
mestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
|
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Ti
|
<|fim_prefix|>import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
<|fim_suffix|>mestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
<|fim_middle|> const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Ti
|
packages/crdt/src/crdt/timestamp.test.ts
|
import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send())
|
00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
|
.toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:
|
<|fim_prefix|>import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send())<|fim_suffix|>00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
<|fim_middle|>.toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:
|
packages/crdt/src/crdt/timestamp.test.ts
|
import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('19
|
p.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
|
70-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestam
|
<|fim_prefix|>import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('19<|fim_suffix|>p.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
<|fim_middle|>70-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestam
|
packages/crdt/src/crdt/timestamp.test.ts
|
import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:
|
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
|
00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
|
<|fim_prefix|>import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:<|fim_suffix|> now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
<|fim_middle|>00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
|
packages/crdt/src/crdt/timestamp.test.ts
|
import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-0
|
(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
|
1T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual
|
<|fim_prefix|>import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-0<|fim_suffix|>(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
now = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
<|fim_middle|>1T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual
|
packages/crdt/src/crdt/timestamp.test.ts
|
import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
no
|
monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
|
w = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global
|
<|fim_prefix|>import { Timestamp } from './timestamp';
describe('Timestamp', function () {
let now = 0;
let prevNow: typeof Date.now;
beforeEach(function () {
prevNow = Date.now;
Date.now = () => now;
Timestamp.init({ node: '1' });
});
afterEach(() => {
Date.now = prevNow;
});
describe('comparison', function () {
it('should be in order', function () {
const sendTimestamp = Timestamp.send();
expect(Timestamp.zero).toBe(Timestamp.zero);
expect(Timestamp.max > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp > Timestamp.zero).toBeTruthy();
expect(sendTimestamp && sendTimestamp < Timestamp.max).toBeTruthy();
});
});
describe('parsing', function () {
it('should not parse', function () {
const invalidInputs = [
null,
undefined,
{},
[],
42,
'',
' ',
'0',
'invalid',
'1969-1-1T0:0:0.0Z-0-0-0',
'1969-01-01T00:00:00.000Z-0000-0000000000000000',
'10000-01-01T00:00:00.000Z-FFFF-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-10000-FFFFFFFFFFFFFFFF',
'9999-12-31T23:59:59.999Z-FFFF-10000000000000000',
];
for (const invalidInput of invalidInputs) {
expect(Timestamp.parse(invalidInput as string)).toBe(null);
}
});
it('should parse', function () {
const validInputs = [
'1970-01-01T00:00:00.000Z-0000-0000000000000000',
'2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF',
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
];
for (const validInput of validInputs) {
const parsed = Timestamp.parse(validInput)!;
expect(typeof parsed).toBe('object');
expect(parsed.millis() >= 0).toBeTruthy();
expect(parsed.millis() < 253402300800000).toBeTruthy();
expect(parsed.counter() >= 0).toBeTruthy();
expect(parsed.counter() < 65536).toBeTruthy();
expect(typeof parsed.node()).toBe('string');
expect(parsed.toString()).toBe(validInput);
}
});
});
describe('send', function () {
it('should send monotonically with a monotonic clock', function () {
now = 10;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.010Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.011Z-0000-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.012Z-0000-0000000000000001'),
);
});
it('should send monotonically with a stuttering clock', function () {
now = 20;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0000-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.020Z-0002-0000000000000001'),
);
now++;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.021Z-0000-0000000000000001'),
);
});
it('should send monotonically with a regressing clock', function () {
now = 30;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0000-0000000000000001'),
);
now--;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0001-0000000000000001'),
);
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.030Z-0002-0000000000000001'),
);
no<|fim_suffix|>monotonic clock', function () {
now = 52;
expect(
Timestamp.recv(
Timestamp.parse('1970-01-01T00:00:00.051Z-0000-0000000000000002')!,
),
).toEqual(
<|fim_middle|>w = 31;
expect(Timestamp.send()).toEqual(
Timestamp.parse('1970-01-01T00:00:00.031Z-0000-0000000000000001'),
);
});
it('should fail with counter overflow', function () {
now = 40;
for (let i = 0; i < 65536; i++) Timestamp.send();
expect(Timestamp.send).toThrow(Timestamp.OverflowError);
});
it('should fail with clock drift', function () {
now = -(5 * 60 * 1000 + 1);
expect(Timestamp.send).toThrow(Timestamp.ClockDriftError);
});
});
describe('recv', function () {
it('should receive monotonically with a global
|
packages/crdt/src/crdt/timestamp.test.ts
|
import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
m
|
', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me
|
essage('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF
|
<|fim_prefix|>import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
m<|fim_suffix|>', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me<|fim_middle|>essage('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF
|
packages/crdt/src/crdt/merkle.test.ts
|
import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
|
erkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me
|
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = m
|
<|fim_prefix|>import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
<|fim_suffix|>erkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me<|fim_middle|>// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = m
|
packages/crdt/src/crdt/merkle.test.ts
|
import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 140
|
000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me
|
0),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0
|
<|fim_prefix|>import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 140<|fim_suffix|>000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me<|fim_middle|>0),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0
|
packages/crdt/src/crdt/merkle.test.ts
|
import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timesta
|
456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me
|
mpStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123
|
<|fim_prefix|>import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timesta<|fim_suffix|>456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me<|fim_middle|>mpStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123
|
packages/crdt/src/crdt/merkle.test.ts
|
import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(tr
|
01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me
|
ie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-
|
<|fim_prefix|>import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(tr<|fim_suffix|>01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me<|fim_middle|>ie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-
|
packages/crdt/src/crdt/merkle.test.ts
|
import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z'
|
018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me
|
,
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2
|
<|fim_prefix|>import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z'<|fim_suffix|>018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me<|fim_middle|>,
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2
|
packages/crdt/src/crdt/merkle.test.ts
|
import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2,
|
hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me
|
messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.
|
<|fim_prefix|>import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, <|fim_suffix|>hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me<|fim_middle|>messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.
|
packages/crdt/src/crdt/merkle.test.ts
|
import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
|
2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me
|
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('
|
<|fim_prefix|>import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
<|fim_suffix|>2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me<|fim_middle|> );
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('
|
packages/crdt/src/crdt/merkle.test.ts
|
import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
m
|
1-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me
|
essages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-1
|
<|fim_prefix|>import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
m<|fim_suffix|>1-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
me<|fim_middle|>essages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-1
|
packages/crdt/src/crdt/merkle.test.ts
|
import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
messa
|
123456789ABCDEF', 1800),
me
|
ge('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0
|
<|fim_prefix|>import * as merkle from './merkle';
import { Timestamp } from './timestamp';
function message(timestampStr: string, hash: number) {
const timestamp = Timestamp.parse(timestampStr)!;
timestamp.hash = () => hash;
return { timestamp };
}
function insertMessages(
trie: merkle.TrieNode,
messages: ReturnType<typeof message>[],
) {
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
return trie;
}
describe('merkle trie', () => {
test('adding an item works', () => {
let trie = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2018-11-12T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
trie = merkle.insert(
trie,
Timestamp.parse('2018-11-13T13:21:40.122Z-0000-0123456789ABCDEF')!,
);
expect(trie).toMatchSnapshot();
});
test('diff returns the correct time difference', () => {
let trie1 = merkle.emptyTrie();
let trie2 = merkle.emptyTrie();
const messages = [
// First client messages
message('2018-11-13T13:20:40.122Z-0000-0123456789ABCDEF', 1000),
message('2018-11-14T13:05:35.122Z-0000-0123456789ABCDEF', 1100),
message('2018-11-15T22:19:00.122Z-0000-0123456789ABCDEF', 1200),
// Second client messages
message('2018-11-20T13:19:40.122Z-0000-0123456789ABCDEF', 1300),
message('2018-11-25T13:19:40.122Z-0000-0123456789ABCDEF', 1400),
];
trie1 = merkle.insert(trie1, messages[0].timestamp);
trie1 = merkle.insert(trie1, messages[1].timestamp);
trie1 = merkle.insert(trie1, messages[2].timestamp);
expect(trie1.hash).toBe(788);
trie2 = merkle.insert(trie2, messages[3].timestamp);
trie2 = merkle.insert(trie2, messages[4].timestamp);
expect(trie2.hash).toBe(108);
expect(new Date(merkle.diff(trie1, trie2)!).toISOString()).toBe(
'2018-11-02T17:15:00.000Z',
);
trie1 = merkle.insert(trie1, messages[3].timestamp);
trie1 = merkle.insert(trie1, messages[4].timestamp);
trie2 = merkle.insert(trie2, messages[0].timestamp);
trie2 = merkle.insert(trie2, messages[1].timestamp);
trie2 = merkle.insert(trie2, messages[2].timestamp);
expect(trie1.hash).toBe(888);
expect(trie1.hash).toBe(trie2.hash);
});
test('diffing works with empty tries', () => {
const trie1 = merkle.emptyTrie();
const trie2 = merkle.insert(
merkle.emptyTrie(),
Timestamp.parse('2009-01-02T10:17:37.789Z-0000-0000testinguuid1')!,
);
expect(merkle.diff(trie1, trie2)).toBe(0);
});
test('pruning works and keeps correct hashes', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
message('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0123456789ABCDEF', 1800),
message('2018-11-01T02:19:00.000Z-0000-0123456789ABCDEF', 1900),
message('2018-11-01T02:28:00.000Z-0000-0123456789ABCDEF', 2000),
message('2018-11-01T02:37:00.000Z-0000-0123456789ABCDEF', 2100),
];
let trie = merkle.emptyTrie();
messages.forEach(msg => {
trie = merkle.insert(trie, msg.timestamp);
});
expect(trie.hash).toBe(2496);
expect(trie).toMatchSnapshot();
const pruned = merkle.prune(trie);
expect(pruned.hash).toBe(2496);
expect(pruned).toMatchSnapshot();
});
test('diffing differently shaped tries returns correct time', () => {
const messages = [
message('2018-11-01T01:00:00.000Z-0000-0123456789ABCDEF', 1000),
message('2018-11-01T01:09:00.000Z-0000-0123456789ABCDEF', 1100),
message('2018-11-01T01:18:00.000Z-0000-0123456789ABCDEF', 1200),
message('2018-11-01T01:27:00.000Z-0000-0123456789ABCDEF', 1300),
message('2018-11-01T01:36:00.000Z-0000-0123456789ABCDEF', 1400),
message('2018-11-01T01:45:00.000Z-0000-0123456789ABCDEF', 1500),
message('2018-11-01T01:54:00.000Z-0000-0123456789ABCDEF', 1600),
messa<|fim_suffix|>123456789ABCDEF', 1800),
me<|fim_middle|>ge('2018-11-01T02:03:00.000Z-0000-0123456789ABCDEF', 1700),
message('2018-11-01T02:10:00.000Z-0000-0
|
packages/crdt/src/crdt/merkle.test.ts
|
import * as merkle from './
|
stamp,
} from './timestamp';
|
merkle';
export { merkle };
export {
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Time
|
<|fim_prefix|>import * as merkle from './<|fim_suffix|>stamp,
} from './timestamp';
<|fim_middle|>merkle';
export { merkle };
export {
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Time
|
packages/crdt/src/crdt/index.ts
|
import * as merkle from './merkle';
export { merkle };
export {
g
|
from './timestamp';
|
etClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Timestamp,
}
|
<|fim_prefix|>import * as merkle from './merkle';
export { merkle };
export {
g<|fim_suffix|>from './timestamp';
<|fim_middle|>etClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Timestamp,
}
|
packages/crdt/src/crdt/index.ts
|
import * as merkle from './merkle';
export { merkle };
export {
getClock,
setClock,
makeClock,
makeClientId,
ser
|
ializeClock,
deserializeClock,
type Clock,
Timestamp,
} from './timestamp';
|
<|fim_prefix|>import * as merkle from './merkle';
export { merkle };
export {
getClock,
setClock,
makeClock,
makeClientId,
ser<|fim_suffix|><|fim_middle|>ializeClock,
deserializeClock,
type Clock,
Timestamp,
} from './timestamp';
|
packages/crdt/src/crdt/index.ts
|
|
im
|
Timestamp,
} from './timestamp';
|
port * as merkle from './merkle';
export { merkle };
export {
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
|
<|fim_prefix|>im<|fim_suffix|> Timestamp,
} from './timestamp';
<|fim_middle|>port * as merkle from './merkle';
export { merkle };
export {
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
|
packages/crdt/src/crdt/index.ts
|
import * as merkle from './merkle';
expo
|
lock,
Timestamp,
} from './timestamp';
|
rt { merkle };
export {
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type C
|
<|fim_prefix|>import * as merkle from './merkle';
expo<|fim_suffix|>lock,
Timestamp,
} from './timestamp';
<|fim_middle|>rt { merkle };
export {
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type C
|
packages/crdt/src/crdt/index.ts
|
import * as merkle from './merkle';
export { merkle
|
tamp,
} from './timestamp';
|
};
export {
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Times
|
<|fim_prefix|>import * as merkle from './merkle';
export { merkle <|fim_suffix|>tamp,
} from './timestamp';
<|fim_middle|>};
export {
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Times
|
packages/crdt/src/crdt/index.ts
|
im
|
estamp,
} from './timestamp';
|
port * as merkle from './merkle';
export { merkle };
export {
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Tim
|
<|fim_prefix|>im<|fim_suffix|>estamp,
} from './timestamp';
<|fim_middle|>port * as merkle from './merkle';
export { merkle };
export {
getClock,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeClock,
type Clock,
Tim
|
packages/crdt/src/crdt/index.ts
|
import * as merkle
|
rializeClock,
deserializeClock,
type Clock,
Timestamp,
} from './timestamp';
|
from './merkle';
export { merkle };
export {
getClock,
setClock,
makeClock,
makeClientId,
se
|
<|fim_prefix|>import * as merkle<|fim_suffix|>rializeClock,
deserializeClock,
type Clock,
Timestamp,
} from './timestamp';
<|fim_middle|> from './merkle';
export { merkle };
export {
getClock,
setClock,
makeClock,
makeClientId,
se
|
packages/crdt/src/crdt/index.ts
|
import * as merkle from './merkle';
export { merkle };
export {
getClo
|
k,
type Clock,
Timestamp,
} from './timestamp';
|
ck,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeCloc
|
<|fim_prefix|>import * as merkle from './merkle';
export { merkle };
export {
getClo<|fim_suffix|>k,
type Clock,
Timestamp,
} from './timestamp';
<|fim_middle|>ck,
setClock,
makeClock,
makeClientId,
serializeClock,
deserializeCloc
|
packages/crdt/src/crdt/index.ts
|
// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
}
|
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun
|
);
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
|
<|fim_prefix|>// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
}<|fim_suffix|>
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun<|fim_middle|>);
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
|
packages/crdt/src/crdt/merkle.ts
|
// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
|
le passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun
|
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multip
|
<|fim_prefix|>// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
<|fim_suffix|>le passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun<|fim_middle|>// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multip
|
packages/crdt/src/crdt/merkle.ts
|
// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make s
|
amp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun
|
ure if account exists when handling
// * transaction changes in syncing
import { Timest
|
<|fim_prefix|>// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make s<|fim_suffix|>amp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun<|fim_middle|>ure if account exists when handling
// * transaction changes in syncing
import { Timest
|
packages/crdt/src/crdt/merkle.ts
|
// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full val
|
time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun
|
ue
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed
|
<|fim_prefix|>// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full val<|fim_suffix|> time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun<|fim_middle|>ue
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed
|
packages/crdt/src/crdt/merkle.ts
|
// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead
|
y(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun
|
the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKe
|
<|fim_prefix|>// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead<|fim_suffix|>y(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun<|fim_middle|> the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKe
|
packages/crdt/src/crdt/merkle.ts
|
// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0
|
is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun
|
'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input
|
<|fim_prefix|>// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0<|fim_suffix|> is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun<|fim_middle|>'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input
|
packages/crdt/src/crdt/merkle.ts
|
// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "p
|
of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun
|
artial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because
|
<|fim_prefix|>// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "p<|fim_suffix|>of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun<|fim_middle|>artial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because
|
packages/crdt/src/crdt/merkle.ts
|
// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.
|
ll;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun
|
hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return nu
|
<|fim_prefix|>// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.<|fim_suffix|>ll;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun<|fim_middle|>hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return nu
|
packages/crdt/src/crdt/merkle.ts
|
// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: Tr
|
ull;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun
|
ieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = n
|
<|fim_prefix|>// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: Tr<|fim_suffix|>ull;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's possible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun<|fim_middle|>ieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = n
|
packages/crdt/src/crdt/merkle.ts
|
// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes
|
ssible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun
|
doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's po
|
<|fim_prefix|>// TODO: Ok, several problems:
//
// * If nothing matches between two merkle trees, we should fallback
// * to the last window instead the front one (use 0 instead of the
// * key)
//
// * Need to check to make sure if account exists when handling
// * transaction changes in syncing
import { Timestamp } from './timestamp';
/**
* Represents a node within a trinary radix trie.
*/
export type TrieNode = {
'0'?: TrieNode;
'1'?: TrieNode;
'2'?: TrieNode;
hash?: number;
};
type NumberTrieNodeKey = keyof Omit<TrieNode, 'hash'>;
export function emptyTrie(): TrieNode {
return { hash: 0 };
}
function isNumberTrieNodeKey(input: string): input is NumberTrieNodeKey {
return ['0', '1', '2'].includes(input);
}
export function getKeys(trie: TrieNode): NumberTrieNodeKey[] {
return Object.keys(trie).filter(isNumberTrieNodeKey);
}
export function keyToTimestamp(key: string): number {
// 16 is the length of the base 3 value of the current time in
// minutes. Ensure it's padded to create the full value
const fullkey = key + '0'.repeat(16 - key.length);
// Parse the base 3 representation
return parseInt(fullkey, 3) * 1000 * 60;
}
/**
* Mutates `trie` to insert a node at `timestamp`
*/
export function insert(trie: TrieNode, timestamp: Timestamp) {
const hash = timestamp.hash();
const key = Number(Math.floor(timestamp.millis() / 1000 / 60)).toString(3);
trie = Object.assign({}, trie, { hash: (trie.hash || 0) ^ hash });
return insertKey(trie, key, hash);
}
function insertKey(trie: TrieNode, key: string, hash: number): TrieNode {
if (key.length === 0) {
return trie;
}
const c = key[0];
const t = isNumberTrieNodeKey(c) ? trie[c] : undefined;
const n = t || {};
return Object.assign({}, trie, {
[c]: Object.assign({}, n, insertKey(n, key.slice(1), hash), {
hash: (n.hash || 0) ^ hash,
}),
});
}
export function build(timestamps: Timestamp[]) {
const trie = emptyTrie();
for (const timestamp of timestamps) {
insert(trie, timestamp);
}
return trie;
}
export function diff(trie1: TrieNode, trie2: TrieNode): number | null {
if (trie1.hash === trie2.hash) {
return null;
}
let node1 = trie1;
let node2 = trie2;
let k = '';
// This loop will eventually stop when it traverses down to find
// where the hashes differ, or otherwise when there are no leaves
// left (this shouldn't happen, if that's the case the hash check at
// the top of this function should pass)
while (1) {
const keyset = new Set([...getKeys(node1), ...getKeys(node2)]);
const keys = [...keyset.values()];
keys.sort();
let diffkey: null | '0' | '1' | '2' = null;
// Traverse down the trie through keys that aren't the same. We
// traverse down the keys in order. Stop in two cases: either one
// of the nodes <|fim_suffix|>ssible we will
// generate a time that only encompasses *some* of the those
// messages. Pruning is lossy, and we traverse down the left-most
// changed time that we know of, because of pruning it might take
// multiple passes to sync up a trie.
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const next1 = node1[key];
const next2 = node2[key];
if (!next1 || !next2) {
break;
}
if (next1.hash !== next2.hash) {
diffkey = key;
break;
}
}
if (!diffkey) {
return keyToTimestamp(k);
}
k += diffkey;
node1 = node1[diffkey] || emptyTrie();
node2 = node2[diffkey] || emptyTrie();
}
// eslint-disable-next-line no-unreachable
return null;
}
export function prune(trie: TrieNode, n = 2): TrieNode {
// Do nothing if empty
if (!trie.hash) {
return trie;
}
const keys = getKeys(trie);
keys.sort();
const next: TrieNode = { hash: trie.hash };
// Prune child nodes.
for (const k of keys.slice(-n)) {
const node = trie[k];
if (!node) {
throw new Error(`TrieNode for key ${k} could not be foun<|fim_middle|>doesn't have the key, or a different key isn't
// found. For the former case, we have to that because pruning is
// lossy. We don't know if we've pruned off a changed key so we
// can't traverse down anymore. For the latter case, it means two
// things: either we've hit the bottom of the tree, or the changed
// key has been pruned off. In the latter case we have a "partial"
// key and will fill the rest with 0s. Note that if multiple older
// messages were added into one trie, it's po
|
packages/crdt/src/crdt/merkle.ts
|
import murmurhash from 'murmurhash';
import { v4 as uuidv4 } from 'uuid';
import { TrieNode } from './merkle';
/**
* Hybrid Unique Logical Clock (HULC) timestamp generator
*
* Globally-unique, monotonic timestamps are generated from the
* combination of the unreliable system time, a counter, and an
* identifier for the current node (instance, machine, process, etc.).
* These timestamps can accommodate clock stuttering (duplicate values),
* regression, and node differences within the configured maximum drift.
*
* In order to generate timestamps locally or for transmission to another
* node, use the send() method. For global causality, timestamps must
* be included in each message processed by the system. Whenever a
* message is received, its timestamp must be passed to the recv()
* method.
*
* Timestamps serialize into a 46-character collatable string
* example: 2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF
* example: 2015-04-24T22:23:42.123Z-1000-A219E7A71CC18912
*
* The 64-bit hybrid clock is based on the HLC specification,
* http://www.cse.buffalo.edu/tech-reports/2014-04.pdf
*/
export type Clock = {
timestamp: MutableTimestamp;
merkle: TrieNode;
};
// A mutable global clock
let clock: Clock;
export function setClock(clock_: Clock): void {
clock = clock_;
}
export function getClock(): Clock {
return clock;
}
export function makeClock(timestamp: Timestamp, merkle: TrieNode = {}) {
return { timestamp: MutableTimestamp.from(timestamp), merkle };
}
export function serializeClock(clock: Clock): string {
return JSON.stringify({
timestamp: clock.timestamp.toString(),
merkle: clock.merkle,
});
}
export function deserializeClock(clock: string): Clock {
let data;
try {
data = JSON.parse(clock);
} catch (e) {
data = {
timestamp: '1970-01-01T00:00:00.000Z-0000-' + makeClientId(),
merkle: {},
};
}
const ts = Timestamp.parse(data.timestamp);
if (!ts) {
throw new Timestamp.InvalidError(data.timestamp);
}
return {
timestamp: MutableTimestamp.from(ts),
merkle: data.merkle,
};
}
export function makeClientId() {
return uuidv4().replace(/-/g, '').slice(-16);
}
const config = {
// Allow 5 minutes of clock drift
maxDrift: 5 * 60 * 1000,
};
const MAX_COUNTER = parseInt('0xFFFF');
const MAX_NODE_LENGTH = 16;
/**
* timestamp instance class
*/
export class Timestamp {
_state: { millis: number; counter: number; node: string };
constructor(millis: number, counter: number, node: string) {
this._state = {
millis,
counter,
node,
};
}
valueOf() {
return this.toString();
}
toString() {
return [
new Date(this.millis()).toISOString(),
('0000' + this.counter().toString(16).toUpperCase()).slice(-4),
('0000000000000000' + this.node()).slice(-16),
].join('-');
}
millis() {
return this._state.millis;
}
counter() {
return this._state.counter;
}
node() {
return this._state.node;
}
hash() {
return murmurhash.v3(this.toString());
}
// Timestamp generator initialization
// * sets the node ID to an arbitrary value
// * useful for mocking/unit testing
static init(options: { maxDrift?: number; node?: string } = {}) {
if (options.maxDrift) {
config.maxDrift = options.
|
),
),
);
}
/**
* maximum timestamp
*/
static max = Timestamp.parse(
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
)!;
/**
* timestamp parsing
* converts a fixed-length string timestamp to the structured value
*/
static parse(timestamp: string | Timestamp): Timestamp | null {
if (timestamp instanceof Timestamp) {
return timestamp;
}
if (typeof timestamp === 'string') {
const parts = timestamp.split('-');
if (parts && parts.length === 5) {
const millis = Date.parse(parts.slice(0, 3).join('-')).valueOf();
const counter = parseInt(parts[3], 16);
const node = parts[4];
if (
!isNaN(millis) &&
millis >= 0 &&
!isNaN(counter) &&
counter <= MAX_COUNTER &&
typeof node === 'string' &&
node.length <= MAX_NODE_LENGTH
) {
return new Timestamp
|
maxDrift;
}
setClock(
makeClock(
new Timestamp(
0,
0,
options.node
? ('0000000000000000' + options.node).toString().slice(-16)
: '',
|
<|fim_prefix|>import murmurhash from 'murmurhash';
import { v4 as uuidv4 } from 'uuid';
import { TrieNode } from './merkle';
/**
* Hybrid Unique Logical Clock (HULC) timestamp generator
*
* Globally-unique, monotonic timestamps are generated from the
* combination of the unreliable system time, a counter, and an
* identifier for the current node (instance, machine, process, etc.).
* These timestamps can accommodate clock stuttering (duplicate values),
* regression, and node differences within the configured maximum drift.
*
* In order to generate timestamps locally or for transmission to another
* node, use the send() method. For global causality, timestamps must
* be included in each message processed by the system. Whenever a
* message is received, its timestamp must be passed to the recv()
* method.
*
* Timestamps serialize into a 46-character collatable string
* example: 2015-04-24T22:23:42.123Z-1000-0123456789ABCDEF
* example: 2015-04-24T22:23:42.123Z-1000-A219E7A71CC18912
*
* The 64-bit hybrid clock is based on the HLC specification,
* http://www.cse.buffalo.edu/tech-reports/2014-04.pdf
*/
export type Clock = {
timestamp: MutableTimestamp;
merkle: TrieNode;
};
// A mutable global clock
let clock: Clock;
export function setClock(clock_: Clock): void {
clock = clock_;
}
export function getClock(): Clock {
return clock;
}
export function makeClock(timestamp: Timestamp, merkle: TrieNode = {}) {
return { timestamp: MutableTimestamp.from(timestamp), merkle };
}
export function serializeClock(clock: Clock): string {
return JSON.stringify({
timestamp: clock.timestamp.toString(),
merkle: clock.merkle,
});
}
export function deserializeClock(clock: string): Clock {
let data;
try {
data = JSON.parse(clock);
} catch (e) {
data = {
timestamp: '1970-01-01T00:00:00.000Z-0000-' + makeClientId(),
merkle: {},
};
}
const ts = Timestamp.parse(data.timestamp);
if (!ts) {
throw new Timestamp.InvalidError(data.timestamp);
}
return {
timestamp: MutableTimestamp.from(ts),
merkle: data.merkle,
};
}
export function makeClientId() {
return uuidv4().replace(/-/g, '').slice(-16);
}
const config = {
// Allow 5 minutes of clock drift
maxDrift: 5 * 60 * 1000,
};
const MAX_COUNTER = parseInt('0xFFFF');
const MAX_NODE_LENGTH = 16;
/**
* timestamp instance class
*/
export class Timestamp {
_state: { millis: number; counter: number; node: string };
constructor(millis: number, counter: number, node: string) {
this._state = {
millis,
counter,
node,
};
}
valueOf() {
return this.toString();
}
toString() {
return [
new Date(this.millis()).toISOString(),
('0000' + this.counter().toString(16).toUpperCase()).slice(-4),
('0000000000000000' + this.node()).slice(-16),
].join('-');
}
millis() {
return this._state.millis;
}
counter() {
return this._state.counter;
}
node() {
return this._state.node;
}
hash() {
return murmurhash.v3(this.toString());
}
// Timestamp generator initialization
// * sets the node ID to an arbitrary value
// * useful for mocking/unit testing
static init(options: { maxDrift?: number; node?: string } = {}) {
if (options.maxDrift) {
config.maxDrift = options.<|fim_suffix|> ),
),
);
}
/**
* maximum timestamp
*/
static max = Timestamp.parse(
'9999-12-31T23:59:59.999Z-FFFF-FFFFFFFFFFFFFFFF',
)!;
/**
* timestamp parsing
* converts a fixed-length string timestamp to the structured value
*/
static parse(timestamp: string | Timestamp): Timestamp | null {
if (timestamp instanceof Timestamp) {
return timestamp;
}
if (typeof timestamp === 'string') {
const parts = timestamp.split('-');
if (parts && parts.length === 5) {
const millis = Date.parse(parts.slice(0, 3).join('-')).valueOf();
const counter = parseInt(parts[3], 16);
const node = parts[4];
if (
!isNaN(millis) &&
millis >= 0 &&
!isNaN(counter) &&
counter <= MAX_COUNTER &&
typeof node === 'string' &&
node.length <= MAX_NODE_LENGTH
) {
return new Timestamp<|fim_middle|>maxDrift;
}
setClock(
makeClock(
new Timestamp(
0,
0,
options.node
? ('0000000000000000' + options.node).toString().slice(-16)
: '',
|
packages/crdt/src/crdt/timestamp.ts
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.