prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
/**
* This module executes inside of electron's main process. You can start
* electron renderer process from here and communicate with the other processes
* through IPC.
*
* When running `npm run build` or `npm run build:main`, this file is compiled to
* `./src/main.js` using webpack. This gives us some performance wins.
*/
import path from 'path';
import { app, BrowserWindow, ipcMain, Menu, shell, Tray } from 'electron';
// import { autoUpdater } from 'electron-updater';
import logger from 'electron-log';
import { resolveHtmlPath } from './util';
import {
configureIpfs,
downloadIpfs,
ipfs,
ipfsDaemon,
ipfsIsInstalled,
ipfsIsRunning,
ipfsKill,
waitForIpfs,
} from './ipfs';
import {
configureFollower,
downloadFollower,
follower,
followerDaemon,
followerId,
followerIsInstalled,
followerKill,
followerPid,
} from './follower';
import { DAPPS, resolveDapp } from './dapps';
import { fetchPeers } from './peers';
import { SYNTHETIX_NODE_APP_CONFIG } from '../const';
import * as settings from './settings';
import http from 'http';
import { proxy } from './proxy';
logger.transports.file.level = 'info';
const isDebug =
process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';
// class AppUpdater {
// constructor() {
// log.transports.file.level = 'info';
// autoUpdater.logger = log;
// autoUpdater.checkForUpdatesAndNotify();
// }
// }
let tray: Tray | null = null;
let mainWindow: BrowserWindow | null = null;
if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support');
sourceMapSupport.install();
}
const RESOURCES_PATH = app.isPackaged
? path.join(process.resourcesPath, 'assets')
: path.join(__dirname, '../../assets');
const getAssetPath = (...paths: string[]): string => {
return path.join(RESOURCES_PATH, ...paths);
};
function updateContextMenu() {
const menu = generateMenuItems();
if (tray && !tray.isDestroyed()) {
tray.setContextMenu(
Menu.buildFromTemplate([
menu.app,
menu.autoStart,
menu.devTools,
menu.dock,
{ type: 'separator' },
...menu.dapps,
{ type: 'separator' },
menu.quit,
])
);
}
app.dock.setMenu(
Menu.buildFromTemplate([
menu.app,
menu.autoStart,
menu.devTools,
menu.tray,
{ type: 'separator' },
...menu.dapps,
])
);
}
function createWindow() {
mainWindow = new BrowserWindow({
show: true,
useContentSize: true,
center: true,
minWidth: 600,
minHeight: 470,
skipTaskbar: true,
fullscreen: false,
fullscreenable: false,
width: 600,
height: 470,
// frame: false,
icon: getAssetPath('icon.icns'),
webPreferences: {
preload: app.isPackaged
? path.join(__dirname, 'preload.js')
: path.join(__dirname, '../../.erb/dll/preload.js'),
},
});
if (isDebug) {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
mainWindow.loadURL(resolveHtmlPath('index.html'));
mainWindow.on('closed', () => {
mainWindow = null;
});
// Open urls in the user's browser
mainWindow.webContents.setWindowOpenHandler((edata) => {
shell.openExternal(edata.url);
return { action: 'deny' };
});
mainWindow.webContents.on('devtools-opened', updateContextMenu);
mainWindow.webContents.on('devtools-closed', updateContextMenu);
mainWindow.on('hide', updateContextMenu);
mainWindow.on('show', updateContextMenu);
// Remove this if your app does not use auto updates
// eslint-disable-next-line
// new AppUpdater();
}
function generateMenuItems() {
return {
app: {
label: mainWindow?.isVisible() ? 'Hide App' : 'Open App',
click: () => {
if (mainWindow?.isVisible()) {
mainWindow.hide();
if (mainWindow.webContents.isDevToolsOpened()) {
mainWindow.webContents.closeDevTools();
}
return;
}
if (!mainWindow) {
createWindow();
} else {
mainWindow.show();
}
updateContextMenu();
},
},
autoStart: {
label: app.getLoginItemSettings().openAtLogin
? 'Disable AutoStart'
: 'Enable AutoStart',
click: () => {
const settings = app.getLoginItemSettings();
settings.openAtLogin = !settings.openAtLogin;
app.setLoginItemSettings(settings);
updateContextMenu();
},
},
devTools: {
label:
mainWindow && mainWindow.webContents.isDevToolsOpened()
? 'Close DevTools'
: 'Open DevTools',
click: () => {
if (mainWindow) {
if (mainWindow.webContents.isDevToolsOpened()) {
mainWindow.webContents.closeDevTools();
} else {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
}
updateContextMenu();
},
},
dock: {
label: app.dock && app.dock.isVisible() ? 'Hide Dock' : 'Show Dock',
click: async () => {
if (app.dock) {
if (app.dock.isVisible()) {
await settings.set('dock', false);
app.dock.hide();
} else {
await settings.set('dock', true);
app.dock.show();
}
}
updateContextMenu();
},
},
tray: {
label: tray && !tray.isDestroyed() ? 'Hide Tray icon' : 'Show Tray icon',
click: async () => {
if (tray && !tray.isDestroyed()) {
await settings.set('tray', false);
tray.destroy();
} else {
await settings.set('tray', true);
createTray();
}
updateContextMenu();
},
},
separator: {
type: 'separator',
},
dapps: DAPPS.map((dapp) => {
return {
enabled: Boolean(dapp.url),
label: dapp.label,
click: () => shell.openExternal(`http://${dapp.id}.localhost:8888`),
};
}),
quit: {
label: 'Quit',
click: () => {
app.quit();
},
},
};
}
app.once('ready', async () => {
// Hide the app from the dock
if (app.dock && !(await settings.get('dock'))) {
app.dock.hide();
}
if (await settings.get('tray')) {
createTray();
}
updateContextMenu();
});
function createTray() {
// Create a Tray instance with the icon you want to use for the menu bar
tray = new Tray(getAssetPath('[email protected]'));
tray.on('mouse-down', (_event) => {
if (mainWindow?.isVisible()) {
mainWindow?.focus();
}
});
}
/**
* Add event listeners...
*/
app.on('window-all-closed', () => {
// Respect the OSX convention of having the application in memory even
// after all windows have been closed
if (process.platform !== 'darwin') {
app.quit();
}
});
app
.whenReady()
.then(() => {
createWindow();
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
})
.catch(logger.error);
ipcMain.handle('install-ipfs', downloadIpfs);
ipcMain.handle('install-follower', downloadFollower);
ipcMain.handle('ipfs-isInstalled', ipfsIsInstalled);
ipcMain.handle('follower-isInstalled', followerIsInstalled);
ipcMain.handle('ipfs-isRunning', ipfsIsRunning);
ipcMain.handle('follower-isRunning', followerPid);
ipcMain.handle('run-ipfs', async () => {
await configureIpfs();
await ipfsDaemon();
});
ipcMain.handle('run-follower', async () => {
await configureFollower();
await followerDaemon();
});
ipcMain.handle('ipfs-peers', () => ipfs('swarm peers'));
ipcMain.handle('ipfs-id', () => followerId());
ipcMain.handle('ipfs-repo-stat', () => ipfs('repo stat'));
ipcMain.handle('ipfs-stats-bw', () => ipfs('stats bw'));
ipcMain.handle('ipfs-follower-info', () => follower('synthetix info'));
app.on('will-quit', ipfsKill);
app.on('will-quit', followerKill);
downloadIpfs();
ipfsDaemon();
const ipfsCheck = setInterval(ipfsDaemon, 10_000);
app.on('will-quit', () => clearInterval(ipfsCheck));
downloadFollower();
followerDaemon();
const followerCheck = setInterval(followerDaemon, 10_000);
app.on('will-quit', () => clearInterval(followerCheck));
ipcMain.handle('dapps', async () => {
return DAPPS.map((dapp) => ({
...dapp,
url: dapp.url ? `http://${dapp.id}.localhost:8888` : null,
}));
});
ipcMain.handle('dapp', async (_event, id: string) => {
const dapp = DAPPS.find((dapp) => dapp.id === id);
return dapp && dapp.url ? `http://${dapp.id}.localhost:8888` : null;
});
async function resolveAllDapps() {
DAPPS.forEach( | (dapp) => resolveDapp(dapp).then(updateContextMenu)); |
}
const dappsResolver = setInterval(resolveAllDapps, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsResolver));
waitForIpfs().then(resolveAllDapps).catch(logger.error);
async function updateConfig() {
const config = JSON.parse(
await ipfs(`cat /ipns/${SYNTHETIX_NODE_APP_CONFIG}`)
);
logger.log('App config fetched', config);
if (config.dapps) {
const oldDapps = DAPPS.splice(0);
for (const dapp of config.dapps) {
const oldDapp = oldDapps.find((d) => d.id === dapp.id);
if (oldDapp) {
DAPPS.push(Object.assign({}, oldDapp, dapp));
} else {
DAPPS.push(dapp);
}
}
logger.log('Dapps updated', DAPPS);
await resolveAllDapps();
}
}
const dappsUpdater = setInterval(updateConfig, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsUpdater));
waitForIpfs().then(updateConfig).catch(logger.error);
ipcMain.handle('peers', async () => fetchPeers());
http
.createServer((req, res) => {
const id = `${req.headers.host}`.replace('.localhost:8888', '');
const dapp = DAPPS.find((dapp) => dapp.id === id);
if (dapp && dapp.url) {
req.headers.host = dapp.url;
proxy({ host: '127.0.0.1', port: 8080 }, req, res);
return;
}
res.writeHead(404);
res.end('Not found');
})
.listen(8888, '0.0.0.0');
| src/main/main.ts | Synthetixio-synthetix-node-6de6a58 | [
{
"filename": "src/main/dapps.ts",
"retrieved_chunk": " Object.assign(dapp, { url });\n logger.log(dapp.id, 'local IPFS host:', url);\n } catch (e) {\n logger.error(e);\n return;\n }\n}\nexport async function cleanupOldDapps() {\n const hashes = DAPPS.map((dapp) => dapp.qm);\n logger.log('Current DAPPs hashes', hashes);",
"score": 0.7740814089775085
},
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": " log(`Installing ipfs version ${latestVersionNumber}`);\n }\n const downloadUrl = `https://dist.ipfs.tech/go-ipfs/${latestVersion}/go-ipfs_${latestVersion}_darwin-${targetArch}.tar.gz`;\n log(`IPFS package: ${downloadUrl}`);\n await fs.rm(path.join(IPFS_PATH, 'config'), { recursive: true });\n await fs.mkdir(ROOT, { recursive: true });\n await new Promise((resolve, reject) => {\n const file = createWriteStream(path.join(ROOT, 'ipfs.tar.gz'));\n https.get(downloadUrl, (response) =>\n pipeline(response, file).then(resolve).catch(reject)",
"score": 0.697283923625946
},
{
"filename": "src/main/follower.ts",
"retrieved_chunk": " const file = createWriteStream(\n path.join(ROOT, 'ipfs-cluster-follow.tar.gz')\n );\n https.get(downloadUrl, (response) =>\n pipeline(response, file).then(resolve).catch(reject)\n );\n });\n await new Promise((resolve, reject) => {\n createReadStream(path.join(ROOT, 'ipfs-cluster-follow.tar.gz'))\n .pipe(zlib.createGunzip())",
"score": 0.6830075979232788
},
{
"filename": "src/main/dapps.ts",
"retrieved_chunk": " return;\n }\n const isDappPinned = await isPinned(qm);\n if (!isDappPinned) {\n logger.log(dapp.id, 'pinning...', qm);\n await ipfs(`pin add --progress ${qm}`);\n }\n const bafy = await convertCid(qm);\n Object.assign(dapp, { bafy });\n const url = `${bafy}.ipfs.localhost`;",
"score": 0.6723223924636841
},
{
"filename": "src/main/util.ts",
"retrieved_chunk": "import { URL } from 'url';\nimport path from 'path';\nexport function resolveHtmlPath(htmlFileName: string) {\n if (process.env.NODE_ENV === 'development') {\n const port = process.env.PORT || 1212;\n const url = new URL(`http://localhost:${port}`);\n url.pathname = htmlFileName;\n return url.href;\n }\n return `file://${path.resolve(__dirname, '../renderer/', htmlFileName)}`;",
"score": 0.6692453622817993
}
] | typescript | (dapp) => resolveDapp(dapp).then(updateContextMenu)); |
import logger from 'electron-log';
import fetch from 'node-fetch';
import { createPublicClient, http } from 'viem';
import { mainnet } from 'viem/chains';
import { namehash, normalize } from 'viem/ens';
// @ts-ignore
import * as contentHash from '@ensdomains/content-hash';
import { ipfs } from './ipfs';
import { getPid } from './pid';
import { DappType } from '../config';
Object.assign(global, { fetch });
export const DAPPS: DappType[] = [];
const client = createPublicClient({
chain: mainnet,
transport: http(),
});
const resolverAbi = [
{
constant: true,
inputs: [{ internalType: 'bytes32', name: 'node', type: 'bytes32' }],
name: 'contenthash',
outputs: [{ internalType: 'bytes', name: '', type: 'bytes' }],
payable: false,
stateMutability: 'view',
type: 'function',
},
];
export async function resolveEns(
dapp: DappType
): Promise<{ codec: string; hash: string }> {
if (dapp.ipns) {
return {
codec: 'ipns-ns',
hash: dapp.ipns,
};
}
if (!dapp.ens) {
throw new Error('Neither ipns nor ens was set, cannot resolve');
}
const name = normalize(dapp.ens);
const resolverAddress = await client.getEnsResolver({ name });
const hash = await client.readContract({
address: resolverAddress,
abi: resolverAbi,
functionName: 'contenthash',
args: [namehash(name)],
});
const codec = contentHash.getCodec(hash);
return {
codec,
hash: contentHash.decode(hash),
};
}
export async function resolveQm(ipns: string): Promise<string> {
const ipfsPath = await ipfs(`resolve /ipns/${ipns}`);
const qm = ipfsPath.slice(6); // remove /ipfs/
return qm; // Qm
}
export async function convertCid(qm: string): Promise<string> {
return await ipfs(`cid base32 ${qm}`);
}
export async function isPinned(qm: string): Promise<boolean> {
try {
const result = await ipfs(`pin ls --type recursive ${qm}`);
return result.includes(qm);
} catch (e) {
return false;
}
}
export async function resolveDapp(dapp: DappType): Promise<void> {
try {
const { codec, hash } = await resolveEns(dapp);
logger.log(dapp.id, 'resolved', codec, hash);
const qm =
codec === 'ipns-ns'
? await resolveQm(hash)
: codec === 'ipfs-ns'
? hash
: undefined;
if (qm) {
Object.assign(dapp, { qm });
}
if (qm !== hash) {
logger.log(dapp.id, 'resolved CID', qm);
}
if (!qm) {
throw new Error(`Codec "${codec}" not supported`);
}
| if (await getPid(`pin add --progress ${qm}`)) { |
logger.log(dapp.id, 'pinning already in progres...');
return;
}
const isDappPinned = await isPinned(qm);
if (!isDappPinned) {
logger.log(dapp.id, 'pinning...', qm);
await ipfs(`pin add --progress ${qm}`);
}
const bafy = await convertCid(qm);
Object.assign(dapp, { bafy });
const url = `${bafy}.ipfs.localhost`;
Object.assign(dapp, { url });
logger.log(dapp.id, 'local IPFS host:', url);
} catch (e) {
logger.error(e);
return;
}
}
export async function cleanupOldDapps() {
const hashes = DAPPS.map((dapp) => dapp.qm);
logger.log('Current DAPPs hashes', hashes);
if (hashes.length < 1 || hashes.some((hash) => !hash)) {
// We only want to cleanup when all the dapps aer resolved
return;
}
try {
const pins = JSON.parse(await ipfs('pin ls --enc=json --type=recursive'));
const pinnedHashes = Object.keys(pins.Keys);
logger.log('Existing IPFS pins', pinnedHashes);
const toUnpin = pinnedHashes.filter((hash) => !hashes.includes(hash));
logger.log('Hashes to unpin', toUnpin);
if (toUnpin.length > 0) {
for (const hash of toUnpin) {
logger.log(`Unpinning ${hash}`);
await ipfs(`pin rm ${hash}`);
}
const pinsAfter = JSON.parse(
await ipfs('pin ls --enc=json --type=recursive')
);
logger.log('Updated IPFS pins', pinsAfter);
// Clenup the repo
await ipfs('repo gc');
}
} catch (e) {
// do nothing
}
}
| src/main/dapps.ts | Synthetixio-synthetix-node-6de6a58 | [
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": " return new Promise((resolve, reject) => {\n exec(\n `${path.join(ROOT, 'go-ipfs/ipfs')} ${arg}`,\n { encoding: 'utf8', env: { IPFS_PATH } },\n (error, stdout, stderr) => {\n if (error) {\n error.message = `${error.message} (${stderr})`;\n reject(error);\n } else {\n resolve(stdout.trim());",
"score": 0.7362293004989624
},
{
"filename": "src/main/main.ts",
"retrieved_chunk": "ipcMain.handle('peers', async () => fetchPeers());\nhttp\n .createServer((req, res) => {\n const id = `${req.headers.host}`.replace('.localhost:8888', '');\n const dapp = DAPPS.find((dapp) => dapp.id === id);\n if (dapp && dapp.url) {\n req.headers.host = dapp.url;\n proxy({ host: '127.0.0.1', port: 8080 }, req, res);\n return;\n }",
"score": 0.7319079637527466
},
{
"filename": "src/renderer/DApps/useDapp.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nconst { ipcRenderer } = window?.electron || {};\nexport function useDapp(id: string) {\n return useQuery({\n queryKey: ['dapp', id],\n queryFn: async () => {\n const url = await ipcRenderer.invoke('dapp', id);\n if (!url) {\n return null;\n }",
"score": 0.7308294177055359
},
{
"filename": "src/main/follower.ts",
"retrieved_chunk": " .pipe(tar.extract({ cwd: ROOT }))\n .on('error', reject)\n .on('end', resolve);\n });\n const installedVersionCheck = await getInstalledVersion();\n if (installedVersionCheck) {\n log(\n `ipfs-cluster-follow version ${installedVersionCheck} installed successfully.`\n );\n } else {",
"score": 0.7238132357597351
},
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": " const installedVersion = await getInstalledVersion();\n if (installedVersion === latestVersionNumber) {\n log(`ipfs version ${installedVersion} is already installed.`);\n return;\n }\n if (installedVersion) {\n log(\n `Updating ipfs from version ${installedVersion} to ${latestVersionNumber}`\n );\n } else {",
"score": 0.7205690145492554
}
] | typescript | if (await getPid(`pin add --progress ${qm}`)) { |
import {
Box,
Code,
Drawer,
DrawerBody,
DrawerCloseButton,
DrawerContent,
DrawerHeader,
DrawerOverlay,
Heading,
Icon,
IconButton,
Spinner,
Stack,
Stat,
StatLabel,
StatNumber,
Text,
Tooltip,
} from '@chakra-ui/react';
import { ArrowRightIcon, CheckIcon, CopyIcon } from '@chakra-ui/icons';
import { usePeerId } from './usePeerId';
import { usePeers } from './usePeers';
import { useRateIn } from './useRateIn';
import { useRateOut } from './useRateOut';
import { useHostingSize } from './useHostingSize';
import { useIsIpfsRunning } from './useIsIpfsRunning';
import { useIsIpfsInstalled } from './useIsIpfsInstalled';
import { useIsFollowerInstalled } from './useIsFollowerInstalled';
import { useFollowerInfo } from './useFollowerInfo';
import { SYNTHETIX_IPNS } from '../../const';
import React from 'react';
function handleCopy(text: string) {
if (text) {
navigator.clipboard.writeText(text);
}
}
function StatusIcon(props: any) {
return (
<Box display="inline-block" mr="1" transform="translateY(-1px)" {...props}>
<Icon viewBox="0 0 200 200">
<path
fill="currentColor"
d="M 100, 100 m -75, 0 a 75,75 0 1,0 150,0 a 75,75 0 1,0 -150,0"
/>
</Icon>
</Box>
);
}
export function Ipfs() {
const { data: isIpfsInstalled } = useIsIpfsInstalled();
const { data: isIpfsRunning } = useIsIpfsRunning();
const { data: isFollowerInstalled } = useIsFollowerInstalled();
const { data: peers } = usePeers();
| const { data: peerId } = usePeerId(); |
const { data: followerInfo } = useFollowerInfo();
const rateIn = useRateIn();
const rateOut = useRateOut();
const hostingSize = useHostingSize();
// eslint-disable-next-line no-console
console.log({
isIpfsInstalled,
isIpfsRunning,
isFollowerInstalled,
isFollowerRunning: followerInfo.cluster,
peers,
peerId,
rateIn,
rateOut,
hostingSize,
});
const [peersOpened, setPeersOpened] = React.useState(false);
return (
<Box pt="3">
<Box flex="1" p="0" whiteSpace="nowrap">
<Stack direction="row" spacing={6} justifyContent="center" mb="2">
<Stat>
<StatLabel mb="0" opacity="0.8">
Hosting
</StatLabel>
<StatNumber>
{hostingSize ? `${hostingSize.toFixed(2)} Mb` : '-'}
</StatNumber>
</Stat>
<Stat>
<StatLabel mb="0" opacity="0.8">
Outgoing
</StatLabel>
<StatNumber>{rateOut ? rateOut : '-'}</StatNumber>
</Stat>
<Stat>
<StatLabel mb="0" opacity="0.8">
Incoming
</StatLabel>
<StatNumber>{rateIn ? rateIn : '-'}</StatNumber>
</Stat>
<Stat cursor="pointer" onClick={() => setPeersOpened(true)}>
<StatLabel mb="0" opacity="0.8">
Cluster peers{' '}
<IconButton
aria-label="Open online peers"
size="xs"
icon={<ArrowRightIcon />}
onClick={() => setPeersOpened(true)}
/>
</StatLabel>
<StatNumber>
{peers ? peers.length : '-'}{' '}
<Drawer
isOpen={peersOpened}
placement="right"
onClose={() => setPeersOpened(false)}
>
<DrawerOverlay />
<DrawerContent maxWidth="26em">
<DrawerCloseButton />
<DrawerHeader>Online peers</DrawerHeader>
<DrawerBody>
<Stack direction="column" margin="0" overflow="scroll">
{peers.map((peer: { id: string }, i: number) => (
<Code
key={peer.id}
fontSize="10px"
display="block"
backgroundColor="transparent"
whiteSpace="nowrap"
>
{`${i}`.padStart(3, '0')}.{' '}
<Tooltip
hasArrow
placement="top"
openDelay={200}
fontSize="xs"
label={
peer.id === peerId
? 'Your connected Peer ID'
: 'Copy Peer ID'
}
>
<Text
as="span"
borderBottom="1px solid green.400"
borderBottomColor={
peer.id === peerId ? 'green.400' : 'transparent'
}
borderBottomStyle="solid"
borderBottomWidth="1px"
cursor="pointer"
onClick={() => handleCopy(peer.id)}
>
{peer.id}
</Text>
</Tooltip>{' '}
{peer.id === peerId ? (
<CheckIcon color="green.400" />
) : null}
</Code>
))}
</Stack>
</DrawerBody>
</DrawerContent>
</Drawer>
</StatNumber>
</Stat>
</Stack>
<Box bg="whiteAlpha.200" pt="4" px="4" pb="4" mb="3">
<Heading mb="3" size="sm">
{isIpfsInstalled && isIpfsRunning ? (
<Text as="span" whiteSpace="nowrap">
<StatusIcon textColor="green.400" />
<Text display="inline-block">Your IPFS node is running</Text>
</Text>
) : null}
{isIpfsInstalled && !isIpfsRunning ? (
<Text as="span" whiteSpace="nowrap">
<Spinner size="xs" mr="2" />
<Text display="inline-block">
Your IPFS node is starting...
</Text>
</Text>
) : null}
{!isIpfsInstalled ? (
<Text as="span" whiteSpace="nowrap">
<Spinner size="xs" mr="2" />
<Text display="inline-block">IPFS node is installing...</Text>
</Text>
) : null}
</Heading>
<Heading size="sm">
{isFollowerInstalled && followerInfo.cluster ? (
<Text as="span" whiteSpace="nowrap">
<StatusIcon textColor="green.400" />
<Text display="inline-block">
You are connected to the Synthetix Cluster
</Text>
</Text>
) : null}
{isFollowerInstalled && !followerInfo.cluster ? (
<Text as="span" whiteSpace="nowrap">
<Spinner size="xs" mr="2" />
<Text display="inline-block">
Connecting to the Synthetix Cluster...
</Text>
</Text>
) : null}
{!isFollowerInstalled ? (
<Text as="span" whiteSpace="nowrap">
<Spinner size="xs" mr="2" />
<Text display="inline-block">
Synthetix Cluster Connector is installing...
</Text>
</Text>
) : null}
</Heading>
</Box>
<Box mb="3">
<Text
fontSize="sm"
textTransform="uppercase"
letterSpacing="1px"
opacity="0.8"
mb="1"
>
Your Peer ID
</Text>
<Box display="flex" alignItems="center">
<Code>
{peerId ? peerId : 'CONNECT YOUR IPFS NODE TO GENERATE A PEER ID'}
</Code>
{peerId && (
<CopyIcon
opacity="0.8"
ml="2"
cursor="pointer"
onClick={() => handleCopy(peerId)}
/>
)}
</Box>
</Box>
<Box>
<Text
fontSize="sm"
textTransform="uppercase"
letterSpacing="1px"
opacity="0.8"
mb="1"
>
Synthetix Cluster IPNS
</Text>
<Box display="flex" alignItems="center">
<Code fontSize="sm">{SYNTHETIX_IPNS}</Code>
{SYNTHETIX_IPNS && (
<CopyIcon
opacity="0.8"
ml="2"
cursor="pointer"
onClick={() => handleCopy(SYNTHETIX_IPNS)}
/>
)}
</Box>
</Box>
</Box>
</Box>
);
}
| src/renderer/Ipfs/Ipfs.tsx | Synthetixio-synthetix-node-6de6a58 | [
{
"filename": "src/renderer/Ipfs/usePeers.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsIpfsRunning } from './useIsIpfsRunning';\nconst { ipcRenderer } = window?.electron || {};\nexport function usePeers() {\n const { data: isRunning } = useIsIpfsRunning();\n return useQuery({\n queryKey: ['ipfs', 'peers'],\n queryFn: async () => {\n const peers = await ipcRenderer.invoke('peers');\n if (!peers) {",
"score": 0.8661608695983887
},
{
"filename": "src/renderer/Ipfs/usePeerId.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsIpfsRunning } from './useIsIpfsRunning';\nconst { ipcRenderer } = window?.electron || {};\nexport function usePeerId() {\n const { data: isRunning } = useIsIpfsRunning();\n return useQuery({\n queryKey: ['ipfs', 'id'],\n queryFn: async () => {\n const id = await ipcRenderer.invoke('ipfs-id');\n if (!id) {",
"score": 0.8475598096847534
},
{
"filename": "src/renderer/Ipfs/useRepoStat.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsIpfsRunning } from './useIsIpfsRunning';\nconst { ipcRenderer } = window?.electron || {};\nexport function useRepoStat() {\n const { data: isRunning } = useIsIpfsRunning();\n return useQuery({\n queryKey: ['ipfs', 'repo stat'],\n queryFn: async () => {\n const stats = await ipcRenderer.invoke('ipfs-repo-stat');\n if (!stats) {",
"score": 0.8343315124511719
},
{
"filename": "src/renderer/Ipfs/useFollowerInfo.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsFollowerRunning } from './useIsFollowerRunning';\nconst { ipcRenderer } = window?.electron || {};\nexport function useFollowerInfo() {\n const { data: isRunning } = useIsFollowerRunning();\n return useQuery({\n queryKey: ['follower', 'info'],\n queryFn: async () => {\n const state = await ipcRenderer.invoke('ipfs-follower-info');\n return {",
"score": 0.8312802314758301
},
{
"filename": "src/renderer/Ipfs/useStatsBw.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsIpfsRunning } from './useIsIpfsRunning';\nconst { ipcRenderer } = window?.electron || {};\nexport function useStatsBw() {\n const { data: isRunning } = useIsIpfsRunning();\n return useQuery({\n queryKey: ['ipfs', 'stats bw'],\n queryFn: async () => {\n const stats = await ipcRenderer.invoke('ipfs-stats-bw');\n if (!stats) {",
"score": 0.8293823599815369
}
] | typescript | const { data: peerId } = usePeerId(); |
import {
Box,
Code,
Drawer,
DrawerBody,
DrawerCloseButton,
DrawerContent,
DrawerHeader,
DrawerOverlay,
Heading,
Icon,
IconButton,
Spinner,
Stack,
Stat,
StatLabel,
StatNumber,
Text,
Tooltip,
} from '@chakra-ui/react';
import { ArrowRightIcon, CheckIcon, CopyIcon } from '@chakra-ui/icons';
import { usePeerId } from './usePeerId';
import { usePeers } from './usePeers';
import { useRateIn } from './useRateIn';
import { useRateOut } from './useRateOut';
import { useHostingSize } from './useHostingSize';
import { useIsIpfsRunning } from './useIsIpfsRunning';
import { useIsIpfsInstalled } from './useIsIpfsInstalled';
import { useIsFollowerInstalled } from './useIsFollowerInstalled';
import { useFollowerInfo } from './useFollowerInfo';
import { SYNTHETIX_IPNS } from '../../const';
import React from 'react';
function handleCopy(text: string) {
if (text) {
navigator.clipboard.writeText(text);
}
}
function StatusIcon(props: any) {
return (
<Box display="inline-block" mr="1" transform="translateY(-1px)" {...props}>
<Icon viewBox="0 0 200 200">
<path
fill="currentColor"
d="M 100, 100 m -75, 0 a 75,75 0 1,0 150,0 a 75,75 0 1,0 -150,0"
/>
</Icon>
</Box>
);
}
export function Ipfs() {
const { data: isIpfsInstalled } = useIsIpfsInstalled();
const { data: isIpfsRunning } = useIsIpfsRunning();
const { data: isFollowerInstalled } = useIsFollowerInstalled();
| const { data: peers } = usePeers(); |
const { data: peerId } = usePeerId();
const { data: followerInfo } = useFollowerInfo();
const rateIn = useRateIn();
const rateOut = useRateOut();
const hostingSize = useHostingSize();
// eslint-disable-next-line no-console
console.log({
isIpfsInstalled,
isIpfsRunning,
isFollowerInstalled,
isFollowerRunning: followerInfo.cluster,
peers,
peerId,
rateIn,
rateOut,
hostingSize,
});
const [peersOpened, setPeersOpened] = React.useState(false);
return (
<Box pt="3">
<Box flex="1" p="0" whiteSpace="nowrap">
<Stack direction="row" spacing={6} justifyContent="center" mb="2">
<Stat>
<StatLabel mb="0" opacity="0.8">
Hosting
</StatLabel>
<StatNumber>
{hostingSize ? `${hostingSize.toFixed(2)} Mb` : '-'}
</StatNumber>
</Stat>
<Stat>
<StatLabel mb="0" opacity="0.8">
Outgoing
</StatLabel>
<StatNumber>{rateOut ? rateOut : '-'}</StatNumber>
</Stat>
<Stat>
<StatLabel mb="0" opacity="0.8">
Incoming
</StatLabel>
<StatNumber>{rateIn ? rateIn : '-'}</StatNumber>
</Stat>
<Stat cursor="pointer" onClick={() => setPeersOpened(true)}>
<StatLabel mb="0" opacity="0.8">
Cluster peers{' '}
<IconButton
aria-label="Open online peers"
size="xs"
icon={<ArrowRightIcon />}
onClick={() => setPeersOpened(true)}
/>
</StatLabel>
<StatNumber>
{peers ? peers.length : '-'}{' '}
<Drawer
isOpen={peersOpened}
placement="right"
onClose={() => setPeersOpened(false)}
>
<DrawerOverlay />
<DrawerContent maxWidth="26em">
<DrawerCloseButton />
<DrawerHeader>Online peers</DrawerHeader>
<DrawerBody>
<Stack direction="column" margin="0" overflow="scroll">
{peers.map((peer: { id: string }, i: number) => (
<Code
key={peer.id}
fontSize="10px"
display="block"
backgroundColor="transparent"
whiteSpace="nowrap"
>
{`${i}`.padStart(3, '0')}.{' '}
<Tooltip
hasArrow
placement="top"
openDelay={200}
fontSize="xs"
label={
peer.id === peerId
? 'Your connected Peer ID'
: 'Copy Peer ID'
}
>
<Text
as="span"
borderBottom="1px solid green.400"
borderBottomColor={
peer.id === peerId ? 'green.400' : 'transparent'
}
borderBottomStyle="solid"
borderBottomWidth="1px"
cursor="pointer"
onClick={() => handleCopy(peer.id)}
>
{peer.id}
</Text>
</Tooltip>{' '}
{peer.id === peerId ? (
<CheckIcon color="green.400" />
) : null}
</Code>
))}
</Stack>
</DrawerBody>
</DrawerContent>
</Drawer>
</StatNumber>
</Stat>
</Stack>
<Box bg="whiteAlpha.200" pt="4" px="4" pb="4" mb="3">
<Heading mb="3" size="sm">
{isIpfsInstalled && isIpfsRunning ? (
<Text as="span" whiteSpace="nowrap">
<StatusIcon textColor="green.400" />
<Text display="inline-block">Your IPFS node is running</Text>
</Text>
) : null}
{isIpfsInstalled && !isIpfsRunning ? (
<Text as="span" whiteSpace="nowrap">
<Spinner size="xs" mr="2" />
<Text display="inline-block">
Your IPFS node is starting...
</Text>
</Text>
) : null}
{!isIpfsInstalled ? (
<Text as="span" whiteSpace="nowrap">
<Spinner size="xs" mr="2" />
<Text display="inline-block">IPFS node is installing...</Text>
</Text>
) : null}
</Heading>
<Heading size="sm">
{isFollowerInstalled && followerInfo.cluster ? (
<Text as="span" whiteSpace="nowrap">
<StatusIcon textColor="green.400" />
<Text display="inline-block">
You are connected to the Synthetix Cluster
</Text>
</Text>
) : null}
{isFollowerInstalled && !followerInfo.cluster ? (
<Text as="span" whiteSpace="nowrap">
<Spinner size="xs" mr="2" />
<Text display="inline-block">
Connecting to the Synthetix Cluster...
</Text>
</Text>
) : null}
{!isFollowerInstalled ? (
<Text as="span" whiteSpace="nowrap">
<Spinner size="xs" mr="2" />
<Text display="inline-block">
Synthetix Cluster Connector is installing...
</Text>
</Text>
) : null}
</Heading>
</Box>
<Box mb="3">
<Text
fontSize="sm"
textTransform="uppercase"
letterSpacing="1px"
opacity="0.8"
mb="1"
>
Your Peer ID
</Text>
<Box display="flex" alignItems="center">
<Code>
{peerId ? peerId : 'CONNECT YOUR IPFS NODE TO GENERATE A PEER ID'}
</Code>
{peerId && (
<CopyIcon
opacity="0.8"
ml="2"
cursor="pointer"
onClick={() => handleCopy(peerId)}
/>
)}
</Box>
</Box>
<Box>
<Text
fontSize="sm"
textTransform="uppercase"
letterSpacing="1px"
opacity="0.8"
mb="1"
>
Synthetix Cluster IPNS
</Text>
<Box display="flex" alignItems="center">
<Code fontSize="sm">{SYNTHETIX_IPNS}</Code>
{SYNTHETIX_IPNS && (
<CopyIcon
opacity="0.8"
ml="2"
cursor="pointer"
onClick={() => handleCopy(SYNTHETIX_IPNS)}
/>
)}
</Box>
</Box>
</Box>
</Box>
);
}
| src/renderer/Ipfs/Ipfs.tsx | Synthetixio-synthetix-node-6de6a58 | [
{
"filename": "src/renderer/Ipfs/usePeers.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsIpfsRunning } from './useIsIpfsRunning';\nconst { ipcRenderer } = window?.electron || {};\nexport function usePeers() {\n const { data: isRunning } = useIsIpfsRunning();\n return useQuery({\n queryKey: ['ipfs', 'peers'],\n queryFn: async () => {\n const peers = await ipcRenderer.invoke('peers');\n if (!peers) {",
"score": 0.8617295026779175
},
{
"filename": "src/renderer/Ipfs/usePeerId.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsIpfsRunning } from './useIsIpfsRunning';\nconst { ipcRenderer } = window?.electron || {};\nexport function usePeerId() {\n const { data: isRunning } = useIsIpfsRunning();\n return useQuery({\n queryKey: ['ipfs', 'id'],\n queryFn: async () => {\n const id = await ipcRenderer.invoke('ipfs-id');\n if (!id) {",
"score": 0.8426578640937805
},
{
"filename": "src/renderer/Ipfs/useRepoStat.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsIpfsRunning } from './useIsIpfsRunning';\nconst { ipcRenderer } = window?.electron || {};\nexport function useRepoStat() {\n const { data: isRunning } = useIsIpfsRunning();\n return useQuery({\n queryKey: ['ipfs', 'repo stat'],\n queryFn: async () => {\n const stats = await ipcRenderer.invoke('ipfs-repo-stat');\n if (!stats) {",
"score": 0.8388115763664246
},
{
"filename": "src/renderer/Ipfs/useIsIpfsRunning.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsIpfsInstalled } from './useIsIpfsInstalled';\nconst { ipcRenderer } = window?.electron || {};\nexport function useIsIpfsRunning() {\n const { data: isInstalled } = useIsIpfsInstalled();\n return useQuery({\n queryKey: ['ipfs', 'isRunning'],\n queryFn: () => ipcRenderer.invoke('ipfs-isRunning'),\n initialData: () => false,\n placeholderData: false,",
"score": 0.83655846118927
},
{
"filename": "src/renderer/Ipfs/useStatsBw.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsIpfsRunning } from './useIsIpfsRunning';\nconst { ipcRenderer } = window?.electron || {};\nexport function useStatsBw() {\n const { data: isRunning } = useIsIpfsRunning();\n return useQuery({\n queryKey: ['ipfs', 'stats bw'],\n queryFn: async () => {\n const stats = await ipcRenderer.invoke('ipfs-stats-bw');\n if (!stats) {",
"score": 0.8325710296630859
}
] | typescript | const { data: peers } = usePeers(); |
/**
* This module executes inside of electron's main process. You can start
* electron renderer process from here and communicate with the other processes
* through IPC.
*
* When running `npm run build` or `npm run build:main`, this file is compiled to
* `./src/main.js` using webpack. This gives us some performance wins.
*/
import path from 'path';
import { app, BrowserWindow, ipcMain, Menu, shell, Tray } from 'electron';
// import { autoUpdater } from 'electron-updater';
import logger from 'electron-log';
import { resolveHtmlPath } from './util';
import {
configureIpfs,
downloadIpfs,
ipfs,
ipfsDaemon,
ipfsIsInstalled,
ipfsIsRunning,
ipfsKill,
waitForIpfs,
} from './ipfs';
import {
configureFollower,
downloadFollower,
follower,
followerDaemon,
followerId,
followerIsInstalled,
followerKill,
followerPid,
} from './follower';
import { DAPPS, resolveDapp } from './dapps';
import { fetchPeers } from './peers';
import { SYNTHETIX_NODE_APP_CONFIG } from '../const';
import * as settings from './settings';
import http from 'http';
import { proxy } from './proxy';
logger.transports.file.level = 'info';
const isDebug =
process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';
// class AppUpdater {
// constructor() {
// log.transports.file.level = 'info';
// autoUpdater.logger = log;
// autoUpdater.checkForUpdatesAndNotify();
// }
// }
let tray: Tray | null = null;
let mainWindow: BrowserWindow | null = null;
if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support');
sourceMapSupport.install();
}
const RESOURCES_PATH = app.isPackaged
? path.join(process.resourcesPath, 'assets')
: path.join(__dirname, '../../assets');
const getAssetPath = (...paths: string[]): string => {
return path.join(RESOURCES_PATH, ...paths);
};
function updateContextMenu() {
const menu = generateMenuItems();
if (tray && !tray.isDestroyed()) {
tray.setContextMenu(
Menu.buildFromTemplate([
menu.app,
menu.autoStart,
menu.devTools,
menu.dock,
{ type: 'separator' },
...menu.dapps,
{ type: 'separator' },
menu.quit,
])
);
}
app.dock.setMenu(
Menu.buildFromTemplate([
menu.app,
menu.autoStart,
menu.devTools,
menu.tray,
{ type: 'separator' },
...menu.dapps,
])
);
}
function createWindow() {
mainWindow = new BrowserWindow({
show: true,
useContentSize: true,
center: true,
minWidth: 600,
minHeight: 470,
skipTaskbar: true,
fullscreen: false,
fullscreenable: false,
width: 600,
height: 470,
// frame: false,
icon: getAssetPath('icon.icns'),
webPreferences: {
preload: app.isPackaged
? path.join(__dirname, 'preload.js')
: path.join(__dirname, '../../.erb/dll/preload.js'),
},
});
if (isDebug) {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
mainWindow.loadURL(resolveHtmlPath('index.html'));
mainWindow.on('closed', () => {
mainWindow = null;
});
// Open urls in the user's browser
mainWindow.webContents.setWindowOpenHandler((edata) => {
shell.openExternal(edata.url);
return { action: 'deny' };
});
mainWindow.webContents.on('devtools-opened', updateContextMenu);
mainWindow.webContents.on('devtools-closed', updateContextMenu);
mainWindow.on('hide', updateContextMenu);
mainWindow.on('show', updateContextMenu);
// Remove this if your app does not use auto updates
// eslint-disable-next-line
// new AppUpdater();
}
function generateMenuItems() {
return {
app: {
label: mainWindow?.isVisible() ? 'Hide App' : 'Open App',
click: () => {
if (mainWindow?.isVisible()) {
mainWindow.hide();
if (mainWindow.webContents.isDevToolsOpened()) {
mainWindow.webContents.closeDevTools();
}
return;
}
if (!mainWindow) {
createWindow();
} else {
mainWindow.show();
}
updateContextMenu();
},
},
autoStart: {
label: app.getLoginItemSettings().openAtLogin
? 'Disable AutoStart'
: 'Enable AutoStart',
click: () => {
const settings = app.getLoginItemSettings();
settings.openAtLogin = !settings.openAtLogin;
app.setLoginItemSettings(settings);
updateContextMenu();
},
},
devTools: {
label:
mainWindow && mainWindow.webContents.isDevToolsOpened()
? 'Close DevTools'
: 'Open DevTools',
click: () => {
if (mainWindow) {
if (mainWindow.webContents.isDevToolsOpened()) {
mainWindow.webContents.closeDevTools();
} else {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
}
updateContextMenu();
},
},
dock: {
label: app.dock && app.dock.isVisible() ? 'Hide Dock' : 'Show Dock',
click: async () => {
if (app.dock) {
if (app.dock.isVisible()) {
await settings.set('dock', false);
app.dock.hide();
} else {
await settings.set('dock', true);
app.dock.show();
}
}
updateContextMenu();
},
},
tray: {
label: tray && !tray.isDestroyed() ? 'Hide Tray icon' : 'Show Tray icon',
click: async () => {
if (tray && !tray.isDestroyed()) {
await settings.set('tray', false);
tray.destroy();
} else {
await settings.set('tray', true);
createTray();
}
updateContextMenu();
},
},
separator: {
type: 'separator',
},
dapps: DAPPS.map((dapp) => {
return {
enabled: Boolean(dapp.url),
label: dapp.label,
click: () => shell.openExternal(`http://${dapp.id}.localhost:8888`),
};
}),
quit: {
label: 'Quit',
click: () => {
app.quit();
},
},
};
}
app.once('ready', async () => {
// Hide the app from the dock
if (app.dock && !(await settings.get('dock'))) {
app.dock.hide();
}
if (await settings.get('tray')) {
createTray();
}
updateContextMenu();
});
function createTray() {
// Create a Tray instance with the icon you want to use for the menu bar
tray = new Tray(getAssetPath('[email protected]'));
tray.on('mouse-down', (_event) => {
if (mainWindow?.isVisible()) {
mainWindow?.focus();
}
});
}
/**
* Add event listeners...
*/
app.on('window-all-closed', () => {
// Respect the OSX convention of having the application in memory even
// after all windows have been closed
if (process.platform !== 'darwin') {
app.quit();
}
});
app
.whenReady()
.then(() => {
createWindow();
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
})
.catch(logger.error);
ipcMain.handle('install-ipfs', downloadIpfs);
ipcMain.handle('install-follower', downloadFollower);
ipcMain.handle('ipfs-isInstalled', ipfsIsInstalled);
ipcMain.handle('follower-isInstalled', followerIsInstalled);
ipcMain.handle('ipfs-isRunning', ipfsIsRunning);
ipcMain.handle('follower-isRunning', followerPid);
ipcMain.handle('run-ipfs', async () => {
await configureIpfs();
await ipfsDaemon();
});
ipcMain.handle('run-follower', async () => {
await configureFollower();
await followerDaemon();
});
ipcMain.handle('ipfs-peers', () => ipfs('swarm peers'));
ipcMain.handle('ipfs-id', () => followerId());
ipcMain.handle('ipfs-repo-stat', () => ipfs('repo stat'));
ipcMain.handle('ipfs-stats-bw', () => ipfs('stats bw'));
ipcMain.handle('ipfs-follower-info', () => follower('synthetix info'));
app.on('will-quit', ipfsKill);
app.on('will-quit', followerKill);
downloadIpfs();
ipfsDaemon();
const ipfsCheck = setInterval(ipfsDaemon, 10_000);
app.on('will-quit', () => clearInterval(ipfsCheck));
downloadFollower();
followerDaemon();
const followerCheck = setInterval(followerDaemon, 10_000);
app.on('will-quit', () => clearInterval(followerCheck));
ipcMain.handle('dapps', async () => {
return DAPPS.map((dapp) => ({
...dapp,
url: dapp.url ? `http://${dapp.id}.localhost:8888` : null,
}));
});
ipcMain.handle('dapp', async (_event, id: string) => {
const dapp = DAPPS.find((dapp) => dapp.id === id);
return dapp && dapp.url ? `http://${dapp.id}.localhost:8888` : null;
});
async function resolveAllDapps() {
DAPPS.forEach((dapp) => resolveDapp(dapp).then(updateContextMenu));
}
const dappsResolver = setInterval(resolveAllDapps, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsResolver));
waitForIpfs().then(resolveAllDapps).catch(logger.error);
async function updateConfig() {
const config = JSON.parse(
await ipfs(`cat /ipns/${SYNTHETIX_NODE_APP_CONFIG}`)
);
logger.log('App config fetched', config);
if (config.dapps) {
const oldDapps = DAPPS.splice(0);
for (const dapp of config.dapps) {
const oldDapp = oldDapps.find((d) => d.id === dapp.id);
if (oldDapp) {
DAPPS.push(Object.assign({}, oldDapp, dapp));
} else {
DAPPS.push(dapp);
}
}
logger.log('Dapps updated', DAPPS);
await resolveAllDapps();
}
}
const dappsUpdater = setInterval(updateConfig, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsUpdater));
waitForIpfs().then(updateConfig).catch(logger.error);
ipcMain.handle('peers' | , async () => fetchPeers()); |
http
.createServer((req, res) => {
const id = `${req.headers.host}`.replace('.localhost:8888', '');
const dapp = DAPPS.find((dapp) => dapp.id === id);
if (dapp && dapp.url) {
req.headers.host = dapp.url;
proxy({ host: '127.0.0.1', port: 8080 }, req, res);
return;
}
res.writeHead(404);
res.end('Not found');
})
.listen(8888, '0.0.0.0');
| src/main/main.ts | Synthetixio-synthetix-node-6de6a58 | [
{
"filename": "src/main/dapps.ts",
"retrieved_chunk": " Object.assign(dapp, { url });\n logger.log(dapp.id, 'local IPFS host:', url);\n } catch (e) {\n logger.error(e);\n return;\n }\n}\nexport async function cleanupOldDapps() {\n const hashes = DAPPS.map((dapp) => dapp.qm);\n logger.log('Current DAPPs hashes', hashes);",
"score": 0.7704514861106873
},
{
"filename": "src/scripts/ipfs-install.ts",
"retrieved_chunk": "import { downloadIpfs, ipfsDaemon, ipfsKill } from '../main/ipfs';\nasync function main() {\n await downloadIpfs();\n await ipfsDaemon();\n}\nprocess.on('beforeExit', ipfsKill);\nmain();",
"score": 0.7592798471450806
},
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": " log(`Installing ipfs version ${latestVersionNumber}`);\n }\n const downloadUrl = `https://dist.ipfs.tech/go-ipfs/${latestVersion}/go-ipfs_${latestVersion}_darwin-${targetArch}.tar.gz`;\n log(`IPFS package: ${downloadUrl}`);\n await fs.rm(path.join(IPFS_PATH, 'config'), { recursive: true });\n await fs.mkdir(ROOT, { recursive: true });\n await new Promise((resolve, reject) => {\n const file = createWriteStream(path.join(ROOT, 'ipfs.tar.gz'));\n https.get(downloadUrl, (response) =>\n pipeline(response, file).then(resolve).catch(reject)",
"score": 0.7193125486373901
},
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": "const IPFS_PATH = path.join(HOME, '.ipfs');\nexport function ipfsKill() {\n try {\n getPidsSync('.synthetix/go-ipfs/ipfs').forEach((pid) => {\n logger.log('Killing ipfs', pid);\n process.kill(pid);\n });\n logger.log('Removing .ipfs/repo.lock');\n rmSync(path.join(IPFS_PATH, 'repo.lock'), { recursive: true });\n } catch (_e) {",
"score": 0.7143276929855347
},
{
"filename": "src/scripts/follower-install.ts",
"retrieved_chunk": "import {\n downloadFollower,\n followerDaemon,\n followerKill,\n} from '../main/follower';\nasync function main() {\n await downloadFollower();\n await followerDaemon();\n}\nprocess.on('beforeExit', followerKill);",
"score": 0.7125990390777588
}
] | typescript | , async () => fetchPeers()); |
/**
* This module executes inside of electron's main process. You can start
* electron renderer process from here and communicate with the other processes
* through IPC.
*
* When running `npm run build` or `npm run build:main`, this file is compiled to
* `./src/main.js` using webpack. This gives us some performance wins.
*/
import path from 'path';
import { app, BrowserWindow, ipcMain, Menu, shell, Tray } from 'electron';
// import { autoUpdater } from 'electron-updater';
import logger from 'electron-log';
import { resolveHtmlPath } from './util';
import {
configureIpfs,
downloadIpfs,
ipfs,
ipfsDaemon,
ipfsIsInstalled,
ipfsIsRunning,
ipfsKill,
waitForIpfs,
} from './ipfs';
import {
configureFollower,
downloadFollower,
follower,
followerDaemon,
followerId,
followerIsInstalled,
followerKill,
followerPid,
} from './follower';
import { DAPPS, resolveDapp } from './dapps';
import { fetchPeers } from './peers';
import { SYNTHETIX_NODE_APP_CONFIG } from '../const';
import * as settings from './settings';
import http from 'http';
import { proxy } from './proxy';
logger.transports.file.level = 'info';
const isDebug =
process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';
// class AppUpdater {
// constructor() {
// log.transports.file.level = 'info';
// autoUpdater.logger = log;
// autoUpdater.checkForUpdatesAndNotify();
// }
// }
let tray: Tray | null = null;
let mainWindow: BrowserWindow | null = null;
if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support');
sourceMapSupport.install();
}
const RESOURCES_PATH = app.isPackaged
? path.join(process.resourcesPath, 'assets')
: path.join(__dirname, '../../assets');
const getAssetPath = (...paths: string[]): string => {
return path.join(RESOURCES_PATH, ...paths);
};
function updateContextMenu() {
const menu = generateMenuItems();
if (tray && !tray.isDestroyed()) {
tray.setContextMenu(
Menu.buildFromTemplate([
menu.app,
menu.autoStart,
menu.devTools,
menu.dock,
{ type: 'separator' },
...menu.dapps,
{ type: 'separator' },
menu.quit,
])
);
}
app.dock.setMenu(
Menu.buildFromTemplate([
menu.app,
menu.autoStart,
menu.devTools,
menu.tray,
{ type: 'separator' },
...menu.dapps,
])
);
}
function createWindow() {
mainWindow = new BrowserWindow({
show: true,
useContentSize: true,
center: true,
minWidth: 600,
minHeight: 470,
skipTaskbar: true,
fullscreen: false,
fullscreenable: false,
width: 600,
height: 470,
// frame: false,
icon: getAssetPath('icon.icns'),
webPreferences: {
preload: app.isPackaged
? path.join(__dirname, 'preload.js')
: path.join(__dirname, '../../.erb/dll/preload.js'),
},
});
if (isDebug) {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
mainWindow.loadURL(resolveHtmlPath('index.html'));
mainWindow.on('closed', () => {
mainWindow = null;
});
// Open urls in the user's browser
mainWindow.webContents.setWindowOpenHandler((edata) => {
shell.openExternal(edata.url);
return { action: 'deny' };
});
mainWindow.webContents.on('devtools-opened', updateContextMenu);
mainWindow.webContents.on('devtools-closed', updateContextMenu);
mainWindow.on('hide', updateContextMenu);
mainWindow.on('show', updateContextMenu);
// Remove this if your app does not use auto updates
// eslint-disable-next-line
// new AppUpdater();
}
function generateMenuItems() {
return {
app: {
label: mainWindow?.isVisible() ? 'Hide App' : 'Open App',
click: () => {
if (mainWindow?.isVisible()) {
mainWindow.hide();
if (mainWindow.webContents.isDevToolsOpened()) {
mainWindow.webContents.closeDevTools();
}
return;
}
if (!mainWindow) {
createWindow();
} else {
mainWindow.show();
}
updateContextMenu();
},
},
autoStart: {
label: app.getLoginItemSettings().openAtLogin
? 'Disable AutoStart'
: 'Enable AutoStart',
click: () => {
const settings = app.getLoginItemSettings();
settings.openAtLogin = !settings.openAtLogin;
app.setLoginItemSettings(settings);
updateContextMenu();
},
},
devTools: {
label:
mainWindow && mainWindow.webContents.isDevToolsOpened()
? 'Close DevTools'
: 'Open DevTools',
click: () => {
if (mainWindow) {
if (mainWindow.webContents.isDevToolsOpened()) {
mainWindow.webContents.closeDevTools();
} else {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
}
updateContextMenu();
},
},
dock: {
label: app.dock && app.dock.isVisible() ? 'Hide Dock' : 'Show Dock',
click: async () => {
if (app.dock) {
if (app.dock.isVisible()) {
await settings.set('dock', false);
app.dock.hide();
} else {
await settings.set('dock', true);
app.dock.show();
}
}
updateContextMenu();
},
},
tray: {
label: tray && !tray.isDestroyed() ? 'Hide Tray icon' : 'Show Tray icon',
click: async () => {
if (tray && !tray.isDestroyed()) {
await settings.set('tray', false);
tray.destroy();
} else {
await settings.set('tray', true);
createTray();
}
updateContextMenu();
},
},
separator: {
type: 'separator',
},
dapps: DAPPS.map((dapp) => {
return {
enabled: Boolean(dapp.url),
label: dapp.label,
click: () => shell.openExternal(`http://${dapp.id}.localhost:8888`),
};
}),
quit: {
label: 'Quit',
click: () => {
app.quit();
},
},
};
}
app.once('ready', async () => {
// Hide the app from the dock
if (app.dock && !(await settings.get('dock'))) {
app.dock.hide();
}
if (await settings.get('tray')) {
createTray();
}
updateContextMenu();
});
function createTray() {
// Create a Tray instance with the icon you want to use for the menu bar
tray = new Tray(getAssetPath('[email protected]'));
tray.on('mouse-down', (_event) => {
if (mainWindow?.isVisible()) {
mainWindow?.focus();
}
});
}
/**
* Add event listeners...
*/
app.on('window-all-closed', () => {
// Respect the OSX convention of having the application in memory even
// after all windows have been closed
if (process.platform !== 'darwin') {
app.quit();
}
});
app
.whenReady()
.then(() => {
createWindow();
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
})
.catch(logger.error);
ipcMain.handle('install-ipfs', downloadIpfs);
ipcMain.handle('install-follower', downloadFollower);
ipcMain.handle('ipfs-isInstalled', ipfsIsInstalled);
ipcMain.handle('follower-isInstalled', followerIsInstalled);
ipcMain.handle('ipfs-isRunning', ipfsIsRunning);
ipcMain.handle('follower-isRunning', followerPid);
ipcMain.handle('run-ipfs', async () => {
await configureIpfs();
await ipfsDaemon();
});
ipcMain.handle('run-follower', async () => {
await configureFollower();
await followerDaemon();
});
ipcMain.handle('ipfs-peers', () => ipfs('swarm peers'));
ipcMain.handle('ipfs-id', () => followerId());
ipcMain.handle('ipfs-repo-stat', () => ipfs('repo stat'));
ipcMain.handle('ipfs-stats-bw', () => ipfs('stats bw'));
ipcMain.handle('ipfs-follower-info', () => follower('synthetix info'));
app.on('will-quit', ipfsKill);
app.on('will-quit', followerKill);
downloadIpfs();
ipfsDaemon();
const ipfsCheck = setInterval(ipfsDaemon, 10_000);
app.on('will-quit', () => clearInterval(ipfsCheck));
downloadFollower();
followerDaemon();
const followerCheck = setInterval(followerDaemon, 10_000);
app.on('will-quit', () => clearInterval(followerCheck));
ipcMain.handle('dapps', async () => {
return DAPPS.map((dapp) => ({
...dapp,
url: dapp.url ? `http://${dapp.id}.localhost:8888` : null,
}));
});
ipcMain.handle('dapp', async (_event, id: string) => {
const dapp = DAPPS.find((dapp) => dapp.id === id);
return dapp && dapp.url ? `http://${dapp.id}.localhost:8888` : null;
});
async function resolveAllDapps() {
DAPPS.forEach((dapp) => resolveDapp(dapp).then(updateContextMenu));
}
const dappsResolver = setInterval(resolveAllDapps, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsResolver));
waitForIpfs().then(resolveAllDapps).catch(logger.error);
async function updateConfig() {
const config = JSON.parse(
await ipfs(`cat /ipns/${SYNTHETIX_NODE_APP_CONFIG}`)
);
logger.log('App config fetched', config);
if (config.dapps) {
const oldDapps = DAPPS.splice(0);
for (const dapp of config.dapps) {
| const oldDapp = oldDapps.find((d) => d.id === dapp.id); |
if (oldDapp) {
DAPPS.push(Object.assign({}, oldDapp, dapp));
} else {
DAPPS.push(dapp);
}
}
logger.log('Dapps updated', DAPPS);
await resolveAllDapps();
}
}
const dappsUpdater = setInterval(updateConfig, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsUpdater));
waitForIpfs().then(updateConfig).catch(logger.error);
ipcMain.handle('peers', async () => fetchPeers());
http
.createServer((req, res) => {
const id = `${req.headers.host}`.replace('.localhost:8888', '');
const dapp = DAPPS.find((dapp) => dapp.id === id);
if (dapp && dapp.url) {
req.headers.host = dapp.url;
proxy({ host: '127.0.0.1', port: 8080 }, req, res);
return;
}
res.writeHead(404);
res.end('Not found');
})
.listen(8888, '0.0.0.0');
| src/main/main.ts | Synthetixio-synthetix-node-6de6a58 | [
{
"filename": "src/main/dapps.ts",
"retrieved_chunk": " Object.assign(dapp, { url });\n logger.log(dapp.id, 'local IPFS host:', url);\n } catch (e) {\n logger.error(e);\n return;\n }\n}\nexport async function cleanupOldDapps() {\n const hashes = DAPPS.map((dapp) => dapp.qm);\n logger.log('Current DAPPs hashes', hashes);",
"score": 0.8327897787094116
},
{
"filename": "src/main/dapps.ts",
"retrieved_chunk": " if (hashes.length < 1 || hashes.some((hash) => !hash)) {\n // We only want to cleanup when all the dapps aer resolved\n return;\n }\n try {\n const pins = JSON.parse(await ipfs('pin ls --enc=json --type=recursive'));\n const pinnedHashes = Object.keys(pins.Keys);\n logger.log('Existing IPFS pins', pinnedHashes);\n const toUnpin = pinnedHashes.filter((hash) => !hashes.includes(hash));\n logger.log('Hashes to unpin', toUnpin);",
"score": 0.7760066986083984
},
{
"filename": "src/main/dapps.ts",
"retrieved_chunk": " return;\n }\n const isDappPinned = await isPinned(qm);\n if (!isDappPinned) {\n logger.log(dapp.id, 'pinning...', qm);\n await ipfs(`pin add --progress ${qm}`);\n }\n const bafy = await convertCid(qm);\n Object.assign(dapp, { bafy });\n const url = `${bafy}.ipfs.localhost`;",
"score": 0.7720428705215454
},
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": " log(`Installing ipfs version ${latestVersionNumber}`);\n }\n const downloadUrl = `https://dist.ipfs.tech/go-ipfs/${latestVersion}/go-ipfs_${latestVersion}_darwin-${targetArch}.tar.gz`;\n log(`IPFS package: ${downloadUrl}`);\n await fs.rm(path.join(IPFS_PATH, 'config'), { recursive: true });\n await fs.mkdir(ROOT, { recursive: true });\n await new Promise((resolve, reject) => {\n const file = createWriteStream(path.join(ROOT, 'ipfs.tar.gz'));\n https.get(downloadUrl, (response) =>\n pipeline(response, file).then(resolve).catch(reject)",
"score": 0.757703959941864
},
{
"filename": "src/main/dapps.ts",
"retrieved_chunk": " if (toUnpin.length > 0) {\n for (const hash of toUnpin) {\n logger.log(`Unpinning ${hash}`);\n await ipfs(`pin rm ${hash}`);\n }\n const pinsAfter = JSON.parse(\n await ipfs('pin ls --enc=json --type=recursive')\n );\n logger.log('Updated IPFS pins', pinsAfter);\n // Clenup the repo",
"score": 0.7570491433143616
}
] | typescript | const oldDapp = oldDapps.find((d) => d.id === dapp.id); |
/**
* This module executes inside of electron's main process. You can start
* electron renderer process from here and communicate with the other processes
* through IPC.
*
* When running `npm run build` or `npm run build:main`, this file is compiled to
* `./src/main.js` using webpack. This gives us some performance wins.
*/
import path from 'path';
import { app, BrowserWindow, ipcMain, Menu, shell, Tray } from 'electron';
// import { autoUpdater } from 'electron-updater';
import logger from 'electron-log';
import { resolveHtmlPath } from './util';
import {
configureIpfs,
downloadIpfs,
ipfs,
ipfsDaemon,
ipfsIsInstalled,
ipfsIsRunning,
ipfsKill,
waitForIpfs,
} from './ipfs';
import {
configureFollower,
downloadFollower,
follower,
followerDaemon,
followerId,
followerIsInstalled,
followerKill,
followerPid,
} from './follower';
import { DAPPS, resolveDapp } from './dapps';
import { fetchPeers } from './peers';
import { SYNTHETIX_NODE_APP_CONFIG } from '../const';
import * as settings from './settings';
import http from 'http';
import { proxy } from './proxy';
logger.transports.file.level = 'info';
const isDebug =
process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';
// class AppUpdater {
// constructor() {
// log.transports.file.level = 'info';
// autoUpdater.logger = log;
// autoUpdater.checkForUpdatesAndNotify();
// }
// }
let tray: Tray | null = null;
let mainWindow: BrowserWindow | null = null;
if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support');
sourceMapSupport.install();
}
const RESOURCES_PATH = app.isPackaged
? path.join(process.resourcesPath, 'assets')
: path.join(__dirname, '../../assets');
const getAssetPath = (...paths: string[]): string => {
return path.join(RESOURCES_PATH, ...paths);
};
function updateContextMenu() {
const menu = generateMenuItems();
if (tray && !tray.isDestroyed()) {
tray.setContextMenu(
Menu.buildFromTemplate([
menu.app,
menu.autoStart,
menu.devTools,
menu.dock,
{ type: 'separator' },
...menu.dapps,
{ type: 'separator' },
menu.quit,
])
);
}
app.dock.setMenu(
Menu.buildFromTemplate([
menu.app,
menu.autoStart,
menu.devTools,
menu.tray,
{ type: 'separator' },
...menu.dapps,
])
);
}
function createWindow() {
mainWindow = new BrowserWindow({
show: true,
useContentSize: true,
center: true,
minWidth: 600,
minHeight: 470,
skipTaskbar: true,
fullscreen: false,
fullscreenable: false,
width: 600,
height: 470,
// frame: false,
icon: getAssetPath('icon.icns'),
webPreferences: {
preload: app.isPackaged
? path.join(__dirname, 'preload.js')
: path.join(__dirname, '../../.erb/dll/preload.js'),
},
});
if (isDebug) {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
mainWindow.loadURL(resolveHtmlPath('index.html'));
mainWindow.on('closed', () => {
mainWindow = null;
});
// Open urls in the user's browser
mainWindow.webContents.setWindowOpenHandler((edata) => {
shell.openExternal(edata.url);
return { action: 'deny' };
});
mainWindow.webContents.on('devtools-opened', updateContextMenu);
mainWindow.webContents.on('devtools-closed', updateContextMenu);
mainWindow.on('hide', updateContextMenu);
mainWindow.on('show', updateContextMenu);
// Remove this if your app does not use auto updates
// eslint-disable-next-line
// new AppUpdater();
}
function generateMenuItems() {
return {
app: {
label: mainWindow?.isVisible() ? 'Hide App' : 'Open App',
click: () => {
if (mainWindow?.isVisible()) {
mainWindow.hide();
if (mainWindow.webContents.isDevToolsOpened()) {
mainWindow.webContents.closeDevTools();
}
return;
}
if (!mainWindow) {
createWindow();
} else {
mainWindow.show();
}
updateContextMenu();
},
},
autoStart: {
label: app.getLoginItemSettings().openAtLogin
? 'Disable AutoStart'
: 'Enable AutoStart',
click: () => {
const settings = app.getLoginItemSettings();
settings.openAtLogin = !settings.openAtLogin;
app.setLoginItemSettings(settings);
updateContextMenu();
},
},
devTools: {
label:
mainWindow && mainWindow.webContents.isDevToolsOpened()
? 'Close DevTools'
: 'Open DevTools',
click: () => {
if (mainWindow) {
if (mainWindow.webContents.isDevToolsOpened()) {
mainWindow.webContents.closeDevTools();
} else {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
}
updateContextMenu();
},
},
dock: {
label: app.dock && app.dock.isVisible() ? 'Hide Dock' : 'Show Dock',
click: async () => {
if (app.dock) {
if (app.dock.isVisible()) {
await settings.set('dock', false);
app.dock.hide();
} else {
await settings.set('dock', true);
app.dock.show();
}
}
updateContextMenu();
},
},
tray: {
label: tray && !tray.isDestroyed() ? 'Hide Tray icon' : 'Show Tray icon',
click: async () => {
if (tray && !tray.isDestroyed()) {
await settings.set('tray', false);
tray.destroy();
} else {
await settings.set('tray', true);
createTray();
}
updateContextMenu();
},
},
separator: {
type: 'separator',
},
dapps: DAPPS.map((dapp) => {
return {
enabled: Boolean(dapp.url),
label: dapp.label,
click: () => shell.openExternal(`http://${dapp.id}.localhost:8888`),
};
}),
quit: {
label: 'Quit',
click: () => {
app.quit();
},
},
};
}
app.once('ready', async () => {
// Hide the app from the dock
if (app.dock && !(await settings.get('dock'))) {
app.dock.hide();
}
if (await settings.get('tray')) {
createTray();
}
updateContextMenu();
});
function createTray() {
// Create a Tray instance with the icon you want to use for the menu bar
tray = new Tray(getAssetPath('[email protected]'));
tray.on('mouse-down', (_event) => {
if (mainWindow?.isVisible()) {
mainWindow?.focus();
}
});
}
/**
* Add event listeners...
*/
app.on('window-all-closed', () => {
// Respect the OSX convention of having the application in memory even
// after all windows have been closed
if (process.platform !== 'darwin') {
app.quit();
}
});
app
.whenReady()
.then(() => {
createWindow();
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
})
.catch(logger.error);
ipcMain.handle('install-ipfs', downloadIpfs);
ipcMain.handle('install-follower', downloadFollower);
ipcMain.handle('ipfs-isInstalled', ipfsIsInstalled);
ipcMain.handle('follower-isInstalled', followerIsInstalled);
ipcMain.handle('ipfs-isRunning', ipfsIsRunning);
ipcMain.handle('follower-isRunning', followerPid);
ipcMain.handle('run-ipfs', async () => {
await configureIpfs();
await ipfsDaemon();
});
ipcMain.handle('run-follower', async () => {
await configureFollower();
await followerDaemon();
});
ipcMain.handle('ipfs-peers', () => ipfs('swarm peers'));
ipcMain.handle('ipfs-id', () => followerId());
ipcMain.handle('ipfs-repo-stat', () => ipfs('repo stat'));
ipcMain.handle('ipfs-stats-bw', () => ipfs('stats bw'));
ipcMain.handle('ipfs-follower-info', () => follower('synthetix info'));
app.on('will-quit', ipfsKill);
app.on('will-quit', followerKill);
downloadIpfs();
ipfsDaemon();
const ipfsCheck = setInterval(ipfsDaemon, 10_000);
app.on('will-quit', () => clearInterval(ipfsCheck));
downloadFollower();
followerDaemon();
const followerCheck = setInterval(followerDaemon, 10_000);
app.on('will-quit', () => clearInterval(followerCheck));
ipcMain.handle('dapps', async () => {
return DAPPS.map((dapp) => ({
...dapp,
url: dapp.url ? `http://${dapp.id}.localhost:8888` : null,
}));
});
ipcMain.handle('dapp', async (_event, id: string) => {
const dapp = DAPPS.find((dapp) => dapp.id === id);
return dapp && dapp.url ? `http://${dapp.id}.localhost:8888` : null;
});
async function resolveAllDapps() {
DAPPS.forEach((dapp) => resolveDapp(dapp).then(updateContextMenu));
}
const dappsResolver = setInterval(resolveAllDapps, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsResolver));
waitForIpfs().then(resolveAllDapps).catch(logger.error);
async function updateConfig() {
const config = JSON.parse(
| await ipfs(`cat /ipns/${SYNTHETIX_NODE_APP_CONFIG}`)
); |
logger.log('App config fetched', config);
if (config.dapps) {
const oldDapps = DAPPS.splice(0);
for (const dapp of config.dapps) {
const oldDapp = oldDapps.find((d) => d.id === dapp.id);
if (oldDapp) {
DAPPS.push(Object.assign({}, oldDapp, dapp));
} else {
DAPPS.push(dapp);
}
}
logger.log('Dapps updated', DAPPS);
await resolveAllDapps();
}
}
const dappsUpdater = setInterval(updateConfig, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsUpdater));
waitForIpfs().then(updateConfig).catch(logger.error);
ipcMain.handle('peers', async () => fetchPeers());
http
.createServer((req, res) => {
const id = `${req.headers.host}`.replace('.localhost:8888', '');
const dapp = DAPPS.find((dapp) => dapp.id === id);
if (dapp && dapp.url) {
req.headers.host = dapp.url;
proxy({ host: '127.0.0.1', port: 8080 }, req, res);
return;
}
res.writeHead(404);
res.end('Not found');
})
.listen(8888, '0.0.0.0');
| src/main/main.ts | Synthetixio-synthetix-node-6de6a58 | [
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": " log(`Installing ipfs version ${latestVersionNumber}`);\n }\n const downloadUrl = `https://dist.ipfs.tech/go-ipfs/${latestVersion}/go-ipfs_${latestVersion}_darwin-${targetArch}.tar.gz`;\n log(`IPFS package: ${downloadUrl}`);\n await fs.rm(path.join(IPFS_PATH, 'config'), { recursive: true });\n await fs.mkdir(ROOT, { recursive: true });\n await new Promise((resolve, reject) => {\n const file = createWriteStream(path.join(ROOT, 'ipfs.tar.gz'));\n https.get(downloadUrl, (response) =>\n pipeline(response, file).then(resolve).catch(reject)",
"score": 0.7831788063049316
},
{
"filename": "src/main/dapps.ts",
"retrieved_chunk": " Object.assign(dapp, { url });\n logger.log(dapp.id, 'local IPFS host:', url);\n } catch (e) {\n logger.error(e);\n return;\n }\n}\nexport async function cleanupOldDapps() {\n const hashes = DAPPS.map((dapp) => dapp.qm);\n logger.log('Current DAPPs hashes', hashes);",
"score": 0.7559303045272827
},
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": "const IPFS_PATH = path.join(HOME, '.ipfs');\nexport function ipfsKill() {\n try {\n getPidsSync('.synthetix/go-ipfs/ipfs').forEach((pid) => {\n logger.log('Killing ipfs', pid);\n process.kill(pid);\n });\n logger.log('Removing .ipfs/repo.lock');\n rmSync(path.join(IPFS_PATH, 'repo.lock'), { recursive: true });\n } catch (_e) {",
"score": 0.7466608285903931
},
{
"filename": "src/main/follower.ts",
"retrieved_chunk": " const file = createWriteStream(\n path.join(ROOT, 'ipfs-cluster-follow.tar.gz')\n );\n https.get(downloadUrl, (response) =>\n pipeline(response, file).then(resolve).catch(reject)\n );\n });\n await new Promise((resolve, reject) => {\n createReadStream(path.join(ROOT, 'ipfs-cluster-follow.tar.gz'))\n .pipe(zlib.createGunzip())",
"score": 0.733188271522522
},
{
"filename": "src/main/follower.ts",
"retrieved_chunk": " log(\n `Updating ipfs-cluster-follow from version ${installedVersion} to ${latestVersionNumber}`\n );\n } else {\n log(`Installing ipfs-cluster-follow version ${latestVersionNumber}`);\n }\n const downloadUrl = `https://dist.ipfs.tech/ipfs-cluster-follow/${latestVersion}/ipfs-cluster-follow_${latestVersion}_darwin-${targetArch}.tar.gz`;\n log(`ipfs-cluster-follow package: ${downloadUrl}`);\n await fs.mkdir(ROOT, { recursive: true });\n await new Promise((resolve, reject) => {",
"score": 0.7152147889137268
}
] | typescript | await ipfs(`cat /ipns/${SYNTHETIX_NODE_APP_CONFIG}`)
); |
import {
Box,
Code,
Drawer,
DrawerBody,
DrawerCloseButton,
DrawerContent,
DrawerHeader,
DrawerOverlay,
Heading,
Icon,
IconButton,
Spinner,
Stack,
Stat,
StatLabel,
StatNumber,
Text,
Tooltip,
} from '@chakra-ui/react';
import { ArrowRightIcon, CheckIcon, CopyIcon } from '@chakra-ui/icons';
import { usePeerId } from './usePeerId';
import { usePeers } from './usePeers';
import { useRateIn } from './useRateIn';
import { useRateOut } from './useRateOut';
import { useHostingSize } from './useHostingSize';
import { useIsIpfsRunning } from './useIsIpfsRunning';
import { useIsIpfsInstalled } from './useIsIpfsInstalled';
import { useIsFollowerInstalled } from './useIsFollowerInstalled';
import { useFollowerInfo } from './useFollowerInfo';
import { SYNTHETIX_IPNS } from '../../const';
import React from 'react';
function handleCopy(text: string) {
if (text) {
navigator.clipboard.writeText(text);
}
}
function StatusIcon(props: any) {
return (
<Box display="inline-block" mr="1" transform="translateY(-1px)" {...props}>
<Icon viewBox="0 0 200 200">
<path
fill="currentColor"
d="M 100, 100 m -75, 0 a 75,75 0 1,0 150,0 a 75,75 0 1,0 -150,0"
/>
</Icon>
</Box>
);
}
export function Ipfs() {
const { data: isIpfsInstalled } = useIsIpfsInstalled();
const { data: isIpfsRunning } = useIsIpfsRunning();
const { data: isFollowerInstalled } = useIsFollowerInstalled();
const { data: peers } = usePeers();
const { data: peerId } = usePeerId();
const { | data: followerInfo } = useFollowerInfo(); |
const rateIn = useRateIn();
const rateOut = useRateOut();
const hostingSize = useHostingSize();
// eslint-disable-next-line no-console
console.log({
isIpfsInstalled,
isIpfsRunning,
isFollowerInstalled,
isFollowerRunning: followerInfo.cluster,
peers,
peerId,
rateIn,
rateOut,
hostingSize,
});
const [peersOpened, setPeersOpened] = React.useState(false);
return (
<Box pt="3">
<Box flex="1" p="0" whiteSpace="nowrap">
<Stack direction="row" spacing={6} justifyContent="center" mb="2">
<Stat>
<StatLabel mb="0" opacity="0.8">
Hosting
</StatLabel>
<StatNumber>
{hostingSize ? `${hostingSize.toFixed(2)} Mb` : '-'}
</StatNumber>
</Stat>
<Stat>
<StatLabel mb="0" opacity="0.8">
Outgoing
</StatLabel>
<StatNumber>{rateOut ? rateOut : '-'}</StatNumber>
</Stat>
<Stat>
<StatLabel mb="0" opacity="0.8">
Incoming
</StatLabel>
<StatNumber>{rateIn ? rateIn : '-'}</StatNumber>
</Stat>
<Stat cursor="pointer" onClick={() => setPeersOpened(true)}>
<StatLabel mb="0" opacity="0.8">
Cluster peers{' '}
<IconButton
aria-label="Open online peers"
size="xs"
icon={<ArrowRightIcon />}
onClick={() => setPeersOpened(true)}
/>
</StatLabel>
<StatNumber>
{peers ? peers.length : '-'}{' '}
<Drawer
isOpen={peersOpened}
placement="right"
onClose={() => setPeersOpened(false)}
>
<DrawerOverlay />
<DrawerContent maxWidth="26em">
<DrawerCloseButton />
<DrawerHeader>Online peers</DrawerHeader>
<DrawerBody>
<Stack direction="column" margin="0" overflow="scroll">
{peers.map((peer: { id: string }, i: number) => (
<Code
key={peer.id}
fontSize="10px"
display="block"
backgroundColor="transparent"
whiteSpace="nowrap"
>
{`${i}`.padStart(3, '0')}.{' '}
<Tooltip
hasArrow
placement="top"
openDelay={200}
fontSize="xs"
label={
peer.id === peerId
? 'Your connected Peer ID'
: 'Copy Peer ID'
}
>
<Text
as="span"
borderBottom="1px solid green.400"
borderBottomColor={
peer.id === peerId ? 'green.400' : 'transparent'
}
borderBottomStyle="solid"
borderBottomWidth="1px"
cursor="pointer"
onClick={() => handleCopy(peer.id)}
>
{peer.id}
</Text>
</Tooltip>{' '}
{peer.id === peerId ? (
<CheckIcon color="green.400" />
) : null}
</Code>
))}
</Stack>
</DrawerBody>
</DrawerContent>
</Drawer>
</StatNumber>
</Stat>
</Stack>
<Box bg="whiteAlpha.200" pt="4" px="4" pb="4" mb="3">
<Heading mb="3" size="sm">
{isIpfsInstalled && isIpfsRunning ? (
<Text as="span" whiteSpace="nowrap">
<StatusIcon textColor="green.400" />
<Text display="inline-block">Your IPFS node is running</Text>
</Text>
) : null}
{isIpfsInstalled && !isIpfsRunning ? (
<Text as="span" whiteSpace="nowrap">
<Spinner size="xs" mr="2" />
<Text display="inline-block">
Your IPFS node is starting...
</Text>
</Text>
) : null}
{!isIpfsInstalled ? (
<Text as="span" whiteSpace="nowrap">
<Spinner size="xs" mr="2" />
<Text display="inline-block">IPFS node is installing...</Text>
</Text>
) : null}
</Heading>
<Heading size="sm">
{isFollowerInstalled && followerInfo.cluster ? (
<Text as="span" whiteSpace="nowrap">
<StatusIcon textColor="green.400" />
<Text display="inline-block">
You are connected to the Synthetix Cluster
</Text>
</Text>
) : null}
{isFollowerInstalled && !followerInfo.cluster ? (
<Text as="span" whiteSpace="nowrap">
<Spinner size="xs" mr="2" />
<Text display="inline-block">
Connecting to the Synthetix Cluster...
</Text>
</Text>
) : null}
{!isFollowerInstalled ? (
<Text as="span" whiteSpace="nowrap">
<Spinner size="xs" mr="2" />
<Text display="inline-block">
Synthetix Cluster Connector is installing...
</Text>
</Text>
) : null}
</Heading>
</Box>
<Box mb="3">
<Text
fontSize="sm"
textTransform="uppercase"
letterSpacing="1px"
opacity="0.8"
mb="1"
>
Your Peer ID
</Text>
<Box display="flex" alignItems="center">
<Code>
{peerId ? peerId : 'CONNECT YOUR IPFS NODE TO GENERATE A PEER ID'}
</Code>
{peerId && (
<CopyIcon
opacity="0.8"
ml="2"
cursor="pointer"
onClick={() => handleCopy(peerId)}
/>
)}
</Box>
</Box>
<Box>
<Text
fontSize="sm"
textTransform="uppercase"
letterSpacing="1px"
opacity="0.8"
mb="1"
>
Synthetix Cluster IPNS
</Text>
<Box display="flex" alignItems="center">
<Code fontSize="sm">{SYNTHETIX_IPNS}</Code>
{SYNTHETIX_IPNS && (
<CopyIcon
opacity="0.8"
ml="2"
cursor="pointer"
onClick={() => handleCopy(SYNTHETIX_IPNS)}
/>
)}
</Box>
</Box>
</Box>
</Box>
);
}
| src/renderer/Ipfs/Ipfs.tsx | Synthetixio-synthetix-node-6de6a58 | [
{
"filename": "src/renderer/Ipfs/usePeers.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsIpfsRunning } from './useIsIpfsRunning';\nconst { ipcRenderer } = window?.electron || {};\nexport function usePeers() {\n const { data: isRunning } = useIsIpfsRunning();\n return useQuery({\n queryKey: ['ipfs', 'peers'],\n queryFn: async () => {\n const peers = await ipcRenderer.invoke('peers');\n if (!peers) {",
"score": 0.8473567366600037
},
{
"filename": "src/renderer/Ipfs/useFollowerInfo.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsFollowerRunning } from './useIsFollowerRunning';\nconst { ipcRenderer } = window?.electron || {};\nexport function useFollowerInfo() {\n const { data: isRunning } = useIsFollowerRunning();\n return useQuery({\n queryKey: ['follower', 'info'],\n queryFn: async () => {\n const state = await ipcRenderer.invoke('ipfs-follower-info');\n return {",
"score": 0.8318996429443359
},
{
"filename": "src/renderer/Ipfs/usePeerId.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsIpfsRunning } from './useIsIpfsRunning';\nconst { ipcRenderer } = window?.electron || {};\nexport function usePeerId() {\n const { data: isRunning } = useIsIpfsRunning();\n return useQuery({\n queryKey: ['ipfs', 'id'],\n queryFn: async () => {\n const id = await ipcRenderer.invoke('ipfs-id');\n if (!id) {",
"score": 0.82664954662323
},
{
"filename": "src/renderer/Ipfs/useRepoStat.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsIpfsRunning } from './useIsIpfsRunning';\nconst { ipcRenderer } = window?.electron || {};\nexport function useRepoStat() {\n const { data: isRunning } = useIsIpfsRunning();\n return useQuery({\n queryKey: ['ipfs', 'repo stat'],\n queryFn: async () => {\n const stats = await ipcRenderer.invoke('ipfs-repo-stat');\n if (!stats) {",
"score": 0.8140888214111328
},
{
"filename": "src/renderer/Ipfs/useStatsBw.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsIpfsRunning } from './useIsIpfsRunning';\nconst { ipcRenderer } = window?.electron || {};\nexport function useStatsBw() {\n const { data: isRunning } = useIsIpfsRunning();\n return useQuery({\n queryKey: ['ipfs', 'stats bw'],\n queryFn: async () => {\n const stats = await ipcRenderer.invoke('ipfs-stats-bw');\n if (!stats) {",
"score": 0.8087862730026245
}
] | typescript | data: followerInfo } = useFollowerInfo(); |
/**
* This module executes inside of electron's main process. You can start
* electron renderer process from here and communicate with the other processes
* through IPC.
*
* When running `npm run build` or `npm run build:main`, this file is compiled to
* `./src/main.js` using webpack. This gives us some performance wins.
*/
import path from 'path';
import { app, BrowserWindow, ipcMain, Menu, shell, Tray } from 'electron';
// import { autoUpdater } from 'electron-updater';
import logger from 'electron-log';
import { resolveHtmlPath } from './util';
import {
configureIpfs,
downloadIpfs,
ipfs,
ipfsDaemon,
ipfsIsInstalled,
ipfsIsRunning,
ipfsKill,
waitForIpfs,
} from './ipfs';
import {
configureFollower,
downloadFollower,
follower,
followerDaemon,
followerId,
followerIsInstalled,
followerKill,
followerPid,
} from './follower';
import { DAPPS, resolveDapp } from './dapps';
import { fetchPeers } from './peers';
import { SYNTHETIX_NODE_APP_CONFIG } from '../const';
import * as settings from './settings';
import http from 'http';
import { proxy } from './proxy';
logger.transports.file.level = 'info';
const isDebug =
process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';
// class AppUpdater {
// constructor() {
// log.transports.file.level = 'info';
// autoUpdater.logger = log;
// autoUpdater.checkForUpdatesAndNotify();
// }
// }
let tray: Tray | null = null;
let mainWindow: BrowserWindow | null = null;
if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support');
sourceMapSupport.install();
}
const RESOURCES_PATH = app.isPackaged
? path.join(process.resourcesPath, 'assets')
: path.join(__dirname, '../../assets');
const getAssetPath = (...paths: string[]): string => {
return path.join(RESOURCES_PATH, ...paths);
};
function updateContextMenu() {
const menu = generateMenuItems();
if (tray && !tray.isDestroyed()) {
tray.setContextMenu(
Menu.buildFromTemplate([
menu.app,
menu.autoStart,
menu.devTools,
menu.dock,
{ type: 'separator' },
...menu.dapps,
{ type: 'separator' },
menu.quit,
])
);
}
app.dock.setMenu(
Menu.buildFromTemplate([
menu.app,
menu.autoStart,
menu.devTools,
menu.tray,
{ type: 'separator' },
...menu.dapps,
])
);
}
function createWindow() {
mainWindow = new BrowserWindow({
show: true,
useContentSize: true,
center: true,
minWidth: 600,
minHeight: 470,
skipTaskbar: true,
fullscreen: false,
fullscreenable: false,
width: 600,
height: 470,
// frame: false,
icon: getAssetPath('icon.icns'),
webPreferences: {
preload: app.isPackaged
? path.join(__dirname, 'preload.js')
: path.join(__dirname, '../../.erb/dll/preload.js'),
},
});
if (isDebug) {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
| mainWindow.loadURL(resolveHtmlPath('index.html')); |
mainWindow.on('closed', () => {
mainWindow = null;
});
// Open urls in the user's browser
mainWindow.webContents.setWindowOpenHandler((edata) => {
shell.openExternal(edata.url);
return { action: 'deny' };
});
mainWindow.webContents.on('devtools-opened', updateContextMenu);
mainWindow.webContents.on('devtools-closed', updateContextMenu);
mainWindow.on('hide', updateContextMenu);
mainWindow.on('show', updateContextMenu);
// Remove this if your app does not use auto updates
// eslint-disable-next-line
// new AppUpdater();
}
function generateMenuItems() {
return {
app: {
label: mainWindow?.isVisible() ? 'Hide App' : 'Open App',
click: () => {
if (mainWindow?.isVisible()) {
mainWindow.hide();
if (mainWindow.webContents.isDevToolsOpened()) {
mainWindow.webContents.closeDevTools();
}
return;
}
if (!mainWindow) {
createWindow();
} else {
mainWindow.show();
}
updateContextMenu();
},
},
autoStart: {
label: app.getLoginItemSettings().openAtLogin
? 'Disable AutoStart'
: 'Enable AutoStart',
click: () => {
const settings = app.getLoginItemSettings();
settings.openAtLogin = !settings.openAtLogin;
app.setLoginItemSettings(settings);
updateContextMenu();
},
},
devTools: {
label:
mainWindow && mainWindow.webContents.isDevToolsOpened()
? 'Close DevTools'
: 'Open DevTools',
click: () => {
if (mainWindow) {
if (mainWindow.webContents.isDevToolsOpened()) {
mainWindow.webContents.closeDevTools();
} else {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
}
updateContextMenu();
},
},
dock: {
label: app.dock && app.dock.isVisible() ? 'Hide Dock' : 'Show Dock',
click: async () => {
if (app.dock) {
if (app.dock.isVisible()) {
await settings.set('dock', false);
app.dock.hide();
} else {
await settings.set('dock', true);
app.dock.show();
}
}
updateContextMenu();
},
},
tray: {
label: tray && !tray.isDestroyed() ? 'Hide Tray icon' : 'Show Tray icon',
click: async () => {
if (tray && !tray.isDestroyed()) {
await settings.set('tray', false);
tray.destroy();
} else {
await settings.set('tray', true);
createTray();
}
updateContextMenu();
},
},
separator: {
type: 'separator',
},
dapps: DAPPS.map((dapp) => {
return {
enabled: Boolean(dapp.url),
label: dapp.label,
click: () => shell.openExternal(`http://${dapp.id}.localhost:8888`),
};
}),
quit: {
label: 'Quit',
click: () => {
app.quit();
},
},
};
}
app.once('ready', async () => {
// Hide the app from the dock
if (app.dock && !(await settings.get('dock'))) {
app.dock.hide();
}
if (await settings.get('tray')) {
createTray();
}
updateContextMenu();
});
function createTray() {
// Create a Tray instance with the icon you want to use for the menu bar
tray = new Tray(getAssetPath('[email protected]'));
tray.on('mouse-down', (_event) => {
if (mainWindow?.isVisible()) {
mainWindow?.focus();
}
});
}
/**
* Add event listeners...
*/
app.on('window-all-closed', () => {
// Respect the OSX convention of having the application in memory even
// after all windows have been closed
if (process.platform !== 'darwin') {
app.quit();
}
});
app
.whenReady()
.then(() => {
createWindow();
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
})
.catch(logger.error);
ipcMain.handle('install-ipfs', downloadIpfs);
ipcMain.handle('install-follower', downloadFollower);
ipcMain.handle('ipfs-isInstalled', ipfsIsInstalled);
ipcMain.handle('follower-isInstalled', followerIsInstalled);
ipcMain.handle('ipfs-isRunning', ipfsIsRunning);
ipcMain.handle('follower-isRunning', followerPid);
ipcMain.handle('run-ipfs', async () => {
await configureIpfs();
await ipfsDaemon();
});
ipcMain.handle('run-follower', async () => {
await configureFollower();
await followerDaemon();
});
ipcMain.handle('ipfs-peers', () => ipfs('swarm peers'));
ipcMain.handle('ipfs-id', () => followerId());
ipcMain.handle('ipfs-repo-stat', () => ipfs('repo stat'));
ipcMain.handle('ipfs-stats-bw', () => ipfs('stats bw'));
ipcMain.handle('ipfs-follower-info', () => follower('synthetix info'));
app.on('will-quit', ipfsKill);
app.on('will-quit', followerKill);
downloadIpfs();
ipfsDaemon();
const ipfsCheck = setInterval(ipfsDaemon, 10_000);
app.on('will-quit', () => clearInterval(ipfsCheck));
downloadFollower();
followerDaemon();
const followerCheck = setInterval(followerDaemon, 10_000);
app.on('will-quit', () => clearInterval(followerCheck));
ipcMain.handle('dapps', async () => {
return DAPPS.map((dapp) => ({
...dapp,
url: dapp.url ? `http://${dapp.id}.localhost:8888` : null,
}));
});
ipcMain.handle('dapp', async (_event, id: string) => {
const dapp = DAPPS.find((dapp) => dapp.id === id);
return dapp && dapp.url ? `http://${dapp.id}.localhost:8888` : null;
});
async function resolveAllDapps() {
DAPPS.forEach((dapp) => resolveDapp(dapp).then(updateContextMenu));
}
const dappsResolver = setInterval(resolveAllDapps, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsResolver));
waitForIpfs().then(resolveAllDapps).catch(logger.error);
async function updateConfig() {
const config = JSON.parse(
await ipfs(`cat /ipns/${SYNTHETIX_NODE_APP_CONFIG}`)
);
logger.log('App config fetched', config);
if (config.dapps) {
const oldDapps = DAPPS.splice(0);
for (const dapp of config.dapps) {
const oldDapp = oldDapps.find((d) => d.id === dapp.id);
if (oldDapp) {
DAPPS.push(Object.assign({}, oldDapp, dapp));
} else {
DAPPS.push(dapp);
}
}
logger.log('Dapps updated', DAPPS);
await resolveAllDapps();
}
}
const dappsUpdater = setInterval(updateConfig, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsUpdater));
waitForIpfs().then(updateConfig).catch(logger.error);
ipcMain.handle('peers', async () => fetchPeers());
http
.createServer((req, res) => {
const id = `${req.headers.host}`.replace('.localhost:8888', '');
const dapp = DAPPS.find((dapp) => dapp.id === id);
if (dapp && dapp.url) {
req.headers.host = dapp.url;
proxy({ host: '127.0.0.1', port: 8080 }, req, res);
return;
}
res.writeHead(404);
res.end('Not found');
})
.listen(8888, '0.0.0.0');
| src/main/main.ts | Synthetixio-synthetix-node-6de6a58 | [
{
"filename": "src/main/util.ts",
"retrieved_chunk": "import { URL } from 'url';\nimport path from 'path';\nexport function resolveHtmlPath(htmlFileName: string) {\n if (process.env.NODE_ENV === 'development') {\n const port = process.env.PORT || 1212;\n const url = new URL(`http://localhost:${port}`);\n url.pathname = htmlFileName;\n return url.href;\n }\n return `file://${path.resolve(__dirname, '../renderer/', htmlFileName)}`;",
"score": 0.7812424302101135
},
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": "const IPFS_PATH = path.join(HOME, '.ipfs');\nexport function ipfsKill() {\n try {\n getPidsSync('.synthetix/go-ipfs/ipfs').forEach((pid) => {\n logger.log('Killing ipfs', pid);\n process.kill(pid);\n });\n logger.log('Removing .ipfs/repo.lock');\n rmSync(path.join(IPFS_PATH, 'repo.lock'), { recursive: true });\n } catch (_e) {",
"score": 0.696877121925354
},
{
"filename": "src/main/settings.ts",
"retrieved_chunk": "import { promises as fs } from 'fs';\nimport os from 'os';\nimport path from 'path';\nexport const ROOT = path.join(os.homedir(), '.synthetix');\nconst DEFAULTS = Object.freeze({\n tray: true,\n dock: true,\n});\nexport async function read() {\n try {",
"score": 0.6939575672149658
},
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": " log(`Installing ipfs version ${latestVersionNumber}`);\n }\n const downloadUrl = `https://dist.ipfs.tech/go-ipfs/${latestVersion}/go-ipfs_${latestVersion}_darwin-${targetArch}.tar.gz`;\n log(`IPFS package: ${downloadUrl}`);\n await fs.rm(path.join(IPFS_PATH, 'config'), { recursive: true });\n await fs.mkdir(ROOT, { recursive: true });\n await new Promise((resolve, reject) => {\n const file = createWriteStream(path.join(ROOT, 'ipfs.tar.gz'));\n https.get(downloadUrl, (response) =>\n pipeline(response, file).then(resolve).catch(reject)",
"score": 0.6859410405158997
},
{
"filename": "src/main/follower.ts",
"retrieved_chunk": " throw new Error('ipfs-cluster-follow installation failed.');\n }\n return installedVersionCheck;\n}\nexport async function isConfigured() {\n try {\n const service = await fs.readFile(\n path.join(IPFS_FOLLOW_PATH, 'synthetix/service.json'),\n 'utf8'\n );",
"score": 0.6849901676177979
}
] | typescript | mainWindow.loadURL(resolveHtmlPath('index.html')); |
import { Plugin } from "obsidian";
import { CssEditorView, VIEW_TYPE_CSS } from "./CssEditorView";
import { CssSnippetFuzzySuggestModal } from "./modals/CssSnippetFuzzySuggestModal";
import { CssSnippetCreateModal } from "./modals/CssSnippetCreateModal";
import { deleteSnippetFile } from "./file-system-helpers";
import { detachLeavesOfTypeAndDisplay, openView } from "./workspace-helpers";
import { InfoNotice } from "./Notice";
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface CssEditorPluginSettings {}
const DEFAULT_SETTINGS: CssEditorPluginSettings = {};
export default class CssEditorPlugin extends Plugin {
settings: CssEditorPluginSettings;
async onload() {
await this.loadSettings();
this.addCommand({
id: "edit-css-snippet",
name: "Edit CSS Snippet",
callback: async () => {
new CssSnippetFuzzySuggestModal(
this.app,
this.openCssEditorView
).open();
},
});
this.addCommand({
id: "create-css-snippet",
name: "Create CSS Snippet",
callback: async () => {
new CssSnippetCreateModal(this.app, this).open();
},
});
this.addCommand({
id: "delete-css-snippet",
name: "Delete CSS Snippet",
callback: async () => {
new CssSnippetFuzzySuggestModal(this.app, (item) => {
deleteSnippetFile(this.app, item);
detachLeavesOfTypeAndDisplay(
this.app.workspace,
VIEW_TYPE_CSS,
item
);
new InfoNotice(`${item} was deleted.`);
}).open();
},
});
this.registerView( | VIEW_TYPE_CSS, (leaf) => new CssEditorView(leaf)); |
}
onunload() {}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
}
async saveSettings() {
await this.saveData(this.settings);
}
async openCssEditorView(filename: string) {
openView(this.app.workspace, VIEW_TYPE_CSS, { filename });
}
}
| src/main.ts | Zachatoo-obsidian-css-editor-881a94e | [
{
"filename": "src/CssEditorView.ts",
"retrieved_chunk": "\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t],\n\t\t});\n\t\tthis.filename = \"\";\n\t}\n\tgetViewType() {\n\t\treturn VIEW_TYPE_CSS;\n\t}\n\tgetIcon() {",
"score": 0.7623100876808167
},
{
"filename": "src/CssEditorView.ts",
"retrieved_chunk": "\t\t\t\t\t);\n\t\t\t\t\tthis.dispatchEditorData(data);\n\t\t\t\t}\n\t\t\t\tthis.filename = state.filename;\n\t\t\t}\n\t\t}\n\t\tsuper.setState(state, result);\n\t}\n\trequestSave = debounce(this.save, 1000);\n\t/**",
"score": 0.7290411591529846
},
{
"filename": "src/modals/CssSnippetFuzzySuggestModal.ts",
"retrieved_chunk": "\t\tsuper.renderSuggestion(item, el);\n\t\tel.appendChild(\n\t\t\tcreateDiv({ cls: \"css-editor-suggestion-description\" }, (el) =>\n\t\t\t\tel.appendText(`${getSnippetDirectory(this.app)}${item.item}`)\n\t\t\t)\n\t\t);\n\t}\n\tonChooseItem(item: string, evt: MouseEvent | KeyboardEvent): void {\n\t\tthrow new Error(\"Method not implemented.\");\n\t}",
"score": 0.7236607670783997
},
{
"filename": "src/workspace-helpers.ts",
"retrieved_chunk": "\t\tif (leaf.getDisplayText() === display) {\n\t\t\tleaf.detach();\n\t\t}\n\t});\n}",
"score": 0.7232943773269653
},
{
"filename": "src/modals/CssSnippetCreateModal.ts",
"retrieved_chunk": "\t\t\ttry {\n\t\t\t\tawait createSnippetFile(this.app, this.value, \"\");\n\t\t\t\tawait this.plugin.openCssEditorView(this.value);\n\t\t\t\tthis.app.customCss?.setCssEnabledStatus?.(\n\t\t\t\t\tthis.value.replace(\".css\", \"\"),\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t\tthis.close();\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof Error) {",
"score": 0.7055749297142029
}
] | typescript | VIEW_TYPE_CSS, (leaf) => new CssEditorView(leaf)); |
import { App, Modal, TextComponent } from "obsidian";
import CssEditorPlugin from "src/main";
import { createSnippetFile } from "../file-system-helpers";
import { ErrorNotice } from "../Notice";
export class CssSnippetCreateModal extends Modal {
private value: string;
private plugin: CssEditorPlugin;
constructor(app: App, plugin: CssEditorPlugin) {
super(app);
this.value = "";
this.plugin = plugin;
}
onOpen(): void {
super.onOpen();
this.titleEl.setText("Create CSS Snippet");
this.containerEl.addClass("css-editor-create-modal");
this.buildForm();
}
private buildForm() {
const textInput = new TextComponent(this.contentEl);
textInput.setPlaceholder("CSS snippet file name (ex: snippet.css)");
textInput.onChange((val) => (this.value = val));
textInput.inputEl.addEventListener("keydown", (evt) => {
this.handleKeydown(evt);
});
}
private async handleKeydown(evt: KeyboardEvent) {
if (evt.key === "Escape") {
this.close();
} else if (evt.key === "Enter") {
try {
await createSnippetFile(this.app, this.value, "");
await this.plugin.openCssEditorView(this.value);
this.app.customCss?.setCssEnabledStatus?.(
this.value.replace(".css", ""),
true
);
this.close();
} catch (err) {
if (err instanceof Error) {
new | ErrorNotice(err.message); |
} else {
new ErrorNotice("Failed to create file. Reason unknown.");
}
}
}
}
}
| src/modals/CssSnippetCreateModal.ts | Zachatoo-obsidian-css-editor-881a94e | [
{
"filename": "src/CssEditorView.ts",
"retrieved_chunk": "\t\tsuper(leaf);\n\t\tthis.navigation = true;\n\t\tthis.editor = new EditorView({\n\t\t\tparent: this.contentEl,\n\t\t\textensions: [\n\t\t\t\tbasicExtensions,\n\t\t\t\tthis.app.vault.getConfig?.(\"vimMode\") ? vim() : [],\n\t\t\t\tEditorView.updateListener.of((update) => {\n\t\t\t\t\tif (update.docChanged) {\n\t\t\t\t\t\tthis.requestSave(update.state.doc.toString());",
"score": 0.7814133763313293
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\t\titem\n\t\t\t\t\t);\n\t\t\t\t\tnew InfoNotice(`${item} was deleted.`);\n\t\t\t\t}).open();\n\t\t\t},\n\t\t});\n\t\tthis.registerView(VIEW_TYPE_CSS, (leaf) => new CssEditorView(leaf));\n\t}\n\tonunload() {}\n\tasync loadSettings() {",
"score": 0.7629684805870056
},
{
"filename": "src/CssEditorView.ts",
"retrieved_chunk": "\t\t\tthis.dispatchEditorData(data);\n\t\t\tthis.app.workspace.requestSaveLayout();\n\t\t}\n\t\tconst timer = window.setInterval(() => {\n\t\t\tthis.editor.focus();\n\t\t\tif (this.editor.hasFocus) clearInterval(timer);\n\t\t}, 200);\n\t\tthis.registerInterval(timer);\n\t}\n\tgetEditorData() {",
"score": 0.761377215385437
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\tthis.openCssEditorView\n\t\t\t\t).open();\n\t\t\t},\n\t\t});\n\t\tthis.addCommand({\n\t\t\tid: \"create-css-snippet\",\n\t\t\tname: \"Create CSS Snippet\",\n\t\t\tcallback: async () => {\n\t\t\t\tnew CssSnippetCreateModal(this.app, this).open();\n\t\t\t},",
"score": 0.7511588931083679
},
{
"filename": "src/modals/CssSnippetFuzzySuggestModal.ts",
"retrieved_chunk": "\t\tsuper.renderSuggestion(item, el);\n\t\tel.appendChild(\n\t\t\tcreateDiv({ cls: \"css-editor-suggestion-description\" }, (el) =>\n\t\t\t\tel.appendText(`${getSnippetDirectory(this.app)}${item.item}`)\n\t\t\t)\n\t\t);\n\t}\n\tonChooseItem(item: string, evt: MouseEvent | KeyboardEvent): void {\n\t\tthrow new Error(\"Method not implemented.\");\n\t}",
"score": 0.7457929849624634
}
] | typescript | ErrorNotice(err.message); |
import { Plugin } from "obsidian";
import { CssEditorView, VIEW_TYPE_CSS } from "./CssEditorView";
import { CssSnippetFuzzySuggestModal } from "./modals/CssSnippetFuzzySuggestModal";
import { CssSnippetCreateModal } from "./modals/CssSnippetCreateModal";
import { deleteSnippetFile } from "./file-system-helpers";
import { detachLeavesOfTypeAndDisplay, openView } from "./workspace-helpers";
import { InfoNotice } from "./Notice";
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface CssEditorPluginSettings {}
const DEFAULT_SETTINGS: CssEditorPluginSettings = {};
export default class CssEditorPlugin extends Plugin {
settings: CssEditorPluginSettings;
async onload() {
await this.loadSettings();
this.addCommand({
id: "edit-css-snippet",
name: "Edit CSS Snippet",
callback: async () => {
new CssSnippetFuzzySuggestModal(
this.app,
this.openCssEditorView
).open();
},
});
this.addCommand({
id: "create-css-snippet",
name: "Create CSS Snippet",
callback: async () => {
new CssSnippetCreateModal(this.app, this).open();
},
});
this.addCommand({
id: "delete-css-snippet",
name: "Delete CSS Snippet",
callback: async () => {
new CssSnippetFuzzySuggestModal(this.app, (item) => {
deleteSnippetFile(this.app, item);
detachLeavesOfTypeAndDisplay(
this.app.workspace,
VIEW_TYPE_CSS,
item
);
| new InfoNotice(`${item} was deleted.`); |
}).open();
},
});
this.registerView(VIEW_TYPE_CSS, (leaf) => new CssEditorView(leaf));
}
onunload() {}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
}
async saveSettings() {
await this.saveData(this.settings);
}
async openCssEditorView(filename: string) {
openView(this.app.workspace, VIEW_TYPE_CSS, { filename });
}
}
| src/main.ts | Zachatoo-obsidian-css-editor-881a94e | [
{
"filename": "src/modals/CssSnippetFuzzySuggestModal.ts",
"retrieved_chunk": "\t\tsuper.renderSuggestion(item, el);\n\t\tel.appendChild(\n\t\t\tcreateDiv({ cls: \"css-editor-suggestion-description\" }, (el) =>\n\t\t\t\tel.appendText(`${getSnippetDirectory(this.app)}${item.item}`)\n\t\t\t)\n\t\t);\n\t}\n\tonChooseItem(item: string, evt: MouseEvent | KeyboardEvent): void {\n\t\tthrow new Error(\"Method not implemented.\");\n\t}",
"score": 0.7429206371307373
},
{
"filename": "src/CssEditorView.ts",
"retrieved_chunk": "\t\tsuper(leaf);\n\t\tthis.navigation = true;\n\t\tthis.editor = new EditorView({\n\t\t\tparent: this.contentEl,\n\t\t\textensions: [\n\t\t\t\tbasicExtensions,\n\t\t\t\tthis.app.vault.getConfig?.(\"vimMode\") ? vim() : [],\n\t\t\t\tEditorView.updateListener.of((update) => {\n\t\t\t\t\tif (update.docChanged) {\n\t\t\t\t\t\tthis.requestSave(update.state.doc.toString());",
"score": 0.7161411643028259
},
{
"filename": "src/CssEditorView.ts",
"retrieved_chunk": "\t * You should almost always call `requestSave` instead of `save` to debounce the saving.\n\t */\n\tprivate async save(data: string): Promise<void> {\n\t\tif (this.filename) {\n\t\t\twriteSnippetFile(this.app, this.filename, data);\n\t\t}\n\t}\n\tasync onClose() {\n\t\tthis.editor.destroy();\n\t}",
"score": 0.7081226110458374
},
{
"filename": "src/modals/CssSnippetFuzzySuggestModal.ts",
"retrieved_chunk": "import { App, FuzzyMatch, FuzzySuggestModal } from \"obsidian\";\nimport { getSnippetDirectory } from \"../file-system-helpers\";\nexport class CssSnippetFuzzySuggestModal extends FuzzySuggestModal<string> {\n\tconstructor(\n\t\tapp: App,\n\t\tonChooseItem: (item: string, evt: MouseEvent | KeyboardEvent) => void\n\t) {\n\t\tsuper(app);\n\t\tthis.onChooseItem = onChooseItem;\n\t}",
"score": 0.7007461190223694
},
{
"filename": "src/modals/CssSnippetCreateModal.ts",
"retrieved_chunk": "\t\t\ttry {\n\t\t\t\tawait createSnippetFile(this.app, this.value, \"\");\n\t\t\t\tawait this.plugin.openCssEditorView(this.value);\n\t\t\t\tthis.app.customCss?.setCssEnabledStatus?.(\n\t\t\t\t\tthis.value.replace(\".css\", \"\"),\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t\tthis.close();\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof Error) {",
"score": 0.6962261199951172
}
] | typescript | new InfoNotice(`${item} was deleted.`); |
/**
* This module executes inside of electron's main process. You can start
* electron renderer process from here and communicate with the other processes
* through IPC.
*
* When running `npm run build` or `npm run build:main`, this file is compiled to
* `./src/main.js` using webpack. This gives us some performance wins.
*/
import path from 'path';
import { app, BrowserWindow, ipcMain, Menu, shell, Tray } from 'electron';
// import { autoUpdater } from 'electron-updater';
import logger from 'electron-log';
import { resolveHtmlPath } from './util';
import {
configureIpfs,
downloadIpfs,
ipfs,
ipfsDaemon,
ipfsIsInstalled,
ipfsIsRunning,
ipfsKill,
waitForIpfs,
} from './ipfs';
import {
configureFollower,
downloadFollower,
follower,
followerDaemon,
followerId,
followerIsInstalled,
followerKill,
followerPid,
} from './follower';
import { DAPPS, resolveDapp } from './dapps';
import { fetchPeers } from './peers';
import { SYNTHETIX_NODE_APP_CONFIG } from '../const';
import * as settings from './settings';
import http from 'http';
import { proxy } from './proxy';
logger.transports.file.level = 'info';
const isDebug =
process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';
// class AppUpdater {
// constructor() {
// log.transports.file.level = 'info';
// autoUpdater.logger = log;
// autoUpdater.checkForUpdatesAndNotify();
// }
// }
let tray: Tray | null = null;
let mainWindow: BrowserWindow | null = null;
if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support');
sourceMapSupport.install();
}
const RESOURCES_PATH = app.isPackaged
? path.join(process.resourcesPath, 'assets')
: path.join(__dirname, '../../assets');
const getAssetPath = (...paths: string[]): string => {
return path.join(RESOURCES_PATH, ...paths);
};
function updateContextMenu() {
const menu = generateMenuItems();
if (tray && !tray.isDestroyed()) {
tray.setContextMenu(
Menu.buildFromTemplate([
menu.app,
menu.autoStart,
menu.devTools,
menu.dock,
{ type: 'separator' },
...menu.dapps,
{ type: 'separator' },
menu.quit,
])
);
}
app.dock.setMenu(
Menu.buildFromTemplate([
menu.app,
menu.autoStart,
menu.devTools,
menu.tray,
{ type: 'separator' },
...menu.dapps,
])
);
}
function createWindow() {
mainWindow = new BrowserWindow({
show: true,
useContentSize: true,
center: true,
minWidth: 600,
minHeight: 470,
skipTaskbar: true,
fullscreen: false,
fullscreenable: false,
width: 600,
height: 470,
// frame: false,
icon: getAssetPath('icon.icns'),
webPreferences: {
preload: app.isPackaged
? path.join(__dirname, 'preload.js')
: path.join(__dirname, '../../.erb/dll/preload.js'),
},
});
if (isDebug) {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
mainWindow.loadURL(resolveHtmlPath('index.html'));
mainWindow.on('closed', () => {
mainWindow = null;
});
// Open urls in the user's browser
mainWindow.webContents.setWindowOpenHandler((edata) => {
shell.openExternal(edata.url);
return { action: 'deny' };
});
mainWindow.webContents.on('devtools-opened', updateContextMenu);
mainWindow.webContents.on('devtools-closed', updateContextMenu);
mainWindow.on('hide', updateContextMenu);
mainWindow.on('show', updateContextMenu);
// Remove this if your app does not use auto updates
// eslint-disable-next-line
// new AppUpdater();
}
function generateMenuItems() {
return {
app: {
label: mainWindow?.isVisible() ? 'Hide App' : 'Open App',
click: () => {
if (mainWindow?.isVisible()) {
mainWindow.hide();
if (mainWindow.webContents.isDevToolsOpened()) {
mainWindow.webContents.closeDevTools();
}
return;
}
if (!mainWindow) {
createWindow();
} else {
mainWindow.show();
}
updateContextMenu();
},
},
autoStart: {
label: app.getLoginItemSettings().openAtLogin
? 'Disable AutoStart'
: 'Enable AutoStart',
click: () => {
const settings = app.getLoginItemSettings();
settings.openAtLogin = !settings.openAtLogin;
app.setLoginItemSettings(settings);
updateContextMenu();
},
},
devTools: {
label:
mainWindow && mainWindow.webContents.isDevToolsOpened()
? 'Close DevTools'
: 'Open DevTools',
click: () => {
if (mainWindow) {
if (mainWindow.webContents.isDevToolsOpened()) {
mainWindow.webContents.closeDevTools();
} else {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
}
updateContextMenu();
},
},
dock: {
label: app.dock && app.dock.isVisible() ? 'Hide Dock' : 'Show Dock',
click: async () => {
if (app.dock) {
if (app.dock.isVisible()) {
await settings.set('dock', false);
app.dock.hide();
} else {
await settings.set('dock', true);
app.dock.show();
}
}
updateContextMenu();
},
},
tray: {
label: tray && !tray.isDestroyed() ? 'Hide Tray icon' : 'Show Tray icon',
click: async () => {
if (tray && !tray.isDestroyed()) {
await settings.set('tray', false);
tray.destroy();
} else {
await settings.set('tray', true);
createTray();
}
updateContextMenu();
},
},
separator: {
type: 'separator',
},
| dapps: DAPPS.map((dapp) => { |
return {
enabled: Boolean(dapp.url),
label: dapp.label,
click: () => shell.openExternal(`http://${dapp.id}.localhost:8888`),
};
}),
quit: {
label: 'Quit',
click: () => {
app.quit();
},
},
};
}
app.once('ready', async () => {
// Hide the app from the dock
if (app.dock && !(await settings.get('dock'))) {
app.dock.hide();
}
if (await settings.get('tray')) {
createTray();
}
updateContextMenu();
});
function createTray() {
// Create a Tray instance with the icon you want to use for the menu bar
tray = new Tray(getAssetPath('[email protected]'));
tray.on('mouse-down', (_event) => {
if (mainWindow?.isVisible()) {
mainWindow?.focus();
}
});
}
/**
* Add event listeners...
*/
app.on('window-all-closed', () => {
// Respect the OSX convention of having the application in memory even
// after all windows have been closed
if (process.platform !== 'darwin') {
app.quit();
}
});
app
.whenReady()
.then(() => {
createWindow();
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
})
.catch(logger.error);
ipcMain.handle('install-ipfs', downloadIpfs);
ipcMain.handle('install-follower', downloadFollower);
ipcMain.handle('ipfs-isInstalled', ipfsIsInstalled);
ipcMain.handle('follower-isInstalled', followerIsInstalled);
ipcMain.handle('ipfs-isRunning', ipfsIsRunning);
ipcMain.handle('follower-isRunning', followerPid);
ipcMain.handle('run-ipfs', async () => {
await configureIpfs();
await ipfsDaemon();
});
ipcMain.handle('run-follower', async () => {
await configureFollower();
await followerDaemon();
});
ipcMain.handle('ipfs-peers', () => ipfs('swarm peers'));
ipcMain.handle('ipfs-id', () => followerId());
ipcMain.handle('ipfs-repo-stat', () => ipfs('repo stat'));
ipcMain.handle('ipfs-stats-bw', () => ipfs('stats bw'));
ipcMain.handle('ipfs-follower-info', () => follower('synthetix info'));
app.on('will-quit', ipfsKill);
app.on('will-quit', followerKill);
downloadIpfs();
ipfsDaemon();
const ipfsCheck = setInterval(ipfsDaemon, 10_000);
app.on('will-quit', () => clearInterval(ipfsCheck));
downloadFollower();
followerDaemon();
const followerCheck = setInterval(followerDaemon, 10_000);
app.on('will-quit', () => clearInterval(followerCheck));
ipcMain.handle('dapps', async () => {
return DAPPS.map((dapp) => ({
...dapp,
url: dapp.url ? `http://${dapp.id}.localhost:8888` : null,
}));
});
ipcMain.handle('dapp', async (_event, id: string) => {
const dapp = DAPPS.find((dapp) => dapp.id === id);
return dapp && dapp.url ? `http://${dapp.id}.localhost:8888` : null;
});
async function resolveAllDapps() {
DAPPS.forEach((dapp) => resolveDapp(dapp).then(updateContextMenu));
}
const dappsResolver = setInterval(resolveAllDapps, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsResolver));
waitForIpfs().then(resolveAllDapps).catch(logger.error);
async function updateConfig() {
const config = JSON.parse(
await ipfs(`cat /ipns/${SYNTHETIX_NODE_APP_CONFIG}`)
);
logger.log('App config fetched', config);
if (config.dapps) {
const oldDapps = DAPPS.splice(0);
for (const dapp of config.dapps) {
const oldDapp = oldDapps.find((d) => d.id === dapp.id);
if (oldDapp) {
DAPPS.push(Object.assign({}, oldDapp, dapp));
} else {
DAPPS.push(dapp);
}
}
logger.log('Dapps updated', DAPPS);
await resolveAllDapps();
}
}
const dappsUpdater = setInterval(updateConfig, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsUpdater));
waitForIpfs().then(updateConfig).catch(logger.error);
ipcMain.handle('peers', async () => fetchPeers());
http
.createServer((req, res) => {
const id = `${req.headers.host}`.replace('.localhost:8888', '');
const dapp = DAPPS.find((dapp) => dapp.id === id);
if (dapp && dapp.url) {
req.headers.host = dapp.url;
proxy({ host: '127.0.0.1', port: 8080 }, req, res);
return;
}
res.writeHead(404);
res.end('Not found');
})
.listen(8888, '0.0.0.0');
| src/main/main.ts | Synthetixio-synthetix-node-6de6a58 | [
{
"filename": "src/renderer/Ipfs/usePeerId.ts",
"retrieved_chunk": " return '';\n }\n return id;\n },\n initialData: () => '',\n placeholderData: '',\n enabled: Boolean(ipcRenderer && isRunning),\n });\n}",
"score": 0.7956520318984985
},
{
"filename": "src/renderer/DApps/useDapp.ts",
"retrieved_chunk": " return url;\n },\n initialData: () => null,\n placeholderData: null,\n enabled: Boolean(ipcRenderer),\n });\n}",
"score": 0.790064811706543
},
{
"filename": "src/renderer/Ipfs/useStatsBw.ts",
"retrieved_chunk": " return '';\n }\n return stats;\n },\n initialData: () => '',\n placeholderData: '',\n enabled: Boolean(ipcRenderer && isRunning),\n });\n}",
"score": 0.7830246090888977
},
{
"filename": "src/renderer/Ipfs/useRepoStat.ts",
"retrieved_chunk": " return '';\n }\n return stats;\n },\n initialData: () => '',\n placeholderData: '',\n enabled: Boolean(ipcRenderer && isRunning),\n });\n}",
"score": 0.7830246090888977
},
{
"filename": "src/renderer/Ipfs/usePeers.ts",
"retrieved_chunk": " return [];\n }\n return peers;\n },\n initialData: () => [],\n placeholderData: [],\n enabled: Boolean(ipcRenderer && isRunning),\n refetchInterval: 30_000,\n refetchOnWindowFocus: true,\n });",
"score": 0.7767757773399353
}
] | typescript | dapps: DAPPS.map((dapp) => { |
import { exec, spawn } from 'child_process';
import https from 'https';
import { createReadStream, createWriteStream, promises as fs } from 'fs';
import { pipeline } from 'stream/promises';
import os from 'os';
import zlib from 'zlib';
import tar from 'tar';
import path from 'path';
import type { IpcMainInvokeEvent } from 'electron';
import logger from 'electron-log';
import { SYNTHETIX_IPNS } from '../const';
import { ROOT } from './settings';
import { getPid, getPidsSync } from './pid';
// Change if we ever want to store all follower info in a custom folder
const HOME = os.homedir();
const IPFS_FOLLOW_PATH = path.join(HOME, '.ipfs-cluster-follow');
export function followerKill() {
try {
getPidsSync('.synthetix/ipfs-cluster-follow/ipfs-cluster-follow').forEach(
(pid) => {
logger.log('Killing ipfs-cluster-follow', pid);
process.kill(pid);
}
);
} catch (_e) {
// whatever
}
}
export async function followerPid() {
return await getPid(
'.synthetix/ipfs-cluster-follow/ipfs-cluster-follow synthetix run'
);
}
export async function followerIsInstalled() {
try {
await fs.access(
path.join(ROOT, 'ipfs-cluster-follow/ipfs-cluster-follow'),
fs.constants.F_OK
);
return true;
} catch (_e) {
return false;
}
}
export async function followerDaemon() {
const isInstalled = await followerIsInstalled();
if (!isInstalled) {
return;
}
const pid = await getPid(
'.synthetix/ipfs-cluster-follow/ipfs-cluster-follow synthetix run'
);
if (!pid) {
await configureFollower();
try {
// Cleanup locks in case of a previous crash
await Promise.all([
fs.rm(path.join(IPFS_FOLLOW_PATH, 'synthetix/badger'), {
recursive: true,
force: true,
}),
fs.rm(path.join(IPFS_FOLLOW_PATH, 'synthetix/api-socket'), {
recursive: true,
force: true,
}),
]);
} catch (e) {
logger.error(e);
// whatever
}
spawn(
path.join(ROOT, 'ipfs-cluster-follow/ipfs-cluster-follow'),
['synthetix', 'run'],
{
stdio: 'inherit',
detached: true,
env: { HOME },
}
);
}
}
export async function follower(arg: string): Promise<string> {
return new Promise((resolve, reject) => {
exec(
`${path.join(ROOT, 'ipfs-cluster-follow/ipfs-cluster-follow')} ${arg}`,
{ encoding: 'utf8', env: { HOME } },
(error, stdout, stderr) => {
if (error) {
error.message = `${error.message} (${stderr})`;
reject(error);
} else {
resolve(stdout.trim());
}
}
);
});
}
export async function getLatestVersion(): Promise<string> {
return new Promise((resolve, reject) => {
https
.get('https://dist.ipfs.tech/ipfs-cluster-follow/versions', (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve(data.trim().split('\n').pop() || '');
});
})
.on('error', (err) => {
reject(err);
});
});
}
export async function getInstalledVersion() {
try {
const version = await follower('--version');
const [, , installedVersion] = version.split(' ');
return installedVersion;
} catch (_error) {
return null;
}
}
export async function downloadFollower(
_e?: IpcMainInvokeEvent,
{ log = logger.log } = {}
) {
const arch = os.arch();
const targetArch = arch === 'x64' ? 'amd64' : 'arm64';
log('Checking for existing ipfs-cluster-follow installation...');
const latestVersion = await getLatestVersion();
const latestVersionNumber = latestVersion.slice(1);
const installedVersion = await getInstalledVersion();
if (installedVersion === latestVersionNumber) {
log(
`ipfs-cluster-follow version ${installedVersion} is already installed.`
);
return;
}
if (installedVersion) {
log(
`Updating ipfs-cluster-follow from version ${installedVersion} to ${latestVersionNumber}`
);
} else {
log(`Installing ipfs-cluster-follow version ${latestVersionNumber}`);
}
const downloadUrl = `https://dist.ipfs.tech/ipfs-cluster-follow/${latestVersion}/ipfs-cluster-follow_${latestVersion}_darwin-${targetArch}.tar.gz`;
log(`ipfs-cluster-follow package: ${downloadUrl}`);
await fs.mkdir(ROOT, { recursive: true });
await new Promise((resolve, reject) => {
const file = createWriteStream(
path.join(ROOT, 'ipfs-cluster-follow.tar.gz')
);
https.get(downloadUrl, (response) =>
pipeline(response, file).then(resolve).catch(reject)
);
});
await new Promise((resolve, reject) => {
createReadStream(path.join(ROOT, 'ipfs-cluster-follow.tar.gz'))
.pipe(zlib.createGunzip())
.pipe(tar.extract({ cwd: ROOT }))
.on('error', reject)
.on('end', resolve);
});
const installedVersionCheck = await getInstalledVersion();
if (installedVersionCheck) {
log(
`ipfs-cluster-follow version ${installedVersionCheck} installed successfully.`
);
} else {
throw new Error('ipfs-cluster-follow installation failed.');
}
return installedVersionCheck;
}
export async function isConfigured() {
try {
const service = await fs.readFile(
path.join(IPFS_FOLLOW_PATH, 'synthetix/service.json'),
'utf8'
);
| return service.includes(SYNTHETIX_IPNS); |
} catch (_error) {
return false;
}
}
export async function followerId() {
try {
const identity = JSON.parse(
await fs.readFile(
path.join(IPFS_FOLLOW_PATH, 'synthetix/identity.json'),
'utf8'
)
);
return identity.id;
} catch (_error) {
return '';
}
}
export async function configureFollower({ log = logger.log } = {}) {
if (await isConfigured()) {
return;
}
try {
log(
await follower(
`synthetix init "http://127.0.0.1:8080/ipns/${SYNTHETIX_IPNS}"`
)
);
} catch (_error) {
// ignore
}
}
| src/main/follower.ts | Synthetixio-synthetix-node-6de6a58 | [
{
"filename": "src/main/settings.ts",
"retrieved_chunk": " return JSON.parse(\n await fs.readFile(path.join(ROOT, 'setting.json'), 'utf8')\n );\n } catch (_error) {\n return DEFAULTS;\n }\n}\nexport async function write(settings: typeof DEFAULTS) {\n try {\n await fs.writeFile(",
"score": 0.8371740579605103
},
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": " });\n}\nexport async function getInstalledVersion() {\n try {\n const ipfsVersion = await ipfs('--version');\n const [, , installedVersion] = ipfsVersion.split(' ');\n return installedVersion;\n } catch (_error) {\n return null;\n }",
"score": 0.7912448644638062
},
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": " if (installedVersionCheck) {\n log(`ipfs version ${installedVersionCheck} installed successfully.`);\n } else {\n throw new Error('IPFS installation failed.');\n }\n return installedVersionCheck;\n}\nexport async function configureIpfs({ log = logger.log } = {}) {\n try {\n log(await ipfs('init'));",
"score": 0.7868334054946899
},
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": " } catch (_e) {\n return false;\n }\n}\nexport async function ipfsDaemon() {\n const isInstalled = await ipfsIsInstalled();\n if (!isInstalled) {\n return;\n }\n const pid = await getPid('.synthetix/go-ipfs/ipfs daemon');",
"score": 0.7706640958786011
},
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": " if (!pid) {\n await configureIpfs();\n spawn(path.join(ROOT, 'go-ipfs/ipfs'), ['daemon'], {\n stdio: 'inherit',\n detached: true,\n env: { IPFS_PATH },\n });\n }\n}\nexport async function ipfs(arg: string): Promise<string> {",
"score": 0.7676147818565369
}
] | typescript | return service.includes(SYNTHETIX_IPNS); |
/**
* This module executes inside of electron's main process. You can start
* electron renderer process from here and communicate with the other processes
* through IPC.
*
* When running `npm run build` or `npm run build:main`, this file is compiled to
* `./src/main.js` using webpack. This gives us some performance wins.
*/
import path from 'path';
import { app, BrowserWindow, ipcMain, Menu, shell, Tray } from 'electron';
// import { autoUpdater } from 'electron-updater';
import logger from 'electron-log';
import { resolveHtmlPath } from './util';
import {
configureIpfs,
downloadIpfs,
ipfs,
ipfsDaemon,
ipfsIsInstalled,
ipfsIsRunning,
ipfsKill,
waitForIpfs,
} from './ipfs';
import {
configureFollower,
downloadFollower,
follower,
followerDaemon,
followerId,
followerIsInstalled,
followerKill,
followerPid,
} from './follower';
import { DAPPS, resolveDapp } from './dapps';
import { fetchPeers } from './peers';
import { SYNTHETIX_NODE_APP_CONFIG } from '../const';
import * as settings from './settings';
import http from 'http';
import { proxy } from './proxy';
logger.transports.file.level = 'info';
const isDebug =
process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';
// class AppUpdater {
// constructor() {
// log.transports.file.level = 'info';
// autoUpdater.logger = log;
// autoUpdater.checkForUpdatesAndNotify();
// }
// }
let tray: Tray | null = null;
let mainWindow: BrowserWindow | null = null;
if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support');
sourceMapSupport.install();
}
const RESOURCES_PATH = app.isPackaged
? path.join(process.resourcesPath, 'assets')
: path.join(__dirname, '../../assets');
const getAssetPath = (...paths: string[]): string => {
return path.join(RESOURCES_PATH, ...paths);
};
function updateContextMenu() {
const menu = generateMenuItems();
if (tray && !tray.isDestroyed()) {
tray.setContextMenu(
Menu.buildFromTemplate([
menu.app,
menu.autoStart,
menu.devTools,
menu.dock,
{ type: 'separator' },
...menu.dapps,
{ type: 'separator' },
menu.quit,
])
);
}
app.dock.setMenu(
Menu.buildFromTemplate([
menu.app,
menu.autoStart,
menu.devTools,
menu.tray,
{ type: 'separator' },
...menu.dapps,
])
);
}
function createWindow() {
mainWindow = new BrowserWindow({
show: true,
useContentSize: true,
center: true,
minWidth: 600,
minHeight: 470,
skipTaskbar: true,
fullscreen: false,
fullscreenable: false,
width: 600,
height: 470,
// frame: false,
icon: getAssetPath('icon.icns'),
webPreferences: {
preload: app.isPackaged
? path.join(__dirname, 'preload.js')
: path.join(__dirname, '../../.erb/dll/preload.js'),
},
});
if (isDebug) {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
mainWindow.loadURL(resolveHtmlPath('index.html'));
mainWindow.on('closed', () => {
mainWindow = null;
});
// Open urls in the user's browser
mainWindow.webContents.setWindowOpenHandler((edata) => {
shell.openExternal(edata.url);
return { action: 'deny' };
});
mainWindow.webContents.on('devtools-opened', updateContextMenu);
mainWindow.webContents.on('devtools-closed', updateContextMenu);
mainWindow.on('hide', updateContextMenu);
mainWindow.on('show', updateContextMenu);
// Remove this if your app does not use auto updates
// eslint-disable-next-line
// new AppUpdater();
}
function generateMenuItems() {
return {
app: {
label: mainWindow?.isVisible() ? 'Hide App' : 'Open App',
click: () => {
if (mainWindow?.isVisible()) {
mainWindow.hide();
if (mainWindow.webContents.isDevToolsOpened()) {
mainWindow.webContents.closeDevTools();
}
return;
}
if (!mainWindow) {
createWindow();
} else {
mainWindow.show();
}
updateContextMenu();
},
},
autoStart: {
label: app.getLoginItemSettings().openAtLogin
? 'Disable AutoStart'
: 'Enable AutoStart',
click: () => {
const settings = app.getLoginItemSettings();
settings.openAtLogin = !settings.openAtLogin;
app.setLoginItemSettings(settings);
updateContextMenu();
},
},
devTools: {
label:
mainWindow && mainWindow.webContents.isDevToolsOpened()
? 'Close DevTools'
: 'Open DevTools',
click: () => {
if (mainWindow) {
if (mainWindow.webContents.isDevToolsOpened()) {
mainWindow.webContents.closeDevTools();
} else {
mainWindow.webContents.openDevTools({ mode: 'detach' });
}
}
updateContextMenu();
},
},
dock: {
label: app.dock && app.dock.isVisible() ? 'Hide Dock' : 'Show Dock',
click: async () => {
if (app.dock) {
if (app.dock.isVisible()) {
await | settings.set('dock', false); |
app.dock.hide();
} else {
await settings.set('dock', true);
app.dock.show();
}
}
updateContextMenu();
},
},
tray: {
label: tray && !tray.isDestroyed() ? 'Hide Tray icon' : 'Show Tray icon',
click: async () => {
if (tray && !tray.isDestroyed()) {
await settings.set('tray', false);
tray.destroy();
} else {
await settings.set('tray', true);
createTray();
}
updateContextMenu();
},
},
separator: {
type: 'separator',
},
dapps: DAPPS.map((dapp) => {
return {
enabled: Boolean(dapp.url),
label: dapp.label,
click: () => shell.openExternal(`http://${dapp.id}.localhost:8888`),
};
}),
quit: {
label: 'Quit',
click: () => {
app.quit();
},
},
};
}
app.once('ready', async () => {
// Hide the app from the dock
if (app.dock && !(await settings.get('dock'))) {
app.dock.hide();
}
if (await settings.get('tray')) {
createTray();
}
updateContextMenu();
});
function createTray() {
// Create a Tray instance with the icon you want to use for the menu bar
tray = new Tray(getAssetPath('[email protected]'));
tray.on('mouse-down', (_event) => {
if (mainWindow?.isVisible()) {
mainWindow?.focus();
}
});
}
/**
* Add event listeners...
*/
app.on('window-all-closed', () => {
// Respect the OSX convention of having the application in memory even
// after all windows have been closed
if (process.platform !== 'darwin') {
app.quit();
}
});
app
.whenReady()
.then(() => {
createWindow();
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
})
.catch(logger.error);
ipcMain.handle('install-ipfs', downloadIpfs);
ipcMain.handle('install-follower', downloadFollower);
ipcMain.handle('ipfs-isInstalled', ipfsIsInstalled);
ipcMain.handle('follower-isInstalled', followerIsInstalled);
ipcMain.handle('ipfs-isRunning', ipfsIsRunning);
ipcMain.handle('follower-isRunning', followerPid);
ipcMain.handle('run-ipfs', async () => {
await configureIpfs();
await ipfsDaemon();
});
ipcMain.handle('run-follower', async () => {
await configureFollower();
await followerDaemon();
});
ipcMain.handle('ipfs-peers', () => ipfs('swarm peers'));
ipcMain.handle('ipfs-id', () => followerId());
ipcMain.handle('ipfs-repo-stat', () => ipfs('repo stat'));
ipcMain.handle('ipfs-stats-bw', () => ipfs('stats bw'));
ipcMain.handle('ipfs-follower-info', () => follower('synthetix info'));
app.on('will-quit', ipfsKill);
app.on('will-quit', followerKill);
downloadIpfs();
ipfsDaemon();
const ipfsCheck = setInterval(ipfsDaemon, 10_000);
app.on('will-quit', () => clearInterval(ipfsCheck));
downloadFollower();
followerDaemon();
const followerCheck = setInterval(followerDaemon, 10_000);
app.on('will-quit', () => clearInterval(followerCheck));
ipcMain.handle('dapps', async () => {
return DAPPS.map((dapp) => ({
...dapp,
url: dapp.url ? `http://${dapp.id}.localhost:8888` : null,
}));
});
ipcMain.handle('dapp', async (_event, id: string) => {
const dapp = DAPPS.find((dapp) => dapp.id === id);
return dapp && dapp.url ? `http://${dapp.id}.localhost:8888` : null;
});
async function resolveAllDapps() {
DAPPS.forEach((dapp) => resolveDapp(dapp).then(updateContextMenu));
}
const dappsResolver = setInterval(resolveAllDapps, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsResolver));
waitForIpfs().then(resolveAllDapps).catch(logger.error);
async function updateConfig() {
const config = JSON.parse(
await ipfs(`cat /ipns/${SYNTHETIX_NODE_APP_CONFIG}`)
);
logger.log('App config fetched', config);
if (config.dapps) {
const oldDapps = DAPPS.splice(0);
for (const dapp of config.dapps) {
const oldDapp = oldDapps.find((d) => d.id === dapp.id);
if (oldDapp) {
DAPPS.push(Object.assign({}, oldDapp, dapp));
} else {
DAPPS.push(dapp);
}
}
logger.log('Dapps updated', DAPPS);
await resolveAllDapps();
}
}
const dappsUpdater = setInterval(updateConfig, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsUpdater));
waitForIpfs().then(updateConfig).catch(logger.error);
ipcMain.handle('peers', async () => fetchPeers());
http
.createServer((req, res) => {
const id = `${req.headers.host}`.replace('.localhost:8888', '');
const dapp = DAPPS.find((dapp) => dapp.id === id);
if (dapp && dapp.url) {
req.headers.host = dapp.url;
proxy({ host: '127.0.0.1', port: 8080 }, req, res);
return;
}
res.writeHead(404);
res.end('Not found');
})
.listen(8888, '0.0.0.0');
| src/main/main.ts | Synthetixio-synthetix-node-6de6a58 | [
{
"filename": "src/renderer/DApps/useDapp.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nconst { ipcRenderer } = window?.electron || {};\nexport function useDapp(id: string) {\n return useQuery({\n queryKey: ['dapp', id],\n queryFn: async () => {\n const url = await ipcRenderer.invoke('dapp', id);\n if (!url) {\n return null;\n }",
"score": 0.747282862663269
},
{
"filename": "src/renderer/Ipfs/useIsFollowerInstalled.ts",
"retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nconst { ipcRenderer } = window?.electron || {};\nexport function useIsFollowerInstalled() {\n return useQuery({\n queryKey: ['follower', 'isInstalled'],\n queryFn: () => ipcRenderer.invoke('follower-isInstalled'),\n initialData: () => false,\n placeholderData: false,\n enabled: Boolean(ipcRenderer),\n });",
"score": 0.7335823178291321
},
{
"filename": "src/renderer/Ipfs/useFollowerInfo.ts",
"retrieved_chunk": " ipfs: state?.includes('IPFS peer online: true'),\n cluster: state?.includes('Cluster Peer online: true'),\n };\n },\n initialData: () => ({\n ipfs: false,\n cluster: false,\n }),\n placeholderData: {\n ipfs: false,",
"score": 0.7303717136383057
},
{
"filename": "src/renderer/Ipfs/usePeerId.ts",
"retrieved_chunk": " return '';\n }\n return id;\n },\n initialData: () => '',\n placeholderData: '',\n enabled: Boolean(ipcRenderer && isRunning),\n });\n}",
"score": 0.7249683141708374
},
{
"filename": "src/renderer/Ipfs/usePeers.ts",
"retrieved_chunk": " return [];\n }\n return peers;\n },\n initialData: () => [],\n placeholderData: [],\n enabled: Boolean(ipcRenderer && isRunning),\n refetchInterval: 30_000,\n refetchOnWindowFocus: true,\n });",
"score": 0.7218196988105774
}
] | typescript | settings.set('dock', false); |
import logger from 'electron-log';
import fetch from 'node-fetch';
import { createPublicClient, http } from 'viem';
import { mainnet } from 'viem/chains';
import { namehash, normalize } from 'viem/ens';
// @ts-ignore
import * as contentHash from '@ensdomains/content-hash';
import { ipfs } from './ipfs';
import { getPid } from './pid';
import { DappType } from '../config';
Object.assign(global, { fetch });
export const DAPPS: DappType[] = [];
const client = createPublicClient({
chain: mainnet,
transport: http(),
});
const resolverAbi = [
{
constant: true,
inputs: [{ internalType: 'bytes32', name: 'node', type: 'bytes32' }],
name: 'contenthash',
outputs: [{ internalType: 'bytes', name: '', type: 'bytes' }],
payable: false,
stateMutability: 'view',
type: 'function',
},
];
export async function resolveEns(
dapp: DappType
): Promise<{ codec: string; hash: string }> {
if (dapp.ipns) {
return {
codec: 'ipns-ns',
hash: dapp.ipns,
};
}
if (!dapp.ens) {
throw new Error('Neither ipns nor ens was set, cannot resolve');
}
const name = normalize(dapp.ens);
const resolverAddress = await client.getEnsResolver({ name });
const hash = await client.readContract({
address: resolverAddress,
abi: resolverAbi,
functionName: 'contenthash',
args: [namehash(name)],
});
const codec = contentHash.getCodec(hash);
return {
codec,
hash: contentHash.decode(hash),
};
}
export async function resolveQm(ipns: string): Promise<string> {
| const ipfsPath = await ipfs(`resolve /ipns/${ipns}`); |
const qm = ipfsPath.slice(6); // remove /ipfs/
return qm; // Qm
}
export async function convertCid(qm: string): Promise<string> {
return await ipfs(`cid base32 ${qm}`);
}
export async function isPinned(qm: string): Promise<boolean> {
try {
const result = await ipfs(`pin ls --type recursive ${qm}`);
return result.includes(qm);
} catch (e) {
return false;
}
}
export async function resolveDapp(dapp: DappType): Promise<void> {
try {
const { codec, hash } = await resolveEns(dapp);
logger.log(dapp.id, 'resolved', codec, hash);
const qm =
codec === 'ipns-ns'
? await resolveQm(hash)
: codec === 'ipfs-ns'
? hash
: undefined;
if (qm) {
Object.assign(dapp, { qm });
}
if (qm !== hash) {
logger.log(dapp.id, 'resolved CID', qm);
}
if (!qm) {
throw new Error(`Codec "${codec}" not supported`);
}
if (await getPid(`pin add --progress ${qm}`)) {
logger.log(dapp.id, 'pinning already in progres...');
return;
}
const isDappPinned = await isPinned(qm);
if (!isDappPinned) {
logger.log(dapp.id, 'pinning...', qm);
await ipfs(`pin add --progress ${qm}`);
}
const bafy = await convertCid(qm);
Object.assign(dapp, { bafy });
const url = `${bafy}.ipfs.localhost`;
Object.assign(dapp, { url });
logger.log(dapp.id, 'local IPFS host:', url);
} catch (e) {
logger.error(e);
return;
}
}
export async function cleanupOldDapps() {
const hashes = DAPPS.map((dapp) => dapp.qm);
logger.log('Current DAPPs hashes', hashes);
if (hashes.length < 1 || hashes.some((hash) => !hash)) {
// We only want to cleanup when all the dapps aer resolved
return;
}
try {
const pins = JSON.parse(await ipfs('pin ls --enc=json --type=recursive'));
const pinnedHashes = Object.keys(pins.Keys);
logger.log('Existing IPFS pins', pinnedHashes);
const toUnpin = pinnedHashes.filter((hash) => !hashes.includes(hash));
logger.log('Hashes to unpin', toUnpin);
if (toUnpin.length > 0) {
for (const hash of toUnpin) {
logger.log(`Unpinning ${hash}`);
await ipfs(`pin rm ${hash}`);
}
const pinsAfter = JSON.parse(
await ipfs('pin ls --enc=json --type=recursive')
);
logger.log('Updated IPFS pins', pinsAfter);
// Clenup the repo
await ipfs('repo gc');
}
} catch (e) {
// do nothing
}
}
| src/main/dapps.ts | Synthetixio-synthetix-node-6de6a58 | [
{
"filename": "src/main/follower.ts",
"retrieved_chunk": " throw new Error('ipfs-cluster-follow installation failed.');\n }\n return installedVersionCheck;\n}\nexport async function isConfigured() {\n try {\n const service = await fs.readFile(\n path.join(IPFS_FOLLOW_PATH, 'synthetix/service.json'),\n 'utf8'\n );",
"score": 0.761886477470398
},
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": " }\n }\n );\n });\n}\nexport async function getLatestVersion(): Promise<string> {\n return new Promise((resolve, reject) => {\n https\n .get('https://dist.ipfs.tech/go-ipfs/versions', (res) => {\n let data = '';",
"score": 0.754435658454895
},
{
"filename": "src/main/peers.ts",
"retrieved_chunk": "import logger from 'electron-log';\nimport fetch from 'node-fetch';\nObject.assign(global, { fetch });\nexport type Peer = {\n id: string;\n version: string;\n};\nexport async function fetchPeers(): Promise<Peer[]> {\n try {\n const response = await fetch('https://ipfs.synthetix.io/dash/api');",
"score": 0.7523232698440552
},
{
"filename": "src/main/follower.ts",
"retrieved_chunk": " return service.includes(SYNTHETIX_IPNS);\n } catch (_error) {\n return false;\n }\n}\nexport async function followerId() {\n try {\n const identity = JSON.parse(\n await fs.readFile(\n path.join(IPFS_FOLLOW_PATH, 'synthetix/identity.json'),",
"score": 0.7485586404800415
},
{
"filename": "src/main/ipfs.ts",
"retrieved_chunk": " // log(await ipfs('config profile apply lowpower'));\n } catch (_error) {\n // whatever\n }\n}\nexport async function ipfsIsRunning() {\n return new Promise((resolve, _reject) => {\n http\n .get('http://127.0.0.1:5001', (res) => {\n const { statusCode } = res;",
"score": 0.7347482442855835
}
] | typescript | const ipfsPath = await ipfs(`resolve /ipns/${ipns}`); |
import { debounce, ItemView, ViewStateResult, WorkspaceLeaf } from "obsidian";
import { EditorView } from "@codemirror/view";
import { vim } from "@replit/codemirror-vim";
import { readSnippetFile, writeSnippetFile } from "./file-system-helpers";
import { basicExtensions } from "./codemirror-extensions/basic-extensions";
export const VIEW_TYPE_CSS = "css-editor-view";
export class CssEditorView extends ItemView {
private editor: EditorView;
private filename: string;
constructor(leaf: WorkspaceLeaf) {
super(leaf);
this.navigation = true;
this.editor = new EditorView({
parent: this.contentEl,
extensions: [
basicExtensions,
this.app.vault.getConfig?.("vimMode") ? vim() : [],
EditorView.updateListener.of((update) => {
if (update.docChanged) {
this.requestSave(update.state.doc.toString());
}
}),
],
});
this.filename = "";
}
getViewType() {
return VIEW_TYPE_CSS;
}
getIcon() {
return "file-code";
}
getDisplayText(): string {
return this.filename;
}
async onOpen(): Promise<void> {
const filename = this.getState()?.filename;
if (filename) {
this.filename = filename;
| const data = await readSnippetFile(this.app, filename); |
this.dispatchEditorData(data);
this.app.workspace.requestSaveLayout();
}
const timer = window.setInterval(() => {
this.editor.focus();
if (this.editor.hasFocus) clearInterval(timer);
}, 200);
this.registerInterval(timer);
}
getEditorData() {
return this.editor.state.doc.toString();
}
private dispatchEditorData(data: string) {
this.editor.dispatch({
changes: {
from: 0,
to: this.editor.state.doc.length,
insert: data,
},
});
}
getState() {
return {
filename: this.filename,
};
}
async setState(
state: { filename: string },
result: ViewStateResult
): Promise<void> {
if (state && typeof state === "object") {
if (
"filename" in state &&
state.filename &&
typeof state.filename === "string"
) {
if (state.filename !== this.filename) {
const data = await readSnippetFile(
this.app,
state.filename
);
this.dispatchEditorData(data);
}
this.filename = state.filename;
}
}
super.setState(state, result);
}
requestSave = debounce(this.save, 1000);
/**
* You should almost always call `requestSave` instead of `save` to debounce the saving.
*/
private async save(data: string): Promise<void> {
if (this.filename) {
writeSnippetFile(this.app, this.filename, data);
}
}
async onClose() {
this.editor.destroy();
}
}
| src/CssEditorView.ts | Zachatoo-obsidian-css-editor-881a94e | [
{
"filename": "src/file-system-helpers.ts",
"retrieved_chunk": "\t);\n\treturn data;\n}\nexport async function createSnippetFile(\n\tapp: App,\n\tfileName: string,\n\tdata = \"\"\n): Promise<void> {\n\tawait _validateFilename(fileName);\n\tawait _createSnippetDirectoryIfNotExists(app);",
"score": 0.8007404804229736
},
{
"filename": "src/file-system-helpers.ts",
"retrieved_chunk": "import { App } from \"obsidian\";\nexport function getSnippetDirectory(app: App) {\n\treturn `${app.vault.configDir}/snippets/`;\n}\nexport async function readSnippetFile(\n\tapp: App,\n\tfileName: string\n): Promise<string> {\n\tconst data = await app.vault.adapter.read(\n\t\t`${getSnippetDirectory(app)}${fileName}`",
"score": 0.7821075916290283
},
{
"filename": "src/modals/CssSnippetFuzzySuggestModal.ts",
"retrieved_chunk": "\tgetItems(): string[] {\n\t\tif (this.app.customCss?.snippets) {\n\t\t\treturn this.app.customCss.snippets.map((x) => `${x}.css`);\n\t\t}\n\t\treturn [];\n\t}\n\tgetItemText(item: string): string {\n\t\treturn item;\n\t}\n\trenderSuggestion(item: FuzzyMatch<string>, el: HTMLElement): void {",
"score": 0.7763383388519287
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\tthis.settings = Object.assign(\n\t\t\t{},\n\t\t\tDEFAULT_SETTINGS,\n\t\t\tawait this.loadData()\n\t\t);\n\t}\n\tasync saveSettings() {\n\t\tawait this.saveData(this.settings);\n\t}\n\tasync openCssEditorView(filename: string) {",
"score": 0.7740446329116821
},
{
"filename": "src/modals/CssSnippetCreateModal.ts",
"retrieved_chunk": "\t\t\ttry {\n\t\t\t\tawait createSnippetFile(this.app, this.value, \"\");\n\t\t\t\tawait this.plugin.openCssEditorView(this.value);\n\t\t\t\tthis.app.customCss?.setCssEnabledStatus?.(\n\t\t\t\t\tthis.value.replace(\".css\", \"\"),\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t\tthis.close();\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof Error) {",
"score": 0.7493770718574524
}
] | typescript | const data = await readSnippetFile(this.app, filename); |
import { Plugin } from "obsidian";
import { CssEditorView, VIEW_TYPE_CSS } from "./CssEditorView";
import { CssSnippetFuzzySuggestModal } from "./modals/CssSnippetFuzzySuggestModal";
import { CssSnippetCreateModal } from "./modals/CssSnippetCreateModal";
import { deleteSnippetFile } from "./file-system-helpers";
import { detachLeavesOfTypeAndDisplay, openView } from "./workspace-helpers";
import { InfoNotice } from "./Notice";
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface CssEditorPluginSettings {}
const DEFAULT_SETTINGS: CssEditorPluginSettings = {};
export default class CssEditorPlugin extends Plugin {
settings: CssEditorPluginSettings;
async onload() {
await this.loadSettings();
this.addCommand({
id: "edit-css-snippet",
name: "Edit CSS Snippet",
callback: async () => {
new CssSnippetFuzzySuggestModal(
this.app,
this.openCssEditorView
).open();
},
});
this.addCommand({
id: "create-css-snippet",
name: "Create CSS Snippet",
callback: async () => {
new CssSnippetCreateModal(this.app, this).open();
},
});
this.addCommand({
id: "delete-css-snippet",
name: "Delete CSS Snippet",
callback: async () => {
new CssSnippetFuzzySuggestModal(this.app, (item) => {
deleteSnippetFile(this.app, item);
detachLeavesOfTypeAndDisplay(
this.app.workspace,
VIEW_TYPE_CSS,
item
);
new | InfoNotice(`${item} was deleted.`); |
}).open();
},
});
this.registerView(VIEW_TYPE_CSS, (leaf) => new CssEditorView(leaf));
}
onunload() {}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
}
async saveSettings() {
await this.saveData(this.settings);
}
async openCssEditorView(filename: string) {
openView(this.app.workspace, VIEW_TYPE_CSS, { filename });
}
}
| src/main.ts | Zachatoo-obsidian-css-editor-881a94e | [
{
"filename": "src/modals/CssSnippetFuzzySuggestModal.ts",
"retrieved_chunk": "\t\tsuper.renderSuggestion(item, el);\n\t\tel.appendChild(\n\t\t\tcreateDiv({ cls: \"css-editor-suggestion-description\" }, (el) =>\n\t\t\t\tel.appendText(`${getSnippetDirectory(this.app)}${item.item}`)\n\t\t\t)\n\t\t);\n\t}\n\tonChooseItem(item: string, evt: MouseEvent | KeyboardEvent): void {\n\t\tthrow new Error(\"Method not implemented.\");\n\t}",
"score": 0.7457647919654846
},
{
"filename": "src/CssEditorView.ts",
"retrieved_chunk": "\t\tsuper(leaf);\n\t\tthis.navigation = true;\n\t\tthis.editor = new EditorView({\n\t\t\tparent: this.contentEl,\n\t\t\textensions: [\n\t\t\t\tbasicExtensions,\n\t\t\t\tthis.app.vault.getConfig?.(\"vimMode\") ? vim() : [],\n\t\t\t\tEditorView.updateListener.of((update) => {\n\t\t\t\t\tif (update.docChanged) {\n\t\t\t\t\t\tthis.requestSave(update.state.doc.toString());",
"score": 0.7203580737113953
},
{
"filename": "src/modals/CssSnippetCreateModal.ts",
"retrieved_chunk": "\t\t\ttry {\n\t\t\t\tawait createSnippetFile(this.app, this.value, \"\");\n\t\t\t\tawait this.plugin.openCssEditorView(this.value);\n\t\t\t\tthis.app.customCss?.setCssEnabledStatus?.(\n\t\t\t\t\tthis.value.replace(\".css\", \"\"),\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t\tthis.close();\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof Error) {",
"score": 0.7120559215545654
},
{
"filename": "src/CssEditorView.ts",
"retrieved_chunk": "\t * You should almost always call `requestSave` instead of `save` to debounce the saving.\n\t */\n\tprivate async save(data: string): Promise<void> {\n\t\tif (this.filename) {\n\t\t\twriteSnippetFile(this.app, this.filename, data);\n\t\t}\n\t}\n\tasync onClose() {\n\t\tthis.editor.destroy();\n\t}",
"score": 0.6939359307289124
},
{
"filename": "src/modals/CssSnippetFuzzySuggestModal.ts",
"retrieved_chunk": "import { App, FuzzyMatch, FuzzySuggestModal } from \"obsidian\";\nimport { getSnippetDirectory } from \"../file-system-helpers\";\nexport class CssSnippetFuzzySuggestModal extends FuzzySuggestModal<string> {\n\tconstructor(\n\t\tapp: App,\n\t\tonChooseItem: (item: string, evt: MouseEvent | KeyboardEvent) => void\n\t) {\n\t\tsuper(app);\n\t\tthis.onChooseItem = onChooseItem;\n\t}",
"score": 0.6924200654029846
}
] | typescript | InfoNotice(`${item} was deleted.`); |
/* eslint-disable @typescript-eslint/no-misused-promises */
import { type NextPage } from "next";
import dynamic from "next/dynamic";
import Head from "next/head";
import Image from "next/image";
import { type TryChar, useIPScanner } from "~/hooks/useIPScanner";
import { download } from "~/helpers/download";
import {
TableCellsIcon,
DocumentTextIcon,
ArrowPathRoundedSquareIcon,
MagnifyingGlassCircleIcon,
PlayIcon,
StopIcon,
} from "@heroicons/react/24/solid";
import { copyIPToClipboard } from "~/helpers/copyIPToClipboard";
import { allIps } from "~/consts";
import { useUserIPInfo } from "~/hooks/useUserIPInfo";
const UserIP = dynamic(() => import("~/components/UserIP"), { ssr: false });
const Home: NextPage = () => {
const { ipInfo } = useUserIPInfo();
const {
startScan,
stopScan,
color,
currentIP,
currentLatency,
ipRegex,
maxIPCount,
maxLatency,
scanState,
testNo,
tryChar,
validIPs,
setSettings,
} = useIPScanner({ allIps });
const isRunning = scanState !== "idle";
const tryCharToRotation: Record<TryChar, string> = {
"": "rotate-[360deg]",
"|": "rotate-[72deg]",
"/": "rotate-[144deg]",
"-": "rotate-[216deg]",
"\\": "rotate-[288deg]",
};
return (
<>
<Head>
<title>Cloudflare Scanner</title>
<meta
name="description"
content="Cloudflare Scanner to find clean ip"
/>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="flex h-full max-w-full flex-col items-center justify-center bg-gradient-to-b from-cyan-300 to-cyan-400 px-3">
<div className="max-h-full w-[900px] max-w-full rounded-lg bg-slate-200 p-5 text-gray-700 shadow-lg">
<section className="flex flex-col items-center border-b-4 border-cyan-600">
<div className="w-full border-b-4 border-cyan-600 py-4 text-center">
<h1 className="text-3xl font-bold text-cyan-900">
Cloudflare Clean IP Scanner{" "}
<MagnifyingGlassCircleIcon className="mb-2 inline-block h-10 w-10" />
</h1>
</div>
<div className="flex w-full flex-col items-center justify-center py-4 md:flex-row">
<div className="mb-4 flex w-full items-center justify-center px-2 md:mb-0 md:w-1/2">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Max Count:
<input
type="number"
id="max-ip"
value={maxIPCount}
onChange={(e) =>
setSettings({ maxIPCount: e.target.valueAsNumber })
}
disabled={isRunning}
min={1}
max={500}
className="ml-2 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
<div className="flex w-full items-center justify-center px-2 md:w-1/2">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Maximum Delay:
<input
type="number"
id="max-latency"
value={maxLatency}
disabled={isRunning}
onChange={(e) =>
setSettings({ maxLatency: e.target.valueAsNumber })
}
min={150}
max={3000}
step={50}
className="ml-2 w-16 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
</div>
<div className="flex w-full items-center justify-center py-4">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Regex for IP:
<input
type="text"
value={ipRegex}
onChange={(e) => setSettings({ ipRegex: e.target.value })}
disabled={isRunning}
id="ip-regex"
placeholder="^104\.17\.|^141\."
className="ml-2 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
<div className="h-16">
<UserIP
ip={ipInfo.ipAddress}
location={
ipInfo.ipVersion === 4
? ipInfo.regionName + ", " + ipInfo.countryName
: "..."
}
/>
</div>
<div className="flex w-full flex-col items-center justify-around py-4 md:w-1/2 md:flex-row">
{!isRunning ? (
<button
className="rounded bg-cyan-500 px-4 py-2 font-bold text-white outline-cyan-700 transition-colors duration-300 hover:bg-cyan-600 disabled:cursor-not-allowed disabled:bg-gray-700 disabled:outline-white disabled:hover:bg-gray-800"
onClick={startScan}
>
Start Scan{" "}
<PlayIcon className="inline-block h-6 w-6 pb-0.5" />
</button>
) : (
<button
className="rounded bg-cyan-500 px-4 py-2 font-bold text-white outline-cyan-700 transition-colors duration-300 hover:bg-cyan-600 disabled:cursor-not-allowed disabled:bg-gray-700 disabled:outline-white disabled:hover:bg-gray-800"
type="button"
onClick={stopScan}
disabled={scanState === "stopping"}
>
Stop Scan <StopIcon className="inline-block h-6 w-6 pb-0.5" />
</button>
)}
</div>
</section>
<section className="my-4 grid grid-cols-1 gap-5 md:grid-cols-3">
<div className="text-center text-red-500">
Notice: Please turn off your vpn!
</div>
<div className="text-center font-bold">Test No: {testNo}</div>
<div
className={`${
color === "red" ? "text-red-500" : "text-green-500"
} text-center`}
>
{currentIP || "0.0.0.0"}
</div>
<div className="flex items-center justify-center md:col-span-3">
<ArrowPathRoundedSquareIcon
className={`mx-2 inline-block h-6 w-6 transform-gpu text-center text-blue-600 duration-300 ${tryCharToRotation[tryChar]}`}
/>
<div className="mx-2 text-center">Latency: {currentLatency}</div>
<TableCellsIcon
| onClick={() => download(validIPs, "csv")} |
title="Download as CSV"
className={
(validIPs.length > 0
? "cursor-pointer text-blue-600 transition-colors duration-300 hover:text-blue-500 "
: "cursor-not-allowed text-gray-500 transition-colors duration-300 hover:text-gray-400 ") +
"mx-2 h-6 w-6"
}
/>
<DocumentTextIcon
onClick={() => download(validIPs, "json")}
title="Download as JSON"
className={
(validIPs.length > 0
? "cursor-pointer text-blue-600 transition-colors duration-300 hover:text-blue-500 "
: "cursor-not-allowed text-gray-500 transition-colors duration-300 hover:text-gray-400 ") +
"mx-2 h-6 w-6"
}
/>
</div>
</section>
<section className="h-40 max-h-40 overflow-y-scroll">
<table className="w-full">
<thead className=" ">
<tr>
<th className="sticky top-0 rounded-bl rounded-tl bg-cyan-300">
No #
</th>
<th className="sticky top-0 bg-cyan-300">IP</th>
<th className="sticky top-0 rounded-br rounded-tr bg-cyan-300">
Latency
</th>
</tr>
</thead>
<tbody>
{validIPs.map(({ ip, latency }, index) => (
<tr key={ip}>
<td className="text-center">{index + 1}</td>
<td
onClick={() => copyIPToClipboard(ip)}
className="cursor-pointer text-center transition-colors duration-200 hover:text-gray-500"
>
{ip}
</td>
<td className="text-center">{latency}</td>
</tr>
))}
</tbody>
</table>
</section>
</div>
<footer className="flex h-24 w-full items-center justify-center">
<a
className="flex items-center justify-center rounded bg-slate-100 p-3"
href="https://github.com/goldsrc/cloudflare-scanner"
target="_blank"
rel="noopener noreferrer"
>
Source on{" "}
<Image
src="/github.svg"
width={16}
height={16}
alt="Github Logo"
className="ml-2 h-4 w-4"
/>
</a>
</footer>
</main>
</>
);
};
export default Home;
| src/pages/index.tsx | goldsrc-cloudflare-scanner-ce66f4d | [
{
"filename": "src/components/UserIP/index.tsx",
"retrieved_chunk": "type Props = {\n ip: string;\n location: string;\n};\nconst UserIP = ({ ip, location }: Props) => {\n return (\n <div className=\"text-center\">\n <b>Your Current IP:</b>\n <p>{ip}</p>\n <p className=\"opacity-75\">{location}</p>",
"score": 0.6088360548019409
},
{
"filename": "src/pages/_app.tsx",
"retrieved_chunk": " <div className={`h-full ${inter.className}`}>\n <Component {...pageProps} />\n <Toaster />\n </div>\n </SWRConfig>\n );\n};\nexport default MyApp;",
"score": 0.5653260946273804
},
{
"filename": "src/pages/_app.tsx",
"retrieved_chunk": "import { type AppType } from \"next/dist/shared/lib/utils\";\nimport { Inter } from \"next/font/google\";\nimport \"~/styles/globals.css\";\nimport { Toaster } from \"react-hot-toast\";\nimport { SWRConfig } from \"swr\";\nimport { localStorageProvider } from \"~/swr/cacheProviders/localstorage\";\nconst inter = Inter({ subsets: [\"latin\"] });\nconst MyApp: AppType = ({ Component, pageProps }) => {\n return (\n <SWRConfig value={{ provider: localStorageProvider }}>",
"score": 0.5212305784225464
},
{
"filename": "src/helpers/download.ts",
"retrieved_chunk": " if (!arr.length) return;\n const blob = format === \"json\" ? createJSON(arr) : createCSV(arr);\n const url = URL.createObjectURL(blob);\n const link = document.createElement(\"a\");\n link.setAttribute(\"href\", url);\n link.setAttribute(\"download\", `ip-list.${format}`);\n link.style.display = \"none\";\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);",
"score": 0.4942132532596588
},
{
"filename": "src/helpers/download.ts",
"retrieved_chunk": " const keys = Object.keys(arr[0] as AcceptableObject);\n const csvHeader = keys.join(\",\");\n const csvContent = arr\n .map((el) => keys.map((key) => String(el[key] || \"\")).join(\",\"))\n .join(\"\\n\");\n const csvString = `${csvHeader}\\n${csvContent}`;\n const blob = new Blob([csvString], { type: \"text/csv\" });\n return blob;\n};\nexport function download(arr: AcceptableObject[], format: \"json\" | \"csv\") {",
"score": 0.4824020266532898
}
] | typescript | onClick={() => download(validIPs, "csv")} |
/* eslint-disable @typescript-eslint/no-misused-promises */
import { type NextPage } from "next";
import dynamic from "next/dynamic";
import Head from "next/head";
import Image from "next/image";
import { type TryChar, useIPScanner } from "~/hooks/useIPScanner";
import { download } from "~/helpers/download";
import {
TableCellsIcon,
DocumentTextIcon,
ArrowPathRoundedSquareIcon,
MagnifyingGlassCircleIcon,
PlayIcon,
StopIcon,
} from "@heroicons/react/24/solid";
import { copyIPToClipboard } from "~/helpers/copyIPToClipboard";
import { allIps } from "~/consts";
import { useUserIPInfo } from "~/hooks/useUserIPInfo";
const UserIP = dynamic(() => import("~/components/UserIP"), { ssr: false });
const Home: NextPage = () => {
const { ipInfo } = useUserIPInfo();
const {
startScan,
stopScan,
color,
currentIP,
currentLatency,
ipRegex,
maxIPCount,
maxLatency,
scanState,
testNo,
tryChar,
validIPs,
setSettings,
} = useIPScanner({ allIps });
const isRunning = scanState !== "idle";
const tryCharToRotation: Record<TryChar, string> = {
"": "rotate-[360deg]",
"|": "rotate-[72deg]",
"/": "rotate-[144deg]",
"-": "rotate-[216deg]",
"\\": "rotate-[288deg]",
};
return (
<>
<Head>
<title>Cloudflare Scanner</title>
<meta
name="description"
content="Cloudflare Scanner to find clean ip"
/>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="flex h-full max-w-full flex-col items-center justify-center bg-gradient-to-b from-cyan-300 to-cyan-400 px-3">
<div className="max-h-full w-[900px] max-w-full rounded-lg bg-slate-200 p-5 text-gray-700 shadow-lg">
<section className="flex flex-col items-center border-b-4 border-cyan-600">
<div className="w-full border-b-4 border-cyan-600 py-4 text-center">
<h1 className="text-3xl font-bold text-cyan-900">
Cloudflare Clean IP Scanner{" "}
<MagnifyingGlassCircleIcon className="mb-2 inline-block h-10 w-10" />
</h1>
</div>
<div className="flex w-full flex-col items-center justify-center py-4 md:flex-row">
<div className="mb-4 flex w-full items-center justify-center px-2 md:mb-0 md:w-1/2">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Max Count:
<input
type="number"
id="max-ip"
value={maxIPCount}
onChange={(e) =>
setSettings({ maxIPCount: e.target.valueAsNumber })
}
disabled={isRunning}
min={1}
max={500}
className="ml-2 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
<div className="flex w-full items-center justify-center px-2 md:w-1/2">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Maximum Delay:
<input
type="number"
id="max-latency"
value={maxLatency}
disabled={isRunning}
onChange={(e) =>
setSettings({ maxLatency: e.target.valueAsNumber })
}
min={150}
max={3000}
step={50}
className="ml-2 w-16 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
</div>
<div className="flex w-full items-center justify-center py-4">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Regex for IP:
<input
type="text"
value={ipRegex}
onChange={(e) => setSettings({ ipRegex: e.target.value })}
disabled={isRunning}
id="ip-regex"
placeholder="^104\.17\.|^141\."
className="ml-2 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
<div className="h-16">
<UserIP
ip={ipInfo.ipAddress}
location={
ipInfo.ipVersion === 4
? ipInfo.regionName + ", " + ipInfo.countryName
: "..."
}
/>
</div>
<div className="flex w-full flex-col items-center justify-around py-4 md:w-1/2 md:flex-row">
{!isRunning ? (
<button
className="rounded bg-cyan-500 px-4 py-2 font-bold text-white outline-cyan-700 transition-colors duration-300 hover:bg-cyan-600 disabled:cursor-not-allowed disabled:bg-gray-700 disabled:outline-white disabled:hover:bg-gray-800"
onClick={startScan}
>
Start Scan{" "}
<PlayIcon className="inline-block h-6 w-6 pb-0.5" />
</button>
) : (
<button
className="rounded bg-cyan-500 px-4 py-2 font-bold text-white outline-cyan-700 transition-colors duration-300 hover:bg-cyan-600 disabled:cursor-not-allowed disabled:bg-gray-700 disabled:outline-white disabled:hover:bg-gray-800"
type="button"
onClick={stopScan}
disabled={scanState === "stopping"}
>
Stop Scan <StopIcon className="inline-block h-6 w-6 pb-0.5" />
</button>
)}
</div>
</section>
<section className="my-4 grid grid-cols-1 gap-5 md:grid-cols-3">
<div className="text-center text-red-500">
Notice: Please turn off your vpn!
</div>
<div className="text-center font-bold">Test No: {testNo}</div>
<div
className={`${
color === "red" ? "text-red-500" : "text-green-500"
} text-center`}
>
{currentIP || "0.0.0.0"}
</div>
<div className="flex items-center justify-center md:col-span-3">
<ArrowPathRoundedSquareIcon
className={`mx-2 inline-block h-6 w-6 transform-gpu text-center text-blue-600 duration-300 ${tryCharToRotation[tryChar]}`}
/>
<div className="mx-2 text-center">Latency: {currentLatency}</div>
<TableCellsIcon
onClick={() | => download(validIPs, "csv")} |
title="Download as CSV"
className={
(validIPs.length > 0
? "cursor-pointer text-blue-600 transition-colors duration-300 hover:text-blue-500 "
: "cursor-not-allowed text-gray-500 transition-colors duration-300 hover:text-gray-400 ") +
"mx-2 h-6 w-6"
}
/>
<DocumentTextIcon
onClick={() => download(validIPs, "json")}
title="Download as JSON"
className={
(validIPs.length > 0
? "cursor-pointer text-blue-600 transition-colors duration-300 hover:text-blue-500 "
: "cursor-not-allowed text-gray-500 transition-colors duration-300 hover:text-gray-400 ") +
"mx-2 h-6 w-6"
}
/>
</div>
</section>
<section className="h-40 max-h-40 overflow-y-scroll">
<table className="w-full">
<thead className=" ">
<tr>
<th className="sticky top-0 rounded-bl rounded-tl bg-cyan-300">
No #
</th>
<th className="sticky top-0 bg-cyan-300">IP</th>
<th className="sticky top-0 rounded-br rounded-tr bg-cyan-300">
Latency
</th>
</tr>
</thead>
<tbody>
{validIPs.map(({ ip, latency }, index) => (
<tr key={ip}>
<td className="text-center">{index + 1}</td>
<td
onClick={() => copyIPToClipboard(ip)}
className="cursor-pointer text-center transition-colors duration-200 hover:text-gray-500"
>
{ip}
</td>
<td className="text-center">{latency}</td>
</tr>
))}
</tbody>
</table>
</section>
</div>
<footer className="flex h-24 w-full items-center justify-center">
<a
className="flex items-center justify-center rounded bg-slate-100 p-3"
href="https://github.com/goldsrc/cloudflare-scanner"
target="_blank"
rel="noopener noreferrer"
>
Source on{" "}
<Image
src="/github.svg"
width={16}
height={16}
alt="Github Logo"
className="ml-2 h-4 w-4"
/>
</a>
</footer>
</main>
</>
);
};
export default Home;
| src/pages/index.tsx | goldsrc-cloudflare-scanner-ce66f4d | [
{
"filename": "src/components/UserIP/index.tsx",
"retrieved_chunk": "type Props = {\n ip: string;\n location: string;\n};\nconst UserIP = ({ ip, location }: Props) => {\n return (\n <div className=\"text-center\">\n <b>Your Current IP:</b>\n <p>{ip}</p>\n <p className=\"opacity-75\">{location}</p>",
"score": 0.6069180369377136
},
{
"filename": "src/pages/_app.tsx",
"retrieved_chunk": " <div className={`h-full ${inter.className}`}>\n <Component {...pageProps} />\n <Toaster />\n </div>\n </SWRConfig>\n );\n};\nexport default MyApp;",
"score": 0.5730080604553223
},
{
"filename": "src/pages/_app.tsx",
"retrieved_chunk": "import { type AppType } from \"next/dist/shared/lib/utils\";\nimport { Inter } from \"next/font/google\";\nimport \"~/styles/globals.css\";\nimport { Toaster } from \"react-hot-toast\";\nimport { SWRConfig } from \"swr\";\nimport { localStorageProvider } from \"~/swr/cacheProviders/localstorage\";\nconst inter = Inter({ subsets: [\"latin\"] });\nconst MyApp: AppType = ({ Component, pageProps }) => {\n return (\n <SWRConfig value={{ provider: localStorageProvider }}>",
"score": 0.528096079826355
},
{
"filename": "src/helpers/download.ts",
"retrieved_chunk": " const keys = Object.keys(arr[0] as AcceptableObject);\n const csvHeader = keys.join(\",\");\n const csvContent = arr\n .map((el) => keys.map((key) => String(el[key] || \"\")).join(\",\"))\n .join(\"\\n\");\n const csvString = `${csvHeader}\\n${csvContent}`;\n const blob = new Blob([csvString], { type: \"text/csv\" });\n return blob;\n};\nexport function download(arr: AcceptableObject[], format: \"json\" | \"csv\") {",
"score": 0.48164594173431396
},
{
"filename": "src/helpers/download.ts",
"retrieved_chunk": " if (!arr.length) return;\n const blob = format === \"json\" ? createJSON(arr) : createCSV(arr);\n const url = URL.createObjectURL(blob);\n const link = document.createElement(\"a\");\n link.setAttribute(\"href\", url);\n link.setAttribute(\"download\", `ip-list.${format}`);\n link.style.display = \"none\";\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);",
"score": 0.47876864671707153
}
] | typescript | => download(validIPs, "csv")} |
import { Plugin } from "obsidian";
import { CssEditorView, VIEW_TYPE_CSS } from "./CssEditorView";
import { CssSnippetFuzzySuggestModal } from "./modals/CssSnippetFuzzySuggestModal";
import { CssSnippetCreateModal } from "./modals/CssSnippetCreateModal";
import { deleteSnippetFile } from "./file-system-helpers";
import { detachLeavesOfTypeAndDisplay, openView } from "./workspace-helpers";
import { InfoNotice } from "./Notice";
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface CssEditorPluginSettings {}
const DEFAULT_SETTINGS: CssEditorPluginSettings = {};
export default class CssEditorPlugin extends Plugin {
settings: CssEditorPluginSettings;
async onload() {
await this.loadSettings();
this.addCommand({
id: "edit-css-snippet",
name: "Edit CSS Snippet",
callback: async () => {
new CssSnippetFuzzySuggestModal(
this.app,
this.openCssEditorView
).open();
},
});
this.addCommand({
id: "create-css-snippet",
name: "Create CSS Snippet",
callback: async () => {
new CssSnippetCreateModal(this.app, this).open();
},
});
this.addCommand({
id: "delete-css-snippet",
name: "Delete CSS Snippet",
callback: async () => {
new CssSnippetFuzzySuggestModal(this.app, (item) => {
deleteSnippetFile(this.app, item);
detachLeavesOfTypeAndDisplay(
this.app.workspace,
VIEW_TYPE_CSS,
item
);
new InfoNotice(`${item} was deleted.`);
}).open();
},
});
| this.registerView(VIEW_TYPE_CSS, (leaf) => new CssEditorView(leaf)); |
}
onunload() {}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
}
async saveSettings() {
await this.saveData(this.settings);
}
async openCssEditorView(filename: string) {
openView(this.app.workspace, VIEW_TYPE_CSS, { filename });
}
}
| src/main.ts | Zachatoo-obsidian-css-editor-881a94e | [
{
"filename": "src/CssEditorView.ts",
"retrieved_chunk": "\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t],\n\t\t});\n\t\tthis.filename = \"\";\n\t}\n\tgetViewType() {\n\t\treturn VIEW_TYPE_CSS;\n\t}\n\tgetIcon() {",
"score": 0.747025728225708
},
{
"filename": "src/modals/CssSnippetFuzzySuggestModal.ts",
"retrieved_chunk": "\t\tsuper.renderSuggestion(item, el);\n\t\tel.appendChild(\n\t\t\tcreateDiv({ cls: \"css-editor-suggestion-description\" }, (el) =>\n\t\t\t\tel.appendText(`${getSnippetDirectory(this.app)}${item.item}`)\n\t\t\t)\n\t\t);\n\t}\n\tonChooseItem(item: string, evt: MouseEvent | KeyboardEvent): void {\n\t\tthrow new Error(\"Method not implemented.\");\n\t}",
"score": 0.7469028234481812
},
{
"filename": "src/modals/CssSnippetCreateModal.ts",
"retrieved_chunk": "\t\t\ttry {\n\t\t\t\tawait createSnippetFile(this.app, this.value, \"\");\n\t\t\t\tawait this.plugin.openCssEditorView(this.value);\n\t\t\t\tthis.app.customCss?.setCssEnabledStatus?.(\n\t\t\t\t\tthis.value.replace(\".css\", \"\"),\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t\tthis.close();\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof Error) {",
"score": 0.7269803285598755
},
{
"filename": "src/CssEditorView.ts",
"retrieved_chunk": "\t\tsuper(leaf);\n\t\tthis.navigation = true;\n\t\tthis.editor = new EditorView({\n\t\t\tparent: this.contentEl,\n\t\t\textensions: [\n\t\t\t\tbasicExtensions,\n\t\t\t\tthis.app.vault.getConfig?.(\"vimMode\") ? vim() : [],\n\t\t\t\tEditorView.updateListener.of((update) => {\n\t\t\t\t\tif (update.docChanged) {\n\t\t\t\t\t\tthis.requestSave(update.state.doc.toString());",
"score": 0.7116175889968872
},
{
"filename": "src/CssEditorView.ts",
"retrieved_chunk": "\t\t\t\t\t);\n\t\t\t\t\tthis.dispatchEditorData(data);\n\t\t\t\t}\n\t\t\t\tthis.filename = state.filename;\n\t\t\t}\n\t\t}\n\t\tsuper.setState(state, result);\n\t}\n\trequestSave = debounce(this.save, 1000);\n\t/**",
"score": 0.7051211595535278
}
] | typescript | this.registerView(VIEW_TYPE_CSS, (leaf) => new CssEditorView(leaf)); |
/* eslint-disable @typescript-eslint/no-misused-promises */
import { type NextPage } from "next";
import dynamic from "next/dynamic";
import Head from "next/head";
import Image from "next/image";
import { type TryChar, useIPScanner } from "~/hooks/useIPScanner";
import { download } from "~/helpers/download";
import {
TableCellsIcon,
DocumentTextIcon,
ArrowPathRoundedSquareIcon,
MagnifyingGlassCircleIcon,
PlayIcon,
StopIcon,
} from "@heroicons/react/24/solid";
import { copyIPToClipboard } from "~/helpers/copyIPToClipboard";
import { allIps } from "~/consts";
import { useUserIPInfo } from "~/hooks/useUserIPInfo";
const UserIP = dynamic(() => import("~/components/UserIP"), { ssr: false });
const Home: NextPage = () => {
const { ipInfo } = useUserIPInfo();
const {
startScan,
stopScan,
color,
currentIP,
currentLatency,
ipRegex,
maxIPCount,
maxLatency,
scanState,
testNo,
tryChar,
validIPs,
setSettings,
} = useIPScanner({ allIps });
const isRunning = scanState !== "idle";
const tryCharToRotation: Record<TryChar, string> = {
"": "rotate-[360deg]",
"|": "rotate-[72deg]",
"/": "rotate-[144deg]",
"-": "rotate-[216deg]",
"\\": "rotate-[288deg]",
};
return (
<>
<Head>
<title>Cloudflare Scanner</title>
<meta
name="description"
content="Cloudflare Scanner to find clean ip"
/>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="flex h-full max-w-full flex-col items-center justify-center bg-gradient-to-b from-cyan-300 to-cyan-400 px-3">
<div className="max-h-full w-[900px] max-w-full rounded-lg bg-slate-200 p-5 text-gray-700 shadow-lg">
<section className="flex flex-col items-center border-b-4 border-cyan-600">
<div className="w-full border-b-4 border-cyan-600 py-4 text-center">
<h1 className="text-3xl font-bold text-cyan-900">
Cloudflare Clean IP Scanner{" "}
<MagnifyingGlassCircleIcon className="mb-2 inline-block h-10 w-10" />
</h1>
</div>
<div className="flex w-full flex-col items-center justify-center py-4 md:flex-row">
<div className="mb-4 flex w-full items-center justify-center px-2 md:mb-0 md:w-1/2">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Max Count:
<input
type="number"
id="max-ip"
value={maxIPCount}
onChange={(e) =>
setSettings({ maxIPCount: e.target.valueAsNumber })
}
disabled={isRunning}
min={1}
max={500}
className="ml-2 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
<div className="flex w-full items-center justify-center px-2 md:w-1/2">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Maximum Delay:
<input
type="number"
id="max-latency"
value={maxLatency}
disabled={isRunning}
onChange={(e) =>
setSettings({ maxLatency: e.target.valueAsNumber })
}
min={150}
max={3000}
step={50}
className="ml-2 w-16 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
</div>
<div className="flex w-full items-center justify-center py-4">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Regex for IP:
<input
type="text"
value={ipRegex}
onChange={(e) => setSettings({ ipRegex: e.target.value })}
disabled={isRunning}
id="ip-regex"
placeholder="^104\.17\.|^141\."
className="ml-2 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
<div className="h-16">
<UserIP
ip={ipInfo.ipAddress}
location={
ipInfo.ipVersion === 4
? ipInfo.regionName + ", " + ipInfo.countryName
: "..."
}
/>
</div>
<div className="flex w-full flex-col items-center justify-around py-4 md:w-1/2 md:flex-row">
{!isRunning ? (
<button
className="rounded bg-cyan-500 px-4 py-2 font-bold text-white outline-cyan-700 transition-colors duration-300 hover:bg-cyan-600 disabled:cursor-not-allowed disabled:bg-gray-700 disabled:outline-white disabled:hover:bg-gray-800"
onClick={startScan}
>
Start Scan{" "}
<PlayIcon className="inline-block h-6 w-6 pb-0.5" />
</button>
) : (
<button
className="rounded bg-cyan-500 px-4 py-2 font-bold text-white outline-cyan-700 transition-colors duration-300 hover:bg-cyan-600 disabled:cursor-not-allowed disabled:bg-gray-700 disabled:outline-white disabled:hover:bg-gray-800"
type="button"
onClick={stopScan}
disabled={scanState === "stopping"}
>
Stop Scan <StopIcon className="inline-block h-6 w-6 pb-0.5" />
</button>
)}
</div>
</section>
<section className="my-4 grid grid-cols-1 gap-5 md:grid-cols-3">
<div className="text-center text-red-500">
Notice: Please turn off your vpn!
</div>
<div className="text-center font-bold">Test No: {testNo}</div>
<div
className={`${
color === "red" ? "text-red-500" : "text-green-500"
} text-center`}
>
{currentIP || "0.0.0.0"}
</div>
<div className="flex items-center justify-center md:col-span-3">
<ArrowPathRoundedSquareIcon
| className={`mx-2 inline-block h-6 w-6 transform-gpu text-center text-blue-600 duration-300 ${tryCharToRotation[tryChar]}`} |
/>
<div className="mx-2 text-center">Latency: {currentLatency}</div>
<TableCellsIcon
onClick={() => download(validIPs, "csv")}
title="Download as CSV"
className={
(validIPs.length > 0
? "cursor-pointer text-blue-600 transition-colors duration-300 hover:text-blue-500 "
: "cursor-not-allowed text-gray-500 transition-colors duration-300 hover:text-gray-400 ") +
"mx-2 h-6 w-6"
}
/>
<DocumentTextIcon
onClick={() => download(validIPs, "json")}
title="Download as JSON"
className={
(validIPs.length > 0
? "cursor-pointer text-blue-600 transition-colors duration-300 hover:text-blue-500 "
: "cursor-not-allowed text-gray-500 transition-colors duration-300 hover:text-gray-400 ") +
"mx-2 h-6 w-6"
}
/>
</div>
</section>
<section className="h-40 max-h-40 overflow-y-scroll">
<table className="w-full">
<thead className=" ">
<tr>
<th className="sticky top-0 rounded-bl rounded-tl bg-cyan-300">
No #
</th>
<th className="sticky top-0 bg-cyan-300">IP</th>
<th className="sticky top-0 rounded-br rounded-tr bg-cyan-300">
Latency
</th>
</tr>
</thead>
<tbody>
{validIPs.map(({ ip, latency }, index) => (
<tr key={ip}>
<td className="text-center">{index + 1}</td>
<td
onClick={() => copyIPToClipboard(ip)}
className="cursor-pointer text-center transition-colors duration-200 hover:text-gray-500"
>
{ip}
</td>
<td className="text-center">{latency}</td>
</tr>
))}
</tbody>
</table>
</section>
</div>
<footer className="flex h-24 w-full items-center justify-center">
<a
className="flex items-center justify-center rounded bg-slate-100 p-3"
href="https://github.com/goldsrc/cloudflare-scanner"
target="_blank"
rel="noopener noreferrer"
>
Source on{" "}
<Image
src="/github.svg"
width={16}
height={16}
alt="Github Logo"
className="ml-2 h-4 w-4"
/>
</a>
</footer>
</main>
</>
);
};
export default Home;
| src/pages/index.tsx | goldsrc-cloudflare-scanner-ce66f4d | [
{
"filename": "src/components/UserIP/index.tsx",
"retrieved_chunk": "type Props = {\n ip: string;\n location: string;\n};\nconst UserIP = ({ ip, location }: Props) => {\n return (\n <div className=\"text-center\">\n <b>Your Current IP:</b>\n <p>{ip}</p>\n <p className=\"opacity-75\">{location}</p>",
"score": 0.5864639282226562
},
{
"filename": "src/pages/_app.tsx",
"retrieved_chunk": " <div className={`h-full ${inter.className}`}>\n <Component {...pageProps} />\n <Toaster />\n </div>\n </SWRConfig>\n );\n};\nexport default MyApp;",
"score": 0.5610882043838501
},
{
"filename": "src/pages/_app.tsx",
"retrieved_chunk": "import { type AppType } from \"next/dist/shared/lib/utils\";\nimport { Inter } from \"next/font/google\";\nimport \"~/styles/globals.css\";\nimport { Toaster } from \"react-hot-toast\";\nimport { SWRConfig } from \"swr\";\nimport { localStorageProvider } from \"~/swr/cacheProviders/localstorage\";\nconst inter = Inter({ subsets: [\"latin\"] });\nconst MyApp: AppType = ({ Component, pageProps }) => {\n return (\n <SWRConfig value={{ provider: localStorageProvider }}>",
"score": 0.4963648319244385
},
{
"filename": "src/helpers/download.ts",
"retrieved_chunk": " if (!arr.length) return;\n const blob = format === \"json\" ? createJSON(arr) : createCSV(arr);\n const url = URL.createObjectURL(blob);\n const link = document.createElement(\"a\");\n link.setAttribute(\"href\", url);\n link.setAttribute(\"download\", `ip-list.${format}`);\n link.style.display = \"none\";\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);",
"score": 0.4477354884147644
},
{
"filename": "src/helpers/download.ts",
"retrieved_chunk": " const keys = Object.keys(arr[0] as AcceptableObject);\n const csvHeader = keys.join(\",\");\n const csvContent = arr\n .map((el) => keys.map((key) => String(el[key] || \"\")).join(\",\"))\n .join(\"\\n\");\n const csvString = `${csvHeader}\\n${csvContent}`;\n const blob = new Blob([csvString], { type: \"text/csv\" });\n return blob;\n};\nexport function download(arr: AcceptableObject[], format: \"json\" | \"csv\") {",
"score": 0.42925912141799927
}
] | typescript | className={`mx-2 inline-block h-6 w-6 transform-gpu text-center text-blue-600 duration-300 ${tryCharToRotation[tryChar]}`} |
import { App, Modal, TextComponent } from "obsidian";
import CssEditorPlugin from "src/main";
import { createSnippetFile } from "../file-system-helpers";
import { ErrorNotice } from "../Notice";
export class CssSnippetCreateModal extends Modal {
private value: string;
private plugin: CssEditorPlugin;
constructor(app: App, plugin: CssEditorPlugin) {
super(app);
this.value = "";
this.plugin = plugin;
}
onOpen(): void {
super.onOpen();
this.titleEl.setText("Create CSS Snippet");
this.containerEl.addClass("css-editor-create-modal");
this.buildForm();
}
private buildForm() {
const textInput = new TextComponent(this.contentEl);
textInput.setPlaceholder("CSS snippet file name (ex: snippet.css)");
textInput.onChange((val) => (this.value = val));
textInput.inputEl.addEventListener("keydown", (evt) => {
this.handleKeydown(evt);
});
}
private async handleKeydown(evt: KeyboardEvent) {
if (evt.key === "Escape") {
this.close();
} else if (evt.key === "Enter") {
try {
await createSnippetFile(this.app, this.value, "");
await this.plugin.openCssEditorView(this.value);
this.app.customCss?.setCssEnabledStatus?.(
this.value.replace(".css", ""),
true
);
this.close();
} catch (err) {
if (err instanceof Error) {
| new ErrorNotice(err.message); |
} else {
new ErrorNotice("Failed to create file. Reason unknown.");
}
}
}
}
}
| src/modals/CssSnippetCreateModal.ts | Zachatoo-obsidian-css-editor-881a94e | [
{
"filename": "src/CssEditorView.ts",
"retrieved_chunk": "\t\tsuper(leaf);\n\t\tthis.navigation = true;\n\t\tthis.editor = new EditorView({\n\t\t\tparent: this.contentEl,\n\t\t\textensions: [\n\t\t\t\tbasicExtensions,\n\t\t\t\tthis.app.vault.getConfig?.(\"vimMode\") ? vim() : [],\n\t\t\t\tEditorView.updateListener.of((update) => {\n\t\t\t\t\tif (update.docChanged) {\n\t\t\t\t\t\tthis.requestSave(update.state.doc.toString());",
"score": 0.7965636253356934
},
{
"filename": "src/CssEditorView.ts",
"retrieved_chunk": "\t\t\tthis.dispatchEditorData(data);\n\t\t\tthis.app.workspace.requestSaveLayout();\n\t\t}\n\t\tconst timer = window.setInterval(() => {\n\t\t\tthis.editor.focus();\n\t\t\tif (this.editor.hasFocus) clearInterval(timer);\n\t\t}, 200);\n\t\tthis.registerInterval(timer);\n\t}\n\tgetEditorData() {",
"score": 0.7664772868156433
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\t\titem\n\t\t\t\t\t);\n\t\t\t\t\tnew InfoNotice(`${item} was deleted.`);\n\t\t\t\t}).open();\n\t\t\t},\n\t\t});\n\t\tthis.registerView(VIEW_TYPE_CSS, (leaf) => new CssEditorView(leaf));\n\t}\n\tonunload() {}\n\tasync loadSettings() {",
"score": 0.7507209777832031
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\tthis.openCssEditorView\n\t\t\t\t).open();\n\t\t\t},\n\t\t});\n\t\tthis.addCommand({\n\t\t\tid: \"create-css-snippet\",\n\t\t\tname: \"Create CSS Snippet\",\n\t\t\tcallback: async () => {\n\t\t\t\tnew CssSnippetCreateModal(this.app, this).open();\n\t\t\t},",
"score": 0.7479469776153564
},
{
"filename": "src/CssEditorView.ts",
"retrieved_chunk": "\t\treturn \"file-code\";\n\t}\n\tgetDisplayText(): string {\n\t\treturn this.filename;\n\t}\n\tasync onOpen(): Promise<void> {\n\t\tconst filename = this.getState()?.filename;\n\t\tif (filename) {\n\t\t\tthis.filename = filename;\n\t\t\tconst data = await readSnippetFile(this.app, filename);",
"score": 0.7445579767227173
}
] | typescript | new ErrorNotice(err.message); |
/* eslint-disable @typescript-eslint/no-misused-promises */
import { type NextPage } from "next";
import dynamic from "next/dynamic";
import Head from "next/head";
import Image from "next/image";
import { type TryChar, useIPScanner } from "~/hooks/useIPScanner";
import { download } from "~/helpers/download";
import {
TableCellsIcon,
DocumentTextIcon,
ArrowPathRoundedSquareIcon,
MagnifyingGlassCircleIcon,
PlayIcon,
StopIcon,
} from "@heroicons/react/24/solid";
import { copyIPToClipboard } from "~/helpers/copyIPToClipboard";
import { allIps } from "~/consts";
import { useUserIPInfo } from "~/hooks/useUserIPInfo";
const UserIP = dynamic(() => import("~/components/UserIP"), { ssr: false });
const Home: NextPage = () => {
const { ipInfo } = useUserIPInfo();
const {
startScan,
stopScan,
color,
currentIP,
currentLatency,
ipRegex,
maxIPCount,
maxLatency,
scanState,
testNo,
tryChar,
validIPs,
setSettings,
} = useIPScanner({ allIps });
const isRunning = scanState !== "idle";
const tryCharToRotation: Record<TryChar, string> = {
"": "rotate-[360deg]",
"|": "rotate-[72deg]",
"/": "rotate-[144deg]",
"-": "rotate-[216deg]",
"\\": "rotate-[288deg]",
};
return (
<>
<Head>
<title>Cloudflare Scanner</title>
<meta
name="description"
content="Cloudflare Scanner to find clean ip"
/>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="flex h-full max-w-full flex-col items-center justify-center bg-gradient-to-b from-cyan-300 to-cyan-400 px-3">
<div className="max-h-full w-[900px] max-w-full rounded-lg bg-slate-200 p-5 text-gray-700 shadow-lg">
<section className="flex flex-col items-center border-b-4 border-cyan-600">
<div className="w-full border-b-4 border-cyan-600 py-4 text-center">
<h1 className="text-3xl font-bold text-cyan-900">
Cloudflare Clean IP Scanner{" "}
<MagnifyingGlassCircleIcon className="mb-2 inline-block h-10 w-10" />
</h1>
</div>
<div className="flex w-full flex-col items-center justify-center py-4 md:flex-row">
<div className="mb-4 flex w-full items-center justify-center px-2 md:mb-0 md:w-1/2">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Max Count:
<input
type="number"
id="max-ip"
value={maxIPCount}
onChange={(e) =>
setSettings({ maxIPCount: e.target.valueAsNumber })
}
disabled={isRunning}
min={1}
max={500}
className="ml-2 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
<div className="flex w-full items-center justify-center px-2 md:w-1/2">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Maximum Delay:
<input
type="number"
id="max-latency"
value={maxLatency}
disabled={isRunning}
onChange={(e) =>
setSettings({ maxLatency: e.target.valueAsNumber })
}
min={150}
max={3000}
step={50}
className="ml-2 w-16 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
</div>
<div className="flex w-full items-center justify-center py-4">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Regex for IP:
<input
type="text"
value={ipRegex}
onChange={(e) => setSettings({ ipRegex: e.target.value })}
disabled={isRunning}
id="ip-regex"
placeholder="^104\.17\.|^141\."
className="ml-2 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
<div className="h-16">
<UserIP
ip={ipInfo.ipAddress}
location={
ipInfo.ipVersion === 4
? ipInfo.regionName + ", " + ipInfo.countryName
: "..."
}
/>
</div>
<div className="flex w-full flex-col items-center justify-around py-4 md:w-1/2 md:flex-row">
{!isRunning ? (
<button
className="rounded bg-cyan-500 px-4 py-2 font-bold text-white outline-cyan-700 transition-colors duration-300 hover:bg-cyan-600 disabled:cursor-not-allowed disabled:bg-gray-700 disabled:outline-white disabled:hover:bg-gray-800"
onClick={startScan}
>
Start Scan{" "}
<PlayIcon className="inline-block h-6 w-6 pb-0.5" />
</button>
) : (
<button
className="rounded bg-cyan-500 px-4 py-2 font-bold text-white outline-cyan-700 transition-colors duration-300 hover:bg-cyan-600 disabled:cursor-not-allowed disabled:bg-gray-700 disabled:outline-white disabled:hover:bg-gray-800"
type="button"
onClick={stopScan}
disabled={scanState === "stopping"}
>
Stop Scan <StopIcon className="inline-block h-6 w-6 pb-0.5" />
</button>
)}
</div>
</section>
<section className="my-4 grid grid-cols-1 gap-5 md:grid-cols-3">
<div className="text-center text-red-500">
Notice: Please turn off your vpn!
</div>
<div className="text-center font-bold">Test No: {testNo}</div>
<div
className={`${
color === "red" ? "text-red-500" : "text-green-500"
} text-center`}
>
{currentIP || "0.0.0.0"}
</div>
<div className="flex items-center justify-center md:col-span-3">
<ArrowPathRoundedSquareIcon
className={`mx-2 inline-block h-6 w-6 transform-gpu text-center text-blue-600 duration-300 ${tryCharToRotation[tryChar]}`}
/>
<div className="mx-2 text-center">Latency: {currentLatency}</div>
<TableCellsIcon
onClick={() => download(validIPs, "csv")}
title="Download as CSV"
className={
(validIPs.length > 0
? "cursor-pointer text-blue-600 transition-colors duration-300 hover:text-blue-500 "
: "cursor-not-allowed text-gray-500 transition-colors duration-300 hover:text-gray-400 ") +
"mx-2 h-6 w-6"
}
/>
<DocumentTextIcon
onClick={() => download(validIPs, "json")}
title="Download as JSON"
className={
(validIPs.length > 0
? "cursor-pointer text-blue-600 transition-colors duration-300 hover:text-blue-500 "
: "cursor-not-allowed text-gray-500 transition-colors duration-300 hover:text-gray-400 ") +
"mx-2 h-6 w-6"
}
/>
</div>
</section>
<section className="h-40 max-h-40 overflow-y-scroll">
<table className="w-full">
<thead className=" ">
<tr>
<th className="sticky top-0 rounded-bl rounded-tl bg-cyan-300">
No #
</th>
<th className="sticky top-0 bg-cyan-300">IP</th>
<th className="sticky top-0 rounded-br rounded-tr bg-cyan-300">
Latency
</th>
</tr>
</thead>
<tbody>
{validIPs.map(({ ip, latency }, index) => (
<tr key={ip}>
<td className="text-center">{index + 1}</td>
<td
| onClick={() => copyIPToClipboard(ip)} |
className="cursor-pointer text-center transition-colors duration-200 hover:text-gray-500"
>
{ip}
</td>
<td className="text-center">{latency}</td>
</tr>
))}
</tbody>
</table>
</section>
</div>
<footer className="flex h-24 w-full items-center justify-center">
<a
className="flex items-center justify-center rounded bg-slate-100 p-3"
href="https://github.com/goldsrc/cloudflare-scanner"
target="_blank"
rel="noopener noreferrer"
>
Source on{" "}
<Image
src="/github.svg"
width={16}
height={16}
alt="Github Logo"
className="ml-2 h-4 w-4"
/>
</a>
</footer>
</main>
</>
);
};
export default Home;
| src/pages/index.tsx | goldsrc-cloudflare-scanner-ce66f4d | [
{
"filename": "src/components/UserIP/index.tsx",
"retrieved_chunk": "type Props = {\n ip: string;\n location: string;\n};\nconst UserIP = ({ ip, location }: Props) => {\n return (\n <div className=\"text-center\">\n <b>Your Current IP:</b>\n <p>{ip}</p>\n <p className=\"opacity-75\">{location}</p>",
"score": 0.780899167060852
},
{
"filename": "src/pages/_app.tsx",
"retrieved_chunk": " <div className={`h-full ${inter.className}`}>\n <Component {...pageProps} />\n <Toaster />\n </div>\n </SWRConfig>\n );\n};\nexport default MyApp;",
"score": 0.6804070472717285
},
{
"filename": "src/hooks/useIPScanner.ts",
"retrieved_chunk": " validIPs: [],\n currentIP: \"\",\n tryChar: \"\",\n currentLatency: 0,\n color: \"red\",\n scanState: \"idle\",\n });\n },\n increaseTestNo: () => {\n set((state) => ({ testNo: state.testNo + 1 }));",
"score": 0.6643036603927612
},
{
"filename": "src/hooks/useIPScanner.ts",
"retrieved_chunk": " dispatch({ scanState: \"stopping\" });\n } else {\n setToIdle();\n }\n }\n async function testIPs(ipList: string[]) {\n for (const ip of ipList) {\n increaseTestNo();\n const url = `https://${ip}/__down`;\n let testCount = 0;",
"score": 0.6527951955795288
},
{
"filename": "src/hooks/useIPScanner.ts",
"retrieved_chunk": " const newArr = [...state.validIPs, validIP];\n const validIPs = newArr.sort((a, b) => a.latency - b.latency);\n return {\n validIPs,\n };\n });\n },\n reset: () => {\n set({\n testNo: 0,",
"score": 0.6428278684616089
}
] | typescript | onClick={() => copyIPToClipboard(ip)} |
/* eslint-disable @typescript-eslint/no-misused-promises */
import { type NextPage } from "next";
import dynamic from "next/dynamic";
import Head from "next/head";
import Image from "next/image";
import { type TryChar, useIPScanner } from "~/hooks/useIPScanner";
import { download } from "~/helpers/download";
import {
TableCellsIcon,
DocumentTextIcon,
ArrowPathRoundedSquareIcon,
MagnifyingGlassCircleIcon,
PlayIcon,
StopIcon,
} from "@heroicons/react/24/solid";
import { copyIPToClipboard } from "~/helpers/copyIPToClipboard";
import { allIps } from "~/consts";
import { useUserIPInfo } from "~/hooks/useUserIPInfo";
const UserIP = dynamic(() => import("~/components/UserIP"), { ssr: false });
const Home: NextPage = () => {
const { ipInfo } = useUserIPInfo();
const {
startScan,
stopScan,
color,
currentIP,
currentLatency,
ipRegex,
maxIPCount,
maxLatency,
scanState,
testNo,
tryChar,
validIPs,
setSettings,
} = useIPScanner({ allIps });
const isRunning = scanState !== "idle";
const tryCharToRotation: Record<TryChar, string> = {
"": "rotate-[360deg]",
"|": "rotate-[72deg]",
"/": "rotate-[144deg]",
"-": "rotate-[216deg]",
"\\": "rotate-[288deg]",
};
return (
<>
<Head>
<title>Cloudflare Scanner</title>
<meta
name="description"
content="Cloudflare Scanner to find clean ip"
/>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="flex h-full max-w-full flex-col items-center justify-center bg-gradient-to-b from-cyan-300 to-cyan-400 px-3">
<div className="max-h-full w-[900px] max-w-full rounded-lg bg-slate-200 p-5 text-gray-700 shadow-lg">
<section className="flex flex-col items-center border-b-4 border-cyan-600">
<div className="w-full border-b-4 border-cyan-600 py-4 text-center">
<h1 className="text-3xl font-bold text-cyan-900">
Cloudflare Clean IP Scanner{" "}
<MagnifyingGlassCircleIcon className="mb-2 inline-block h-10 w-10" />
</h1>
</div>
<div className="flex w-full flex-col items-center justify-center py-4 md:flex-row">
<div className="mb-4 flex w-full items-center justify-center px-2 md:mb-0 md:w-1/2">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Max Count:
<input
type="number"
id="max-ip"
value={maxIPCount}
onChange={(e) =>
setSettings({ maxIPCount: e.target.valueAsNumber })
}
disabled={isRunning}
min={1}
max={500}
className="ml-2 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
<div className="flex w-full items-center justify-center px-2 md:w-1/2">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Maximum Delay:
<input
type="number"
id="max-latency"
value={maxLatency}
disabled={isRunning}
onChange={(e) =>
setSettings({ maxLatency: e.target.valueAsNumber })
}
min={150}
max={3000}
step={50}
className="ml-2 w-16 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
</div>
<div className="flex w-full items-center justify-center py-4">
<label className="inline-flex h-12 items-center justify-center rounded-lg bg-white p-2">
Regex for IP:
<input
type="text"
value={ipRegex}
onChange={(e) => setSettings({ ipRegex: e.target.value })}
disabled={isRunning}
id="ip-regex"
placeholder="^104\.17\.|^141\."
className="ml-2 rounded-md border-0 px-2 py-1.5 text-center text-gray-900 shadow-sm ring-1 ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-600 disabled:cursor-not-allowed disabled:bg-gray-50 disabled:text-gray-500 disabled:ring-gray-200 sm:text-sm sm:leading-6"
/>
</label>
</div>
<div className="h-16">
<UserIP
ip={ipInfo.ipAddress}
location={
ipInfo.ipVersion === 4
? ipInfo.regionName + ", " + ipInfo.countryName
: "..."
}
/>
</div>
<div className="flex w-full flex-col items-center justify-around py-4 md:w-1/2 md:flex-row">
{!isRunning ? (
<button
className="rounded bg-cyan-500 px-4 py-2 font-bold text-white outline-cyan-700 transition-colors duration-300 hover:bg-cyan-600 disabled:cursor-not-allowed disabled:bg-gray-700 disabled:outline-white disabled:hover:bg-gray-800"
onClick={startScan}
>
Start Scan{" "}
<PlayIcon className="inline-block h-6 w-6 pb-0.5" />
</button>
) : (
<button
className="rounded bg-cyan-500 px-4 py-2 font-bold text-white outline-cyan-700 transition-colors duration-300 hover:bg-cyan-600 disabled:cursor-not-allowed disabled:bg-gray-700 disabled:outline-white disabled:hover:bg-gray-800"
type="button"
onClick={stopScan}
disabled={scanState === "stopping"}
>
Stop Scan <StopIcon className="inline-block h-6 w-6 pb-0.5" />
</button>
)}
</div>
</section>
<section className="my-4 grid grid-cols-1 gap-5 md:grid-cols-3">
<div className="text-center text-red-500">
Notice: Please turn off your vpn!
</div>
<div className="text-center font-bold">Test No: {testNo}</div>
<div
className={`${
color === "red" ? "text-red-500" : "text-green-500"
} text-center`}
>
{currentIP || "0.0.0.0"}
</div>
<div className="flex items-center justify-center md:col-span-3">
<ArrowPathRoundedSquareIcon
className={`mx-2 inline-block h-6 w-6 transform-gpu text-center text-blue-600 duration-300 ${tryCharToRotation[tryChar]}`}
/>
<div className="mx-2 text-center">Latency: {currentLatency}</div>
<TableCellsIcon
onClick={() => download(validIPs, "csv")}
title="Download as CSV"
className={
(validIPs.length > 0
? "cursor-pointer text-blue-600 transition-colors duration-300 hover:text-blue-500 "
: "cursor-not-allowed text-gray-500 transition-colors duration-300 hover:text-gray-400 ") +
"mx-2 h-6 w-6"
}
/>
<DocumentTextIcon
onClick={() => download(validIPs, "json")}
title="Download as JSON"
className={
(validIPs.length > 0
? "cursor-pointer text-blue-600 transition-colors duration-300 hover:text-blue-500 "
: "cursor-not-allowed text-gray-500 transition-colors duration-300 hover:text-gray-400 ") +
"mx-2 h-6 w-6"
}
/>
</div>
</section>
<section className="h-40 max-h-40 overflow-y-scroll">
<table className="w-full">
<thead className=" ">
<tr>
<th className="sticky top-0 rounded-bl rounded-tl bg-cyan-300">
No #
</th>
<th className="sticky top-0 bg-cyan-300">IP</th>
<th className="sticky top-0 rounded-br rounded-tr bg-cyan-300">
Latency
</th>
</tr>
</thead>
<tbody>
{validIPs.map(({ ip, latency }, index) => (
<tr key={ip}>
<td className="text-center">{index + 1}</td>
<td
onClick={( | ) => copyIPToClipboard(ip)} |
className="cursor-pointer text-center transition-colors duration-200 hover:text-gray-500"
>
{ip}
</td>
<td className="text-center">{latency}</td>
</tr>
))}
</tbody>
</table>
</section>
</div>
<footer className="flex h-24 w-full items-center justify-center">
<a
className="flex items-center justify-center rounded bg-slate-100 p-3"
href="https://github.com/goldsrc/cloudflare-scanner"
target="_blank"
rel="noopener noreferrer"
>
Source on{" "}
<Image
src="/github.svg"
width={16}
height={16}
alt="Github Logo"
className="ml-2 h-4 w-4"
/>
</a>
</footer>
</main>
</>
);
};
export default Home;
| src/pages/index.tsx | goldsrc-cloudflare-scanner-ce66f4d | [
{
"filename": "src/components/UserIP/index.tsx",
"retrieved_chunk": "type Props = {\n ip: string;\n location: string;\n};\nconst UserIP = ({ ip, location }: Props) => {\n return (\n <div className=\"text-center\">\n <b>Your Current IP:</b>\n <p>{ip}</p>\n <p className=\"opacity-75\">{location}</p>",
"score": 0.7857025861740112
},
{
"filename": "src/pages/_app.tsx",
"retrieved_chunk": " <div className={`h-full ${inter.className}`}>\n <Component {...pageProps} />\n <Toaster />\n </div>\n </SWRConfig>\n );\n};\nexport default MyApp;",
"score": 0.6841668486595154
},
{
"filename": "src/hooks/useIPScanner.ts",
"retrieved_chunk": " validIPs: [],\n currentIP: \"\",\n tryChar: \"\",\n currentLatency: 0,\n color: \"red\",\n scanState: \"idle\",\n });\n },\n increaseTestNo: () => {\n set((state) => ({ testNo: state.testNo + 1 }));",
"score": 0.6623479723930359
},
{
"filename": "src/hooks/useIPScanner.ts",
"retrieved_chunk": " dispatch({ scanState: \"stopping\" });\n } else {\n setToIdle();\n }\n }\n async function testIPs(ipList: string[]) {\n for (const ip of ipList) {\n increaseTestNo();\n const url = `https://${ip}/__down`;\n let testCount = 0;",
"score": 0.6536741256713867
},
{
"filename": "src/hooks/useIPScanner.ts",
"retrieved_chunk": " currentIP: \"\",\n tryChar: \"\",\n currentLatency: 0,\n color: \"red\",\n scanState: \"idle\",\n};\nexport const useScannerStore = create<ScannerStore>()(\n persist(\n (set, get) => ({\n ...initialState,",
"score": 0.6456118822097778
}
] | typescript | ) => copyIPToClipboard(ip)} |
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { randomizeElements } from "~/helpers/randomizeElements";
import pick from "lodash/pick";
type ValidIP = {
ip: string;
latency: number;
};
const TRY_CHARS = ["", "|", "/", "-", "\\"] as const;
const MAX_TRIES = TRY_CHARS.length;
export type TryChar = (typeof TRY_CHARS)[number];
export type Settings = {
maxIPCount: number;
maxLatency: number;
ipRegex: string;
};
type SettingKeys = keyof Settings;
type ScanState = "idle" | "stopping" | "scanning";
type ScannerStore = Settings & {
testNo: number;
validIPs: ValidIP[];
currentIP: string;
tryChar: TryChar;
currentLatency: number;
color: "red" | "green";
scanState: ScanState;
dispatch: (newState: Partial<ScannerStore>) => void;
reset: () => void;
increaseTestNo: () => void;
addValidIP: (validIP: ValidIP) => void;
setSettings: (newSettings: Partial<Settings>) => void;
getScanState: () => ScanState;
getValidIPCount: () => number;
};
type FunctionalKeys = {
[K in keyof ScannerStore]: ScannerStore[K] extends (
...args: never[]
) => unknown
? K
: never;
}[keyof ScannerStore];
export const settingsInitialValues: Pick<ScannerStore, SettingKeys> = {
maxIPCount: 5,
maxLatency: 1000,
ipRegex: "",
};
const initialState: Omit<ScannerStore, FunctionalKeys> = {
...settingsInitialValues,
testNo: 0,
validIPs: [],
currentIP: "",
tryChar: "",
currentLatency: 0,
color: "red",
scanState: "idle",
};
export const useScannerStore = create<ScannerStore>()(
persist(
(set, get) => ({
...initialState,
getScanState: () => get().scanState,
getValidIPCount: () => get().validIPs.length,
setSettings: (newSettings) => {
set(newSettings);
},
dispatch: (newState) => {
set(newState);
},
addValidIP(validIP) {
set((state) => {
const newArr = [...state.validIPs, validIP];
const validIPs = newArr.sort((a, b) => a.latency - b.latency);
return {
validIPs,
};
});
},
reset: () => {
set({
testNo: 0,
validIPs: [],
currentIP: "",
tryChar: "",
currentLatency: 0,
color: "red",
scanState: "idle",
});
},
increaseTestNo: () => {
set((state) => ({ testNo: state.testNo + 1 }));
},
}),
{
name: "scanner-store",
partialize: (state) => pick(state, Object.keys(settingsInitialValues)),
version: 1,
}
)
);
type IPScannerProps = {
allIps: string[];
};
export const useIPScanner = ({ allIps }: IPScannerProps) => {
const {
dispatch,
reset,
increaseTestNo,
addValidIP,
getScanState,
getValidIPCount,
...state
} = useScannerStore();
function setToIdle() {
dispatch({ scanState: "idle", tryChar: "" });
}
async function startScan() {
reset();
try {
const ips = state.ipRegex
? allIps.filter((el) => new RegExp(state.ipRegex).test(el))
: allIps;
dispatch({ scanState: "scanning" });
await | testIPs(randomizeElements(ips)); |
setToIdle();
} catch (e) {
console.error(e);
}
}
function stopScan() {
if (getScanState() === "scanning") {
dispatch({ scanState: "stopping" });
} else {
setToIdle();
}
}
async function testIPs(ipList: string[]) {
for (const ip of ipList) {
increaseTestNo();
const url = `https://${ip}/__down`;
let testCount = 0;
const startTime = performance.now();
const multiply =
state.maxLatency <= 500 ? 1.5 : state.maxLatency <= 1000 ? 1.2 : 1;
let timeout = 1.5 * multiply * state.maxLatency;
for (let i = 0; i < MAX_TRIES; i++) {
const controller = new AbortController();
const timeoutId = setTimeout(() => {
controller.abort();
}, Math.trunc(timeout));
const newState: Partial<ScannerStore> = {
currentIP: ip,
tryChar: TRY_CHARS[i] || "",
};
if (i === 0) {
timeout = multiply * state.maxLatency;
newState.color = "red";
newState.currentLatency = 0;
} else {
timeout = 1.2 * multiply * state.maxLatency;
newState.color = "green";
newState.currentLatency = Math.floor(
(performance.now() - startTime) / (i + 1)
);
}
dispatch(newState);
try {
await fetch(url, {
signal: controller.signal,
});
testCount++;
} catch (error) {
// don't increase testResult if it's not an abort error
if (!(error instanceof Error && error.name === "AbortError")) {
testCount++;
}
}
clearTimeout(timeoutId);
}
const latency = Math.floor((performance.now() - startTime) / MAX_TRIES);
if (testCount === MAX_TRIES && latency <= state.maxLatency) {
addValidIP({
ip,
latency,
});
}
if (
getScanState() !== "scanning" ||
getValidIPCount() >= state.maxIPCount
) {
break;
}
}
}
return {
...state,
startScan,
stopScan,
};
};
| src/hooks/useIPScanner.ts | goldsrc-cloudflare-scanner-ce66f4d | [
{
"filename": "src/helpers/rangeToIpArray.ts",
"retrieved_chunk": "export function rangeToIpArray(range: string) {\n const parts = range.split(\"/\");\n if (parts.length !== 2) {\n throw new Error(`Invalid IP Range format ${range} `);\n }\n const [ip, maskString] = parts as [string, string];\n const mask = parseInt(maskString, 10);\n const ipParts = ip.split(\".\");\n if (ipParts.length !== 4) {\n throw new Error(\"Invalid IP\");",
"score": 0.7516369819641113
},
{
"filename": "src/pages/index.tsx",
"retrieved_chunk": " scanState,\n testNo,\n tryChar,\n validIPs,\n setSettings,\n } = useIPScanner({ allIps });\n const isRunning = scanState !== \"idle\";\n const tryCharToRotation: Record<TryChar, string> = {\n \"\": \"rotate-[360deg]\",\n \"|\": \"rotate-[72deg]\",",
"score": 0.7493114471435547
},
{
"filename": "src/pages/index.tsx",
"retrieved_chunk": " const { ipInfo } = useUserIPInfo();\n const {\n startScan,\n stopScan,\n color,\n currentIP,\n currentLatency,\n ipRegex,\n maxIPCount,\n maxLatency,",
"score": 0.7454999685287476
},
{
"filename": "src/swr/cacheProviders/localstorage.ts",
"retrieved_chunk": " if (!isServer) {\n // Before unloading the app, we write back all the data into `localStorage`.\n window.addEventListener(\"beforeunload\", () => {\n const appCache = JSON.stringify(Array.from(map.entries()));\n localStorage.setItem(CACHE_KEY, appCache);\n });\n }\n // We still use the map for write & read for performance.\n return map;\n};",
"score": 0.7198203802108765
},
{
"filename": "src/swr/cacheProviders/localstorage.ts",
"retrieved_chunk": "import { type State } from \"swr\";\nconst CACHE_KEY = \"swr-cache\";\nexport const localStorageProvider = () => {\n const isServer = typeof window === \"undefined\";\n const localStorageData: unknown = JSON.parse(\n (!isServer && localStorage.getItem(CACHE_KEY)) || \"[]\"\n );\n const map = new Map<string, State<unknown, unknown> | undefined>(\n Array.isArray(localStorageData) ? localStorageData : []\n );",
"score": 0.7165675759315491
}
] | typescript | testIPs(randomizeElements(ips)); |
import { Payload } from "payload";
import { IcrowdinFile } from "./payload-crowdin-sync/files";
/**
* get Crowdin Article Directory for a given documentId
*
* The Crowdin Article Directory is associated with a document,
* so is easy to retrieve. Use this function when you only have
* a document id.
*/
export async function getArticleDirectory(
documentId: string,
payload: Payload,
allowEmpty?: boolean
) {
// Get directory
const crowdinPayloadArticleDirectory = await payload.find({
collection: "crowdin-article-directories",
where: {
name: {
equals: documentId,
},
},
});
if (crowdinPayloadArticleDirectory.totalDocs === 0 && allowEmpty) {
// a thrown error won't be reported in an api call, so console.log it as well.
console.log(`No article directory found for document ${documentId}`);
throw new Error(
"This article does not have a corresponding entry in the crowdin-article-directories collection."
);
}
return crowdinPayloadArticleDirectory
? crowdinPayloadArticleDirectory.docs[0]
: undefined;
}
export async function getFile(
name: string,
crowdinArticleDirectoryId: string,
payload: Payload
): Promise<any> {
const result = await payload.find({
collection: "crowdin-files",
where: {
field: { equals: name },
crowdinArticleDirectory: {
equals: crowdinArticleDirectoryId,
},
},
});
return result.docs[0];
}
export async function getFiles(
crowdinArticleDirectoryId: string,
payload: Payload
): Promise<any> {
const result = await payload.find({
collection: "crowdin-files",
where: {
crowdinArticleDirectory: {
equals: crowdinArticleDirectoryId,
},
},
});
return result.docs;
}
export async function getFileByDocumentID(
name: string,
documentId: string,
payload: Payload
| ): Promise<IcrowdinFile> { |
const articleDirectory = await getArticleDirectory(documentId, payload);
return getFile(name, articleDirectory.id, payload);
}
export async function getFilesByDocumentID(
documentId: string,
payload: Payload
): Promise<IcrowdinFile[]> {
const articleDirectory = await getArticleDirectory(documentId, payload);
if (!articleDirectory) {
// tests call this function to make sure files are deleted
return [];
}
const files = await getFiles(articleDirectory.id, payload);
return files;
}
| src/api/helpers.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " id: crowdinFile.id, // required\n });\n return payloadFile;\n }\n private async crowdinUpdateFile({\n fileId,\n name,\n fileData,\n fileType,\n }: IupdateCrowdinFile) {",
"score": 0.8675199151039124
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " }\n async getFilesByDocumentID(documentId: string) {\n const result = await getFilesByDocumentID(documentId, this.payload);\n return result;\n }\n}",
"score": 0.8591175079345703
},
{
"filename": "src/api/mock/crowdin-client.ts",
"retrieved_chunk": " });\n return file;\n }\n async buildProjectFileTranslation(\n projectId: number,\n fileId: number,\n { targetLanguageId }: TranslationsModel.BuildProjectFileTranslationRequest\n ): Promise<\n ResponseObject<TranslationsModel.BuildProjectFileTranslationResponse>\n > {",
"score": 0.848448634147644
},
{
"filename": "src/api/mock/crowdin-client.ts",
"retrieved_chunk": " createdAt: date,\n updatedAt: date,\n },\n };\n });\n }\n async addStorage(\n fileName: string,\n request: any,\n contentType?: string",
"score": 0.8421189785003662
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " storageId: storage.data.id,\n }\n );\n return file;\n }\n private async crowdinCreateFile({\n name,\n fileData,\n fileType,\n directoryId,",
"score": 0.8232930898666382
}
] | typescript | ): Promise<IcrowdinFile> { |
import crowdin, {
Credentials,
Translations,
} from "@crowdin/crowdin-api-client";
import { payloadCrowdinSyncFilesApi } from "./files";
import { mockCrowdinClient } from "../mock/crowdin-client";
import { Payload } from "payload";
import { PluginOptions } from "../../types";
import deepEqual from "deep-equal";
import {
CollectionConfig,
GlobalConfig,
SanitizedCollectionConfig,
SanitizedGlobalConfig,
} from "payload/types";
import { htmlToSlate, payloadHtmlToSlateConfig } from "slate-serializers";
import {
getLocalizedFields,
getFieldSlugs,
buildCrowdinJsonObject,
buildCrowdinHtmlObject,
buildPayloadUpdateObject,
getLocalizedRequiredFields,
} from "../../utilities";
interface IgetLatestDocumentTranslation {
collection: string;
doc: any;
locale: string;
global?: boolean;
}
interface IgetCurrentDocumentTranslation {
doc: any;
collection: string;
locale: string;
global?: boolean;
}
interface IgetTranslation {
documentId: string;
fieldName: string;
locale: string;
global?: boolean;
}
interface IupdateTranslation {
documentId: string;
collection: string;
dryRun?: boolean;
global?: boolean;
excludeLocales?: string[];
}
export class payloadCrowdinSyncTranslationsApi {
translationsApi: Translations;
filesApi: payloadCrowdinSyncFilesApi; // our wrapper for file operations
projectId: number;
directoryId?: number;
payload: Payload;
localeMap: PluginOptions["localeMap"];
sourceLocale: PluginOptions["sourceLocale"];
constructor(pluginOptions: PluginOptions, payload: Payload) {
// credentials
const credentials: Credentials = {
token: pluginOptions.token,
};
const { translationsApi } = new crowdin(credentials);
this.projectId = pluginOptions.projectId;
this.directoryId = pluginOptions.directoryId;
this.translationsApi =
process.env.NODE_ENV === "test"
? ( | mockCrowdinClient(pluginOptions) as any)
: translationsApi; |
this.filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, payload);
this.payload = payload;
this.localeMap = pluginOptions.localeMap;
this.sourceLocale = pluginOptions.sourceLocale;
}
async updateTranslation({
documentId,
collection,
dryRun = true,
global = false,
excludeLocales = [],
}: IupdateTranslation) {
/**
* Get existing document
*
* * check document exists
* * check for `meta` field (which can be added by @payloadcms/seo)
*
*/
let doc: { crowdinArticleDirectory: { id: any } };
if (global) {
doc = await this.payload.findGlobal({
slug: collection,
locale: this.sourceLocale,
});
} else {
doc = await this.payload.findByID({
collection: collection,
id: documentId,
locale: this.sourceLocale,
});
}
const report: { [key: string]: any } = {};
for (const locale of Object.keys(this.localeMap)) {
if (excludeLocales.includes(locale)) {
continue;
}
report[locale] = {};
report[locale].currentTranslations =
await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
report[locale].latestTranslations =
await this.getLatestDocumentTranslation({
collection: collection,
doc: doc,
locale: locale,
global,
});
report[locale].changed = !deepEqual(
report[locale].currentTranslations,
report[locale].latestTranslations
);
if (report[locale].changed && !dryRun) {
if (global) {
try {
await this.payload.updateGlobal({
slug: collection,
locale: locale,
data: {
...report[locale].latestTranslations,
// error on update without the following line.
// see https://github.com/thompsonsj/payload-crowdin-sync/pull/13/files#r1209271660
crowdinArticleDirectory: doc.crowdinArticleDirectory.id,
},
});
} catch (error) {
console.log(error);
}
} else {
try {
await this.payload.update({
collection: collection,
locale: locale,
id: documentId,
data: report[locale].latestTranslations,
});
} catch (error) {
console.log(error);
}
}
}
}
return {
source: doc,
translations: { ...report },
};
}
getCollectionConfig(
collection: string,
global: boolean
): CollectionConfig | GlobalConfig {
let collectionConfig:
| SanitizedGlobalConfig
| SanitizedCollectionConfig
| undefined;
if (global) {
collectionConfig = this.payload.config.globals.find(
(col: GlobalConfig) => col.slug === collection
);
} else {
collectionConfig = this.payload.config.collections.find(
(col: CollectionConfig) => col.slug === collection
);
}
if (!collectionConfig)
throw new Error(`Collection ${collection} not found in payload config`);
return collectionConfig;
}
async getCurrentDocumentTranslation({
doc,
collection,
locale,
global = false,
}: IgetCurrentDocumentTranslation) {
// get document
let document: any;
if (global) {
document = await this.payload.findGlobal({
slug: collection,
locale: locale,
});
} else {
document = await this.payload.findByID({
collection: collection,
id: doc.id,
locale: locale,
});
}
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
// build crowdin json object
const crowdinJsonObject = buildCrowdinJsonObject({
doc: document,
fields: localizedFields,
});
const crowdinHtmlObject = buildCrowdinHtmlObject({
doc: document,
fields: localizedFields,
});
try {
const docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document,
});
return docTranslations;
} catch (error) {
console.log(error);
throw new Error(`${error}`);
}
}
/**
* Retrieve translations from Crowdin for a document in a given locale
*/
async getLatestDocumentTranslation({
collection,
doc,
locale,
global = false,
}: IgetLatestDocumentTranslation) {
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
if (!localizedFields) {
return { message: "no localized fields" };
}
let docTranslations: { [key: string]: any } = {};
// add json fields
const crowdinJsonObject =
(await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: "fields",
locale: locale,
})) || {};
// add html fields
const localizedHtmlFields = await this.getHtmlFieldSlugs(
global ? collectionConfig.slug : doc.id
);
let crowdinHtmlObject: { [key: string]: any } = {};
for (const field of localizedHtmlFields) {
crowdinHtmlObject[field] = await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: field,
locale: locale,
});
}
docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document: doc,
});
// Add required fields if not present
const requiredFieldSlugs = getFieldSlugs(
getLocalizedRequiredFields(collectionConfig)
);
if (requiredFieldSlugs.length > 0) {
const currentTranslations = await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
requiredFieldSlugs.forEach((slug) => {
if (!docTranslations.hasOwnProperty(slug)) {
docTranslations[slug] = currentTranslations[slug];
}
});
}
return docTranslations;
}
async getHtmlFieldSlugs(documentId: string) {
const files = await this.filesApi.getFilesByDocumentID(documentId);
return files
.filter((file: any) => file.type === "html")
.map((file: any) => file.field);
}
/**
* Retrieve translations for a document field name
*
* * returns Slate object for html fields
* * returns all json fields if fieldName is 'fields'
*/
async getTranslation({ documentId, fieldName, locale }: IgetTranslation) {
const articleDirectory = await this.filesApi.getArticleDirectory(
documentId
);
const file = await this.filesApi.getFile(fieldName, articleDirectory.id);
// it is possible a file doesn't exist yet - e.g. an article with localized text fields that contains an empty html field.
if (!file) {
return;
}
try {
const response = await this.translationsApi.buildProjectFileTranslation(
this.projectId,
file.originalId,
{
targetLanguageId: this.localeMap[locale].crowdinId,
}
);
const data = await this.getFileDataFromUrl(response.data.url);
return file.type === "html"
? htmlToSlate(data, payloadHtmlToSlateConfig)
: JSON.parse(data);
} catch (error) {
console.log(error);
}
}
private async getFileDataFromUrl(url: string) {
const response = await fetch(url);
const body = await response.text();
return body;
}
/**
* Restore id and blockType to translations
*
* In order to update a document, we need to know the id and blockType of each block.
*
* Ideally, id and blockType are not sent to Crowdin - hence
* we need to restore them from the original document.
*
* This currently only works for a top-level `layout` blocks field.
*
* TODO: make this work for nested blocks.
*/
restoreIdAndBlockType = (
document: any,
translations: any,
key: string = "layout"
) => {
if (translations.hasOwnProperty(key)) {
translations[key] = translations[key].map(
(block: any, index: number) => ({
...block,
id: document[key][index].id,
blockType: document[key][index].blockType,
})
);
}
return translations;
};
}
| src/api/payload-crowdin-sync/translations.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " const { sourceFilesApi, uploadStorageApi } = new crowdin(credentials);\n this.projectId = pluginOptions.projectId;\n this.directoryId = pluginOptions.directoryId;\n this.sourceFilesApi =\n process.env.NODE_ENV === \"test\"\n ? (mockCrowdinClient(pluginOptions) as any)\n : sourceFilesApi;\n this.uploadStorageApi =\n process.env.NODE_ENV === \"test\"\n ? (mockCrowdinClient(pluginOptions) as any)",
"score": 0.9306764006614685
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " sourceFilesApi: SourceFiles;\n uploadStorageApi: UploadStorage;\n projectId: number;\n directoryId?: number;\n payload: Payload;\n constructor(pluginOptions: PluginOptions, payload: Payload) {\n // credentials\n const credentials: Credentials = {\n token: pluginOptions.token,\n };",
"score": 0.809322714805603
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " },\n });\n if (query.totalDocs === 0) {\n // Create collection directory on Crowdin\n const crowdinDirectory = await this.sourceFilesApi.createDirectory(\n this.projectId,\n {\n directoryId: this.directoryId,\n name: collectionSlug,\n title: toWords(collectionSlug), // is this transformed value available on the collection object?",
"score": 0.808932900428772
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " } else {\n const crowdinPayloadCollectionDirectory =\n await this.findOrCreateCollectionDirectory({\n collectionSlug: global ? \"globals\" : collectionSlug,\n });\n // Create article directory on Crowdin\n const crowdinDirectory = await this.sourceFilesApi.createDirectory(\n this.projectId,\n {\n directoryId: crowdinPayloadCollectionDirectory.originalId,",
"score": 0.807274580001831
},
{
"filename": "src/endpoints/globals/reviewTranslation.ts",
"retrieved_chunk": " pluginOptions,\n req.payload\n );\n try {\n const translations = await translationsApi.updateTranslation({\n documentId: !global && articleDirectory.name,\n collection: global\n ? articleDirectory.name\n : articleDirectory.crowdinCollectionDirectory.collectionSlug,\n global,",
"score": 0.8049811720848083
}
] | typescript | mockCrowdinClient(pluginOptions) as any)
: translationsApi; |
import { PluginOptions } from "../../types";
import {
ResponseObject,
SourceFilesModel,
UploadStorageModel,
TranslationsModel,
} from "@crowdin/crowdin-api-client";
/*
Crowdin Service mock
Although it is against best practice to mock an API
response, Crowdin and Payload CMS need to perform
multiple interdependent operations.
As a result, for effective testing, mocks are required
to provide Payload with expected data for subsequent
operations.
Importing types from the Crowdin API client provides
assurance that the mock returns expected data structures.
*/
class crowdinAPIWrapper {
projectId: number;
directoryId?: number;
branchId: number;
constructor(pluginOptions: PluginOptions) {
this.projectId = pluginOptions.projectId;
this.directoryId = pluginOptions.directoryId;
this.branchId = 4;
}
async listFileRevisions(projectId: number, fileId: number) {
return await Promise.resolve(1).then(() => undefined);
}
async createDirectory(
projectId: number,
{
directoryId = 1179,
name,
title = "undefined",
}: SourceFilesModel.CreateDirectoryRequest
): Promise<ResponseObject<SourceFilesModel.Directory>> {
return await Promise.resolve(1).then(() => {
const date = new Date().toISOString();
return {
data: {
id: 1169,
projectId: this.projectId,
branchId: this.branchId,
directoryId,
name: name,
title: title,
exportPattern: "**",
priority: "normal",
createdAt: date,
updatedAt: date,
},
};
});
}
async addStorage(
fileName: string,
request: any,
contentType?: string
): Promise<ResponseObject<UploadStorageModel.Storage>> {
const storage = await Promise.resolve(1).then(() => {
return {
data: {
id: 1788135621,
fileName,
},
};
});
return storage;
}
async deleteFile(projectId: number, fileId: number): Promise<void> {
await Promise.resolve(1).then(() => undefined);
}
async deleteDirectory(projectId: number, directoryId: number): Promise<void> {
await Promise.resolve(1).then(() => undefined);
}
async createFile(
projectId: number,
{
directoryId = 1172,
name,
storageId,
type = "html",
}: SourceFilesModel.CreateFileRequest
): Promise<ResponseObject<SourceFilesModel.File>> {
/*const storageId = await this.addStorage({
name,
fileData,
fileType,
})*/
const file = await Promise.resolve(1).then(() => {
const date = new Date().toISOString();
return {
data: {
revisionId: 5,
status: "active",
priority: "normal" as SourceFilesModel.Priority,
importOptions: {} as any,
exportOptions: {} as any,
excludedTargetLanguages: [],
createdAt: date,
updatedAt: date,
id: 1079,
projectId,
branchId: this.branchId,
directoryId,
name: name,
title: name,
type,
path: `/policies/security-and-privacy/${name}`,
parserVersion: 3,
},
};
});
return file;
}
async updateOrRestoreFile(
projectId: number,
fileId: number,
{ storageId }: SourceFilesModel.ReplaceFileFromStorageRequest
): Promise<ResponseObject<SourceFilesModel.File>> {
/*const storageId = await this.addStorage({
name,
fileData,
fileType,
})*/
const file = await Promise.resolve(1).then(() => {
const date = new Date().toISOString();
return {
data: {
revisionId: 5,
status: "active",
priority: "normal" as SourceFilesModel.Priority,
importOptions: {} as any,
exportOptions: {} as any,
excludedTargetLanguages: [],
createdAt: date,
updatedAt: date,
id: 1079,
projectId,
branchId: this.branchId,
directoryId: this.directoryId as number,
name: "file",
title: "file",
type: "html",
path: `/policies/security-and-privacy/file.filetype`,
parserVersion: 3,
},
};
});
return file;
}
async buildProjectFileTranslation(
projectId: number,
fileId: number,
{ targetLanguageId }: TranslationsModel.BuildProjectFileTranslationRequest
): Promise<
ResponseObject<TranslationsModel.BuildProjectFileTranslationResponse>
> {
const build = await Promise.resolve(1).then(() => {
const date = new Date().toISOString();
return {
data: {
id: 1,
projectId,
branchId: this.branchId,
fileId,
languageId: "en",
status: "inProgress",
progress: 0,
createdAt: date,
updatedAt: date,
etag: "string",
url: `https://api.crowdin.com/api/v2/projects/1/translations/builds/1/download?targetLanguageId=${targetLanguageId}`,
expireIn: "string",
},
};
});
return build;
}
}
export function | mockCrowdinClient(pluginOptions: PluginOptions) { |
return new crowdinAPIWrapper(pluginOptions);
}
| src/api/mock/crowdin-client.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " locale: locale,\n data: {\n ...report[locale].latestTranslations,\n // error on update without the following line.\n // see https://github.com/thompsonsj/payload-crowdin-sync/pull/13/files#r1209271660\n crowdinArticleDirectory: doc.crowdinArticleDirectory.id,\n },\n });\n } catch (error) {\n console.log(error);",
"score": 0.7384973764419556
},
{
"filename": "src/endpoints/globals/reviewFields.ts",
"retrieved_chunk": "import { Endpoint } from \"payload/config\";\nimport { PluginOptions } from \"../../types\";\nimport { payloadCrowdinSyncTranslationsApi } from \"../../api/payload-crowdin-sync/translations\";\nimport { getLocalizedFields } from \"../../utilities\";\nexport const getReviewFieldsEndpoint = ({\n pluginOptions,\n}: {\n pluginOptions: PluginOptions;\n}): Endpoint => ({\n path: `/:id/fields`,",
"score": 0.7352219223976135
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": "import crowdin, {\n Credentials,\n SourceFiles,\n UploadStorage,\n} from \"@crowdin/crowdin-api-client\";\nimport { mockCrowdinClient } from \"../mock/crowdin-client\";\nimport { Payload } from \"payload\";\nimport { PluginOptions } from \"../../types\";\nimport { toWords } from \"payload/dist/utilities/formatLabels\";\nimport {",
"score": 0.72429358959198
},
{
"filename": "src/endpoints/globals/reviewTranslation.ts",
"retrieved_chunk": "import { Endpoint } from \"payload/config\";\nimport { PluginOptions } from \"../../types\";\nimport { payloadCrowdinSyncTranslationsApi } from \"../../api/payload-crowdin-sync/translations\";\nexport const getReviewTranslationEndpoint = ({\n pluginOptions,\n type = \"review\",\n}: {\n pluginOptions: PluginOptions;\n type?: \"review\" | \"update\";\n}): Endpoint => ({",
"score": 0.7220185399055481
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " name: crowdinDirectory.data.name,\n title: crowdinDirectory.data.title,\n createdAt: crowdinDirectory.data.createdAt,\n updatedAt: crowdinDirectory.data.updatedAt,\n },\n });\n } else {\n crowdinPayloadCollectionDirectory = query.docs[0];\n }\n return crowdinPayloadCollectionDirectory;",
"score": 0.7200982570648193
}
] | typescript | mockCrowdinClient(pluginOptions: PluginOptions) { |
import crowdin, {
Credentials,
Translations,
} from "@crowdin/crowdin-api-client";
import { payloadCrowdinSyncFilesApi } from "./files";
import { mockCrowdinClient } from "../mock/crowdin-client";
import { Payload } from "payload";
import { PluginOptions } from "../../types";
import deepEqual from "deep-equal";
import {
CollectionConfig,
GlobalConfig,
SanitizedCollectionConfig,
SanitizedGlobalConfig,
} from "payload/types";
import { htmlToSlate, payloadHtmlToSlateConfig } from "slate-serializers";
import {
getLocalizedFields,
getFieldSlugs,
buildCrowdinJsonObject,
buildCrowdinHtmlObject,
buildPayloadUpdateObject,
getLocalizedRequiredFields,
} from "../../utilities";
interface IgetLatestDocumentTranslation {
collection: string;
doc: any;
locale: string;
global?: boolean;
}
interface IgetCurrentDocumentTranslation {
doc: any;
collection: string;
locale: string;
global?: boolean;
}
interface IgetTranslation {
documentId: string;
fieldName: string;
locale: string;
global?: boolean;
}
interface IupdateTranslation {
documentId: string;
collection: string;
dryRun?: boolean;
global?: boolean;
excludeLocales?: string[];
}
export class payloadCrowdinSyncTranslationsApi {
translationsApi: Translations;
filesApi: payloadCrowdinSyncFilesApi; // our wrapper for file operations
projectId: number;
directoryId?: number;
payload: Payload;
localeMap: PluginOptions["localeMap"];
sourceLocale | : PluginOptions["sourceLocale"]; |
constructor(pluginOptions: PluginOptions, payload: Payload) {
// credentials
const credentials: Credentials = {
token: pluginOptions.token,
};
const { translationsApi } = new crowdin(credentials);
this.projectId = pluginOptions.projectId;
this.directoryId = pluginOptions.directoryId;
this.translationsApi =
process.env.NODE_ENV === "test"
? (mockCrowdinClient(pluginOptions) as any)
: translationsApi;
this.filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, payload);
this.payload = payload;
this.localeMap = pluginOptions.localeMap;
this.sourceLocale = pluginOptions.sourceLocale;
}
async updateTranslation({
documentId,
collection,
dryRun = true,
global = false,
excludeLocales = [],
}: IupdateTranslation) {
/**
* Get existing document
*
* * check document exists
* * check for `meta` field (which can be added by @payloadcms/seo)
*
*/
let doc: { crowdinArticleDirectory: { id: any } };
if (global) {
doc = await this.payload.findGlobal({
slug: collection,
locale: this.sourceLocale,
});
} else {
doc = await this.payload.findByID({
collection: collection,
id: documentId,
locale: this.sourceLocale,
});
}
const report: { [key: string]: any } = {};
for (const locale of Object.keys(this.localeMap)) {
if (excludeLocales.includes(locale)) {
continue;
}
report[locale] = {};
report[locale].currentTranslations =
await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
report[locale].latestTranslations =
await this.getLatestDocumentTranslation({
collection: collection,
doc: doc,
locale: locale,
global,
});
report[locale].changed = !deepEqual(
report[locale].currentTranslations,
report[locale].latestTranslations
);
if (report[locale].changed && !dryRun) {
if (global) {
try {
await this.payload.updateGlobal({
slug: collection,
locale: locale,
data: {
...report[locale].latestTranslations,
// error on update without the following line.
// see https://github.com/thompsonsj/payload-crowdin-sync/pull/13/files#r1209271660
crowdinArticleDirectory: doc.crowdinArticleDirectory.id,
},
});
} catch (error) {
console.log(error);
}
} else {
try {
await this.payload.update({
collection: collection,
locale: locale,
id: documentId,
data: report[locale].latestTranslations,
});
} catch (error) {
console.log(error);
}
}
}
}
return {
source: doc,
translations: { ...report },
};
}
getCollectionConfig(
collection: string,
global: boolean
): CollectionConfig | GlobalConfig {
let collectionConfig:
| SanitizedGlobalConfig
| SanitizedCollectionConfig
| undefined;
if (global) {
collectionConfig = this.payload.config.globals.find(
(col: GlobalConfig) => col.slug === collection
);
} else {
collectionConfig = this.payload.config.collections.find(
(col: CollectionConfig) => col.slug === collection
);
}
if (!collectionConfig)
throw new Error(`Collection ${collection} not found in payload config`);
return collectionConfig;
}
async getCurrentDocumentTranslation({
doc,
collection,
locale,
global = false,
}: IgetCurrentDocumentTranslation) {
// get document
let document: any;
if (global) {
document = await this.payload.findGlobal({
slug: collection,
locale: locale,
});
} else {
document = await this.payload.findByID({
collection: collection,
id: doc.id,
locale: locale,
});
}
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
// build crowdin json object
const crowdinJsonObject = buildCrowdinJsonObject({
doc: document,
fields: localizedFields,
});
const crowdinHtmlObject = buildCrowdinHtmlObject({
doc: document,
fields: localizedFields,
});
try {
const docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document,
});
return docTranslations;
} catch (error) {
console.log(error);
throw new Error(`${error}`);
}
}
/**
* Retrieve translations from Crowdin for a document in a given locale
*/
async getLatestDocumentTranslation({
collection,
doc,
locale,
global = false,
}: IgetLatestDocumentTranslation) {
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
if (!localizedFields) {
return { message: "no localized fields" };
}
let docTranslations: { [key: string]: any } = {};
// add json fields
const crowdinJsonObject =
(await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: "fields",
locale: locale,
})) || {};
// add html fields
const localizedHtmlFields = await this.getHtmlFieldSlugs(
global ? collectionConfig.slug : doc.id
);
let crowdinHtmlObject: { [key: string]: any } = {};
for (const field of localizedHtmlFields) {
crowdinHtmlObject[field] = await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: field,
locale: locale,
});
}
docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document: doc,
});
// Add required fields if not present
const requiredFieldSlugs = getFieldSlugs(
getLocalizedRequiredFields(collectionConfig)
);
if (requiredFieldSlugs.length > 0) {
const currentTranslations = await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
requiredFieldSlugs.forEach((slug) => {
if (!docTranslations.hasOwnProperty(slug)) {
docTranslations[slug] = currentTranslations[slug];
}
});
}
return docTranslations;
}
async getHtmlFieldSlugs(documentId: string) {
const files = await this.filesApi.getFilesByDocumentID(documentId);
return files
.filter((file: any) => file.type === "html")
.map((file: any) => file.field);
}
/**
* Retrieve translations for a document field name
*
* * returns Slate object for html fields
* * returns all json fields if fieldName is 'fields'
*/
async getTranslation({ documentId, fieldName, locale }: IgetTranslation) {
const articleDirectory = await this.filesApi.getArticleDirectory(
documentId
);
const file = await this.filesApi.getFile(fieldName, articleDirectory.id);
// it is possible a file doesn't exist yet - e.g. an article with localized text fields that contains an empty html field.
if (!file) {
return;
}
try {
const response = await this.translationsApi.buildProjectFileTranslation(
this.projectId,
file.originalId,
{
targetLanguageId: this.localeMap[locale].crowdinId,
}
);
const data = await this.getFileDataFromUrl(response.data.url);
return file.type === "html"
? htmlToSlate(data, payloadHtmlToSlateConfig)
: JSON.parse(data);
} catch (error) {
console.log(error);
}
}
private async getFileDataFromUrl(url: string) {
const response = await fetch(url);
const body = await response.text();
return body;
}
/**
* Restore id and blockType to translations
*
* In order to update a document, we need to know the id and blockType of each block.
*
* Ideally, id and blockType are not sent to Crowdin - hence
* we need to restore them from the original document.
*
* This currently only works for a top-level `layout` blocks field.
*
* TODO: make this work for nested blocks.
*/
restoreIdAndBlockType = (
document: any,
translations: any,
key: string = "layout"
) => {
if (translations.hasOwnProperty(key)) {
translations[key] = translations[key].map(
(block: any, index: number) => ({
...block,
id: document[key][index].id,
blockType: document[key][index].blockType,
})
);
}
return translations;
};
}
| src/api/payload-crowdin-sync/translations.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/types.ts",
"retrieved_chunk": "import { Field } from \"payload/types\";\nexport interface CollectionOptions {\n directory?: string;\n}\nexport interface PluginOptions {\n projectId: number;\n /** This should be optional? */\n directoryId?: number;\n token: string;\n //client: crowdinAPIService,",
"score": 0.8664236068725586
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " sourceFilesApi: SourceFiles;\n uploadStorageApi: UploadStorage;\n projectId: number;\n directoryId?: number;\n payload: Payload;\n constructor(pluginOptions: PluginOptions, payload: Payload) {\n // credentials\n const credentials: Credentials = {\n token: pluginOptions.token,\n };",
"score": 0.861747682094574
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": "interface IupdateCrowdinFile extends IcreateOrUpdateFile {\n fileId: number;\n}\ninterface IgetTranslation {\n documentId: string;\n fieldName: string;\n locale: string;\n global?: boolean;\n}\nexport class payloadCrowdinSyncFilesApi {",
"score": 0.8584272861480713
},
{
"filename": "src/api/mock/crowdin-client.ts",
"retrieved_chunk": " });\n return file;\n }\n async buildProjectFileTranslation(\n projectId: number,\n fileId: number,\n { targetLanguageId }: TranslationsModel.BuildProjectFileTranslationRequest\n ): Promise<\n ResponseObject<TranslationsModel.BuildProjectFileTranslationResponse>\n > {",
"score": 0.8083296418190002
},
{
"filename": "src/fields/getFields.ts",
"retrieved_chunk": "import type { CollectionConfig, Field, GlobalConfig } from \"payload/types\";\ninterface Args {\n collection: CollectionConfig | GlobalConfig;\n}\nexport const getFields = ({ collection }: Args): Field[] => {\n const fields = [...collection.fields];\n const crowdinArticleDirectoryField: Field = {\n name: \"crowdinArticleDirectory\",\n type: \"relationship\",\n relationTo: \"crowdin-article-directories\",",
"score": 0.8077729940414429
}
] | typescript | : PluginOptions["sourceLocale"]; |
import crowdin, {
Credentials,
Translations,
} from "@crowdin/crowdin-api-client";
import { payloadCrowdinSyncFilesApi } from "./files";
import { mockCrowdinClient } from "../mock/crowdin-client";
import { Payload } from "payload";
import { PluginOptions } from "../../types";
import deepEqual from "deep-equal";
import {
CollectionConfig,
GlobalConfig,
SanitizedCollectionConfig,
SanitizedGlobalConfig,
} from "payload/types";
import { htmlToSlate, payloadHtmlToSlateConfig } from "slate-serializers";
import {
getLocalizedFields,
getFieldSlugs,
buildCrowdinJsonObject,
buildCrowdinHtmlObject,
buildPayloadUpdateObject,
getLocalizedRequiredFields,
} from "../../utilities";
interface IgetLatestDocumentTranslation {
collection: string;
doc: any;
locale: string;
global?: boolean;
}
interface IgetCurrentDocumentTranslation {
doc: any;
collection: string;
locale: string;
global?: boolean;
}
interface IgetTranslation {
documentId: string;
fieldName: string;
locale: string;
global?: boolean;
}
interface IupdateTranslation {
documentId: string;
collection: string;
dryRun?: boolean;
global?: boolean;
excludeLocales?: string[];
}
export class payloadCrowdinSyncTranslationsApi {
translationsApi: Translations;
filesApi: | payloadCrowdinSyncFilesApi; // our wrapper for file operations
projectId: number; |
directoryId?: number;
payload: Payload;
localeMap: PluginOptions["localeMap"];
sourceLocale: PluginOptions["sourceLocale"];
constructor(pluginOptions: PluginOptions, payload: Payload) {
// credentials
const credentials: Credentials = {
token: pluginOptions.token,
};
const { translationsApi } = new crowdin(credentials);
this.projectId = pluginOptions.projectId;
this.directoryId = pluginOptions.directoryId;
this.translationsApi =
process.env.NODE_ENV === "test"
? (mockCrowdinClient(pluginOptions) as any)
: translationsApi;
this.filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, payload);
this.payload = payload;
this.localeMap = pluginOptions.localeMap;
this.sourceLocale = pluginOptions.sourceLocale;
}
async updateTranslation({
documentId,
collection,
dryRun = true,
global = false,
excludeLocales = [],
}: IupdateTranslation) {
/**
* Get existing document
*
* * check document exists
* * check for `meta` field (which can be added by @payloadcms/seo)
*
*/
let doc: { crowdinArticleDirectory: { id: any } };
if (global) {
doc = await this.payload.findGlobal({
slug: collection,
locale: this.sourceLocale,
});
} else {
doc = await this.payload.findByID({
collection: collection,
id: documentId,
locale: this.sourceLocale,
});
}
const report: { [key: string]: any } = {};
for (const locale of Object.keys(this.localeMap)) {
if (excludeLocales.includes(locale)) {
continue;
}
report[locale] = {};
report[locale].currentTranslations =
await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
report[locale].latestTranslations =
await this.getLatestDocumentTranslation({
collection: collection,
doc: doc,
locale: locale,
global,
});
report[locale].changed = !deepEqual(
report[locale].currentTranslations,
report[locale].latestTranslations
);
if (report[locale].changed && !dryRun) {
if (global) {
try {
await this.payload.updateGlobal({
slug: collection,
locale: locale,
data: {
...report[locale].latestTranslations,
// error on update without the following line.
// see https://github.com/thompsonsj/payload-crowdin-sync/pull/13/files#r1209271660
crowdinArticleDirectory: doc.crowdinArticleDirectory.id,
},
});
} catch (error) {
console.log(error);
}
} else {
try {
await this.payload.update({
collection: collection,
locale: locale,
id: documentId,
data: report[locale].latestTranslations,
});
} catch (error) {
console.log(error);
}
}
}
}
return {
source: doc,
translations: { ...report },
};
}
getCollectionConfig(
collection: string,
global: boolean
): CollectionConfig | GlobalConfig {
let collectionConfig:
| SanitizedGlobalConfig
| SanitizedCollectionConfig
| undefined;
if (global) {
collectionConfig = this.payload.config.globals.find(
(col: GlobalConfig) => col.slug === collection
);
} else {
collectionConfig = this.payload.config.collections.find(
(col: CollectionConfig) => col.slug === collection
);
}
if (!collectionConfig)
throw new Error(`Collection ${collection} not found in payload config`);
return collectionConfig;
}
async getCurrentDocumentTranslation({
doc,
collection,
locale,
global = false,
}: IgetCurrentDocumentTranslation) {
// get document
let document: any;
if (global) {
document = await this.payload.findGlobal({
slug: collection,
locale: locale,
});
} else {
document = await this.payload.findByID({
collection: collection,
id: doc.id,
locale: locale,
});
}
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
// build crowdin json object
const crowdinJsonObject = buildCrowdinJsonObject({
doc: document,
fields: localizedFields,
});
const crowdinHtmlObject = buildCrowdinHtmlObject({
doc: document,
fields: localizedFields,
});
try {
const docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document,
});
return docTranslations;
} catch (error) {
console.log(error);
throw new Error(`${error}`);
}
}
/**
* Retrieve translations from Crowdin for a document in a given locale
*/
async getLatestDocumentTranslation({
collection,
doc,
locale,
global = false,
}: IgetLatestDocumentTranslation) {
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
if (!localizedFields) {
return { message: "no localized fields" };
}
let docTranslations: { [key: string]: any } = {};
// add json fields
const crowdinJsonObject =
(await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: "fields",
locale: locale,
})) || {};
// add html fields
const localizedHtmlFields = await this.getHtmlFieldSlugs(
global ? collectionConfig.slug : doc.id
);
let crowdinHtmlObject: { [key: string]: any } = {};
for (const field of localizedHtmlFields) {
crowdinHtmlObject[field] = await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: field,
locale: locale,
});
}
docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document: doc,
});
// Add required fields if not present
const requiredFieldSlugs = getFieldSlugs(
getLocalizedRequiredFields(collectionConfig)
);
if (requiredFieldSlugs.length > 0) {
const currentTranslations = await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
requiredFieldSlugs.forEach((slug) => {
if (!docTranslations.hasOwnProperty(slug)) {
docTranslations[slug] = currentTranslations[slug];
}
});
}
return docTranslations;
}
async getHtmlFieldSlugs(documentId: string) {
const files = await this.filesApi.getFilesByDocumentID(documentId);
return files
.filter((file: any) => file.type === "html")
.map((file: any) => file.field);
}
/**
* Retrieve translations for a document field name
*
* * returns Slate object for html fields
* * returns all json fields if fieldName is 'fields'
*/
async getTranslation({ documentId, fieldName, locale }: IgetTranslation) {
const articleDirectory = await this.filesApi.getArticleDirectory(
documentId
);
const file = await this.filesApi.getFile(fieldName, articleDirectory.id);
// it is possible a file doesn't exist yet - e.g. an article with localized text fields that contains an empty html field.
if (!file) {
return;
}
try {
const response = await this.translationsApi.buildProjectFileTranslation(
this.projectId,
file.originalId,
{
targetLanguageId: this.localeMap[locale].crowdinId,
}
);
const data = await this.getFileDataFromUrl(response.data.url);
return file.type === "html"
? htmlToSlate(data, payloadHtmlToSlateConfig)
: JSON.parse(data);
} catch (error) {
console.log(error);
}
}
private async getFileDataFromUrl(url: string) {
const response = await fetch(url);
const body = await response.text();
return body;
}
/**
* Restore id and blockType to translations
*
* In order to update a document, we need to know the id and blockType of each block.
*
* Ideally, id and blockType are not sent to Crowdin - hence
* we need to restore them from the original document.
*
* This currently only works for a top-level `layout` blocks field.
*
* TODO: make this work for nested blocks.
*/
restoreIdAndBlockType = (
document: any,
translations: any,
key: string = "layout"
) => {
if (translations.hasOwnProperty(key)) {
translations[key] = translations[key].map(
(block: any, index: number) => ({
...block,
id: document[key][index].id,
blockType: document[key][index].blockType,
})
);
}
return translations;
};
}
| src/api/payload-crowdin-sync/translations.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": "interface IupdateCrowdinFile extends IcreateOrUpdateFile {\n fileId: number;\n}\ninterface IgetTranslation {\n documentId: string;\n fieldName: string;\n locale: string;\n global?: boolean;\n}\nexport class payloadCrowdinSyncFilesApi {",
"score": 0.885024905204773
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { Field } from \"payload/types\";\nexport interface CollectionOptions {\n directory?: string;\n}\nexport interface PluginOptions {\n projectId: number;\n /** This should be optional? */\n directoryId?: number;\n token: string;\n //client: crowdinAPIService,",
"score": 0.875025749206543
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " sourceFilesApi: SourceFiles;\n uploadStorageApi: UploadStorage;\n projectId: number;\n directoryId?: number;\n payload: Payload;\n constructor(pluginOptions: PluginOptions, payload: Payload) {\n // credentials\n const credentials: Credentials = {\n token: pluginOptions.token,\n };",
"score": 0.8501989841461182
},
{
"filename": "src/types.ts",
"retrieved_chunk": " localeMap: {\n [key: string]: {\n crowdinId: string;\n };\n };\n sourceLocale: string;\n collections?: Record<string, CollectionOptions>;\n}\nexport type FieldWithName = Field & { name: string };",
"score": 0.8325921893119812
},
{
"filename": "src/hooks/collections/afterChange.ts",
"retrieved_chunk": " pluginOptions,\n });\n };\ninterface IPerformChange {\n doc: any;\n req: PayloadRequest;\n previousDoc: any;\n operation: string;\n collection: CollectionConfig | GlobalConfig;\n global?: boolean;",
"score": 0.8223240971565247
}
] | typescript | payloadCrowdinSyncFilesApi; // our wrapper for file operations
projectId: number; |
import type { Config } from "payload/config";
import type { PluginOptions } from "./types";
import {
getAfterChangeHook,
getGlobalAfterChangeHook,
} from "./hooks/collections/afterChange";
import { getAfterDeleteHook } from "./hooks/collections/afterDelete";
import { getFields } from "./fields/getFields";
import CrowdinFiles from "./collections/CrowdinFiles";
import CrowdinCollectionDirectories from "./collections/CrowdinCollectionDirectories";
import CrowdinArticleDirectories from "./collections/CrowdinArticleDirectories";
import { containsLocalizedFields } from "./utilities";
import { getReviewTranslationEndpoint } from "./endpoints/globals/reviewTranslation";
import { getReviewFieldsEndpoint } from "./endpoints/globals/reviewFields";
import Joi from "joi";
/**
* This plugin extends all collections that contain localized fields
* by uploading all translation-enabled field content in the default
* language to Crowdin for translation. Crowdin translations are
* are synced to fields in all other locales (except the default language).
*
**/
export const crowdinSync =
(pluginOptions: PluginOptions) =>
(config: Config): Config => {
const initFunctions: (() => void)[] = [];
// schema validation
const schema = Joi.object({
projectId: Joi.number().required(),
directoryId: Joi.number(),
// optional - if not provided, the plugin will not do anything in the afterChange hook.
token: Joi.string().required(),
localeMap: Joi.object().pattern(
/./,
Joi.object({
crowdinId: Joi.string().required(),
}).pattern(/./, Joi.any())
),
sourceLocale: Joi.string().required(),
});
const validate = schema.validate(pluginOptions);
if (validate.error) {
console.log(
"Payload Crowdin Sync option validation errors:",
validate.error
);
}
return {
...config,
admin: {
...(config.admin || {}),
},
collections: [
...(config.collections || []).map((existingCollection) => {
if ( | containsLocalizedFields({ fields: existingCollection.fields })) { |
const fields = getFields({
collection: existingCollection,
});
return {
...existingCollection,
hooks: {
...(existingCollection.hooks || {}),
afterChange: [
...(existingCollection.hooks?.afterChange || []),
getAfterChangeHook({
collection: existingCollection,
pluginOptions,
}),
],
afterDelete: [
...(existingCollection.hooks?.afterDelete || []),
getAfterDeleteHook({
pluginOptions,
}),
],
},
fields,
};
}
return existingCollection;
}),
CrowdinFiles,
CrowdinCollectionDirectories,
{
...CrowdinArticleDirectories,
fields: [
...(CrowdinArticleDirectories.fields || []),
{
name: "excludeLocales",
type: "select",
options: Object.keys(pluginOptions.localeMap),
hasMany: true,
admin: {
description:
"Select locales to exclude from translation synchronization.",
},
},
],
endpoints: [
...(CrowdinArticleDirectories.endpoints || []),
getReviewTranslationEndpoint({
pluginOptions,
}),
getReviewTranslationEndpoint({
pluginOptions,
type: "update",
}),
getReviewFieldsEndpoint({
pluginOptions
})
],
},
],
globals: [
...(config.globals || []).map((existingGlobal) => {
if (containsLocalizedFields({ fields: existingGlobal.fields })) {
const fields = getFields({
collection: existingGlobal,
});
return {
...existingGlobal,
hooks: {
...(existingGlobal.hooks || {}),
afterChange: [
...(existingGlobal.hooks?.afterChange || []),
getGlobalAfterChangeHook({
global: existingGlobal,
pluginOptions,
}),
],
},
fields,
};
}
return existingGlobal;
}),
],
onInit: async (payload) => {
initFunctions.forEach((fn) => fn());
if (config.onInit) await config.onInit(payload);
},
};
};
| src/plugin.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/endpoints/globals/reviewFields.ts",
"retrieved_chunk": " req.payload\n );\n try {\n const collectionConfig = await translationsApi.getCollectionConfig(global ? articleDirectory.name : articleDirectory.crowdinCollectionDirectory.collectionSlug, global)\n const response = {\n fields: collectionConfig.fields,\n localizedFields: getLocalizedFields({ fields: collectionConfig.fields })\n }\n res.status(200).send(response);\n } catch (error) {",
"score": 0.8347042798995972
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": " }\n const filteredFields = topLevel\n ? getLocalizedFields({\n fields,\n type: !crowdinHtmlObject ? \"json\" : undefined,\n })\n : fields;\n filteredFields.forEach((field) => {\n if (!crowdinJsonObject[field.name]) {\n return;",
"score": 0.832878589630127
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": " .map((field) => {\n const localizedParent = hasLocalizedProp(field);\n if (field.type === \"group\" || field.type === \"array\") {\n return {\n ...field,\n fields: getLocalizedFields({\n fields: field.fields,\n type,\n localizedParent,\n }),",
"score": 0.8265365362167358
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": " localizedParent?: boolean;\n}): any[] => [\n ...fields\n // localized or group fields only.\n .filter(\n (field) =>\n isLocalizedField(field, localizedParent) || containsNestedFields(field)\n )\n // further filter on Crowdin field type\n .filter((field) => {",
"score": 0.8206568956375122
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": " };\n }\n if (field.type === \"blocks\") {\n const blocks = field.blocks\n .map((block: Block) => {\n if (\n containsLocalizedFields({\n fields: block.fields,\n type,\n localizedParent,",
"score": 0.8196179270744324
}
] | typescript | containsLocalizedFields({ fields: existingCollection.fields })) { |
import type { Config } from "payload/config";
import type { PluginOptions } from "./types";
import {
getAfterChangeHook,
getGlobalAfterChangeHook,
} from "./hooks/collections/afterChange";
import { getAfterDeleteHook } from "./hooks/collections/afterDelete";
import { getFields } from "./fields/getFields";
import CrowdinFiles from "./collections/CrowdinFiles";
import CrowdinCollectionDirectories from "./collections/CrowdinCollectionDirectories";
import CrowdinArticleDirectories from "./collections/CrowdinArticleDirectories";
import { containsLocalizedFields } from "./utilities";
import { getReviewTranslationEndpoint } from "./endpoints/globals/reviewTranslation";
import { getReviewFieldsEndpoint } from "./endpoints/globals/reviewFields";
import Joi from "joi";
/**
* This plugin extends all collections that contain localized fields
* by uploading all translation-enabled field content in the default
* language to Crowdin for translation. Crowdin translations are
* are synced to fields in all other locales (except the default language).
*
**/
export const crowdinSync =
(pluginOptions: PluginOptions) =>
(config: Config): Config => {
const initFunctions: (() => void)[] = [];
// schema validation
const schema = Joi.object({
projectId: Joi.number().required(),
directoryId: Joi.number(),
// optional - if not provided, the plugin will not do anything in the afterChange hook.
token: Joi.string().required(),
localeMap: Joi.object().pattern(
/./,
Joi.object({
crowdinId: Joi.string().required(),
}).pattern(/./, Joi.any())
),
sourceLocale: Joi.string().required(),
});
const validate = schema.validate(pluginOptions);
if (validate.error) {
console.log(
"Payload Crowdin Sync option validation errors:",
validate.error
);
}
return {
...config,
admin: {
...(config.admin || {}),
},
collections: [
...(config.collections || []).map((existingCollection) => {
if (containsLocalizedFields({ fields: existingCollection.fields })) {
const fields = getFields({
collection: existingCollection,
});
return {
...existingCollection,
hooks: {
...(existingCollection.hooks || {}),
afterChange: [
...(existingCollection.hooks?.afterChange || []),
getAfterChangeHook({
collection: existingCollection,
pluginOptions,
}),
],
afterDelete: [
...(existingCollection.hooks?.afterDelete || []),
getAfterDeleteHook({
pluginOptions,
}),
],
},
fields,
};
}
return existingCollection;
}),
CrowdinFiles,
CrowdinCollectionDirectories,
{
| ...CrowdinArticleDirectories,
fields: [
...(CrowdinArticleDirectories.fields || []),
{ |
name: "excludeLocales",
type: "select",
options: Object.keys(pluginOptions.localeMap),
hasMany: true,
admin: {
description:
"Select locales to exclude from translation synchronization.",
},
},
],
endpoints: [
...(CrowdinArticleDirectories.endpoints || []),
getReviewTranslationEndpoint({
pluginOptions,
}),
getReviewTranslationEndpoint({
pluginOptions,
type: "update",
}),
getReviewFieldsEndpoint({
pluginOptions
})
],
},
],
globals: [
...(config.globals || []).map((existingGlobal) => {
if (containsLocalizedFields({ fields: existingGlobal.fields })) {
const fields = getFields({
collection: existingGlobal,
});
return {
...existingGlobal,
hooks: {
...(existingGlobal.hooks || {}),
afterChange: [
...(existingGlobal.hooks?.afterChange || []),
getGlobalAfterChangeHook({
global: existingGlobal,
pluginOptions,
}),
],
},
fields,
};
}
return existingGlobal;
}),
],
onInit: async (payload) => {
initFunctions.forEach((fn) => fn());
if (config.onInit) await config.onInit(payload);
},
};
};
| src/plugin.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " id: document.id,\n data: {\n crowdinArticleDirectory: crowdinPayloadArticleDirectory.id,\n },\n });\n }\n }\n return crowdinPayloadArticleDirectory;\n }\n private async findOrCreateCollectionDirectory({",
"score": 0.8412963151931763
},
{
"filename": "src/fields/getFields.ts",
"retrieved_chunk": "import type { CollectionConfig, Field, GlobalConfig } from \"payload/types\";\ninterface Args {\n collection: CollectionConfig | GlobalConfig;\n}\nexport const getFields = ({ collection }: Args): Field[] => {\n const fields = [...collection.fields];\n const crowdinArticleDirectoryField: Field = {\n name: \"crowdinArticleDirectory\",\n type: \"relationship\",\n relationTo: \"crowdin-article-directories\",",
"score": 0.8115103840827942
},
{
"filename": "src/collections/CrowdinArticleDirectories.ts",
"retrieved_chunk": "import { CollectionConfig } from \"payload/types\";\nconst CrowdinArticleDirectories: CollectionConfig = {\n slug: \"crowdin-article-directories\",\n admin: {\n defaultColumns: [\n \"name\",\n \"title\",\n \"crowdinCollectionDirectory\",\n \"createdAt\",\n ],",
"score": 0.8044527173042297
},
{
"filename": "src/api/helpers.ts",
"retrieved_chunk": " collection: \"crowdin-files\",\n where: {\n field: { equals: name },\n crowdinArticleDirectory: {\n equals: crowdinArticleDirectoryId,\n },\n },\n });\n return result.docs[0];\n}",
"score": 0.8042986989021301
},
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " locale: locale,\n });\n }\n docTranslations = buildPayloadUpdateObject({\n crowdinJsonObject,\n crowdinHtmlObject,\n fields: localizedFields,\n document: doc,\n });\n // Add required fields if not present",
"score": 0.7942076325416565
}
] | typescript | ...CrowdinArticleDirectories,
fields: [
...(CrowdinArticleDirectories.fields || []),
{ |
import {
Block,
CollapsibleField,
CollectionConfig,
Field,
GlobalConfig,
} from "payload/types";
import deepEqual from "deep-equal";
import { FieldWithName } from "../types";
import { slateToHtml, payloadSlateToDomConfig } from "slate-serializers";
import type { Descendant } from "slate";
import { get, isEmpty, map, merge, omitBy } from "lodash";
import dot from "dot-object";
const localizedFieldTypes = ["richText", "text", "textarea"];
const nestedFieldTypes = ["array", "group", "blocks"];
export const containsNestedFields = (field: Field) =>
nestedFieldTypes.includes(field.type);
export const getLocalizedFields = ({
fields,
type,
localizedParent = false,
}: {
fields: Field[];
type?: "json" | "html";
localizedParent?: boolean;
}): any[] => {
const localizedFields = getLocalizedFieldsRecursive({
fields,
type,
localizedParent,
});
return localizedFields;
};
export const getLocalizedFieldsRecursive = ({
fields,
type,
localizedParent = false,
}: {
fields: Field[];
type?: "json" | "html";
localizedParent?: boolean;
}): any[] => [
...fields
// localized or group fields only.
.filter(
(field) =>
isLocalizedField(field, localizedParent) || containsNestedFields(field)
)
// further filter on Crowdin field type
.filter((field) => {
if (containsNestedFields(field)) {
return true;
}
return type
| ? fieldCrowdinFileType(field as FieldWithName) === type
: true; |
})
// exclude group, array and block fields with no localized fields
// TODO: find a better way to do this - block, array and group logic is duplicated, and this filter needs to be compatible with field extraction logic later in this function
.filter((field) => {
const localizedParent = hasLocalizedProp(field);
if (field.type === "group" || field.type === "array") {
return containsLocalizedFields({
fields: field.fields,
type,
localizedParent,
});
}
if (field.type === "blocks") {
return field.blocks.find((block) =>
containsLocalizedFields({
fields: block.fields,
type,
localizedParent,
})
);
}
return true;
})
// recursion for group, array and blocks field
.map((field) => {
const localizedParent = hasLocalizedProp(field);
if (field.type === "group" || field.type === "array") {
return {
...field,
fields: getLocalizedFields({
fields: field.fields,
type,
localizedParent,
}),
};
}
if (field.type === "blocks") {
const blocks = field.blocks
.map((block: Block) => {
if (
containsLocalizedFields({
fields: block.fields,
type,
localizedParent,
})
) {
return {
slug: block.slug,
fields: getLocalizedFields({
fields: block.fields,
type,
localizedParent,
}),
};
}
})
.filter((block) => block);
return {
...field,
blocks,
};
}
return field;
})
.filter(
(field) =>
(field as any).type !== "collapsible" && (field as any).type !== "tabs"
),
...convertTabs({ fields }),
// recursion for collapsible field - flatten results into the returned array
...getCollapsibleLocalizedFields({ fields, type }),
];
export const getCollapsibleLocalizedFields = ({
fields,
type,
}: {
fields: Field[];
type?: "json" | "html";
}): any[] =>
fields
.filter((field) => field.type === "collapsible")
.flatMap((field) =>
getLocalizedFields({
fields: (field as CollapsibleField).fields,
type,
})
);
export const convertTabs = ({
fields,
type,
}: {
fields: Field[];
type?: "json" | "html";
}): any[] =>
fields
.filter((field) => field.type === "tabs")
.flatMap((field) => {
if (field.type === "tabs") {
const flattenedFields = field.tabs.reduce((tabFields, tab) => {
return [
...tabFields,
"name" in tab
? ({
type: "group",
name: tab.name,
fields: tab.fields,
} as Field)
: ({
label: "fromTab",
type: "collapsible",
fields: tab.fields,
} as Field),
];
}, [] as Field[]);
return getLocalizedFields({
fields: flattenedFields,
type,
});
}
return field;
});
export const getLocalizedRequiredFields = (
collection: CollectionConfig | GlobalConfig,
type?: "json" | "html"
): any[] => {
const fields = getLocalizedFields({ fields: collection.fields, type });
return fields.filter((field) => field.required);
};
/**
* Not yet compatible with nested fields - this means nested HTML
* field translations cannot be synced from Crowdin.
*/
export const getFieldSlugs = (fields: FieldWithName[]): string[] =>
fields
.filter(
(field: Field) => field.type === "text" || field.type === "richText"
)
.map((field: FieldWithName) => field.name);
const hasLocalizedProp = (field: Field) =>
"localized" in field && field.localized;
/**
* Is Localized Field
*
* Note that `id` should be excluded - it is a `text` field that is added by Payload CMS.
*/
export const isLocalizedField = (
field: Field,
addLocalizedProp: boolean = false
) =>
(hasLocalizedProp(field) || addLocalizedProp) &&
localizedFieldTypes.includes(field.type) &&
!excludeBasedOnDescription(field) &&
(field as any).name !== "id";
const excludeBasedOnDescription = (field: Field) => {
const description = get(field, "admin.description", "");
if (description.includes("Not sent to Crowdin. Localize in the CMS.")) {
return true;
}
return false;
};
export const containsLocalizedFields = ({
fields,
type,
localizedParent,
}: {
fields: Field[];
type?: "json" | "html";
localizedParent?: boolean;
}): boolean => {
return !isEmpty(getLocalizedFields({ fields, type, localizedParent }));
};
export const fieldChanged = (
previousValue: string | object | undefined,
value: string | object | undefined,
type: string
) => {
if (type === "richText") {
return !deepEqual(previousValue || {}, value || {});
}
return previousValue !== value;
};
export const removeLineBreaks = (string: string) =>
string.replace(/(\r\n|\n|\r)/gm, "");
export const fieldCrowdinFileType = (field: FieldWithName): "json" | "html" =>
field.type === "richText" ? "html" : "json";
/**
* Reorder blocks and array values based on the order of the original document.
*/
export const restoreOrder = ({
updateDocument,
document,
fields,
}: {
updateDocument: { [key: string]: any };
document: { [key: string]: any };
fields: Field[];
}) => {
let response: { [key: string]: any } = {};
// it is possible the original document is empty (e.g. new document)
if (!document) {
return updateDocument;
}
fields.forEach((field: any) => {
if (!updateDocument || !updateDocument[field.name]) {
return;
}
if (field.type === "group") {
response[field.name] = restoreOrder({
updateDocument: updateDocument[field.name],
document: document[field.name],
fields: field.fields,
});
} else if (field.type === "array" || field.type === "blocks") {
response[field.name] = document[field.name]
.map((item: any) => {
const arrayItem = updateDocument[field.name].find(
(updateItem: any) => {
return updateItem.id === item.id;
}
);
if (!arrayItem) {
return;
}
const subFields =
field.type === "blocks"
? field.blocks.find(
(block: Block) => block.slug === item.blockType
)?.fields || []
: field.fields;
return {
...restoreOrder({
updateDocument: arrayItem,
document: item,
fields: subFields,
}),
id: arrayItem.id,
...(field.type === "blocks" && { blockType: arrayItem.blockType }),
};
})
.filter((item: any) => !isEmpty(item));
} else {
response[field.name] = updateDocument[field.name];
}
});
return response;
};
/**
* Convert Crowdin objects to Payload CMS data objects.
*
* * `crowdinJsonObject` is the JSON object returned from Crowdin.
* * `crowdinHtmlObject` is the HTML object returned from Crowdin. Optional. Merged into resulting object if provided.
* * `fields` is the collection or global fields array.
* * `topLevel` is a flag used internally to filter json fields before recursion.
* * `document` is the document object. Optional. Used to restore the order of `array` and `blocks` field values.
*/
export const buildPayloadUpdateObject = ({
crowdinJsonObject,
crowdinHtmlObject,
fields,
topLevel = true,
document,
}: {
crowdinJsonObject: { [key: string]: any };
crowdinHtmlObject?: { [key: string]: any };
/** Use getLocalizedFields to pass localized fields only */
fields: Field[];
/** Flag used internally to filter json fields before recursion. */
topLevel?: boolean;
document?: { [key: string]: any };
}) => {
let response: { [key: string]: any } = {};
if (crowdinHtmlObject) {
const destructured = dot.object(crowdinHtmlObject);
merge(crowdinJsonObject, destructured);
}
const filteredFields = topLevel
? getLocalizedFields({
fields,
type: !crowdinHtmlObject ? "json" : undefined,
})
: fields;
filteredFields.forEach((field) => {
if (!crowdinJsonObject[field.name]) {
return;
}
if (field.type === "group") {
response[field.name] = buildPayloadUpdateObject({
crowdinJsonObject: crowdinJsonObject[field.name],
fields: field.fields,
topLevel: false,
});
} else if (field.type === "array") {
response[field.name] = map(crowdinJsonObject[field.name], (item, id) => {
const payloadUpdateObject = buildPayloadUpdateObject({
crowdinJsonObject: item,
fields: field.fields,
topLevel: false,
});
return {
...payloadUpdateObject,
id,
};
}).filter((item: any) => !isEmpty(item));
} else if (field.type === "blocks") {
response[field.name] = map(crowdinJsonObject[field.name], (item, id) => {
// get first and only object key
const blockType = Object.keys(item)[0];
const payloadUpdateObject = buildPayloadUpdateObject({
crowdinJsonObject: item[blockType],
fields:
field.blocks.find((block: Block) => block.slug === blockType)
?.fields || [],
topLevel: false,
});
return {
...payloadUpdateObject,
id,
blockType,
};
}).filter((item: any) => !isEmpty(item));
} else {
response[field.name] = crowdinJsonObject[field.name];
}
});
if (document) {
response = restoreOrder({
updateDocument: response,
document,
fields,
});
}
return omitBy(response, isEmpty);
};
export const buildCrowdinJsonObject = ({
doc,
fields,
topLevel = true,
}: {
doc: { [key: string]: any };
/** Use getLocalizedFields to pass localized fields only */
fields: Field[];
/** Flag used internally to filter json fields before recursion. */
topLevel?: boolean;
}) => {
let response: { [key: string]: any } = {};
const filteredFields = topLevel
? getLocalizedFields({ fields, type: "json" })
: fields;
filteredFields.forEach((field) => {
if (!doc[field.name]) {
return;
}
if (field.type === "group") {
response[field.name] = buildCrowdinJsonObject({
doc: doc[field.name],
fields: field.fields,
topLevel: false,
});
} else if (field.type === "array") {
response[field.name] = doc[field.name]
.map((item: any) => {
const crowdinJsonObject = buildCrowdinJsonObject({
doc: item,
fields: field.fields,
topLevel: false,
});
if (!isEmpty(crowdinJsonObject)) {
return {
[item.id]: crowdinJsonObject,
};
}
})
.filter((item: any) => !isEmpty(item))
.reduce((acc: object, item: any) => ({ ...acc, ...item }), {});
} else if (field.type === "blocks") {
response[field.name] = doc[field.name]
.map((item: any) => {
const crowdinJsonObject = buildCrowdinJsonObject({
doc: item,
fields:
field.blocks.find((block: Block) => block.slug === item.blockType)
?.fields || [],
topLevel: false,
});
if (!isEmpty(crowdinJsonObject)) {
return {
[item.id]: {
[item.blockType]: crowdinJsonObject,
},
};
}
})
.filter((item: any) => !isEmpty(item))
.reduce((acc: object, item: any) => ({ ...acc, ...item }), {});
} else {
response[field.name] = doc[field.name];
}
});
return omitBy(response, isEmpty);
};
export const buildCrowdinHtmlObject = ({
doc,
fields,
prefix = "",
topLevel = true,
}: {
doc: { [key: string]: any };
/** Use getLocalizedFields to pass localized fields only */
fields: Field[];
/** Use to build dot notation field during recursion. */
prefix?: string;
/** Flag used internally to filter html fields before recursion. */
topLevel?: boolean;
}) => {
let response: { [key: string]: any } = {};
// it is convenient to be able to pass all fields - filter in this case
const filteredFields = topLevel
? getLocalizedFields({ fields, type: "html" })
: fields;
filteredFields.forEach((field) => {
const name = [prefix, (field as FieldWithName).name]
.filter((string) => string)
.join(".");
if (!doc[field.name]) {
return;
}
if (field.type === "group") {
const subPrefix = `${[prefix, field.name]
.filter((string) => string)
.join(".")}`;
response = {
...response,
...buildCrowdinHtmlObject({
doc: doc[field.name],
fields: field.fields,
prefix: subPrefix,
topLevel: false,
}),
};
} else if (field.type === "array") {
const arrayValues = doc[field.name].map((item: any, index: number) => {
const subPrefix = `${[prefix, `${field.name}`, `${item.id}`]
.filter((string) => string)
.join(".")}`;
return buildCrowdinHtmlObject({
doc: item,
fields: field.fields,
prefix: subPrefix,
topLevel: false,
});
});
response = {
...response,
...merge({}, ...arrayValues),
};
} else if (field.type === "blocks") {
const arrayValues = doc[field.name].map((item: any, index: number) => {
const subPrefix = `${[
prefix,
`${field.name}`,
`${item.id}`,
`${item.blockType}`,
]
.filter((string) => string)
.join(".")}`;
return buildCrowdinHtmlObject({
doc: item,
fields:
field.blocks.find((block: Block) => block.slug === item.blockType)
?.fields || [],
prefix: subPrefix,
topLevel: false,
});
});
response = {
...response,
...merge({}, ...arrayValues),
};
} else {
if (doc[field.name]?.en) {
response[name] = doc[field.name].en;
} else {
response[name] = doc[field.name];
}
}
});
return response;
};
export const convertSlateToHtml = (slate: Descendant[]): string => {
return slateToHtml(slate, {
...payloadSlateToDomConfig,
encodeEntities: false,
alwaysEncodeBreakingEntities: true,
});
};
| src/utilities/index.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/plugin.ts",
"retrieved_chunk": " ],\n },\n ],\n globals: [\n ...(config.globals || []).map((existingGlobal) => {\n if (containsLocalizedFields({ fields: existingGlobal.fields })) {\n const fields = getFields({\n collection: existingGlobal,\n });\n return {",
"score": 0.8537325859069824
},
{
"filename": "src/plugin.ts",
"retrieved_chunk": " ...(config.admin || {}),\n },\n collections: [\n ...(config.collections || []).map((existingCollection) => {\n if (containsLocalizedFields({ fields: existingCollection.fields })) {\n const fields = getFields({\n collection: existingCollection,\n });\n return {\n ...existingCollection,",
"score": 0.8325037956237793
},
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " async getTranslation({ documentId, fieldName, locale }: IgetTranslation) {\n const articleDirectory = await this.filesApi.getArticleDirectory(\n documentId\n );\n const file = await this.filesApi.getFile(fieldName, articleDirectory.id);\n // it is possible a file doesn't exist yet - e.g. an article with localized text fields that contains an empty html field.\n if (!file) {\n return;\n }\n try {",
"score": 0.8240920305252075
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/group-field-type.spec.ts",
"retrieved_chunk": " localized: true,\n },\n {\n name: \"groupField\",\n type: \"group\",\n localized: true,\n fields: basicNonLocalizedFields,\n },\n ];\n const localizedFields = getLocalizedFields({ fields });",
"score": 0.8231875896453857
},
{
"filename": "src/hooks/collections/afterChange.ts",
"retrieved_chunk": "}: IPerformChange) => {\n /**\n * Abort if token not set and not in test mode\n */\n if (!pluginOptions.token && process.env.NODE_ENV !== \"test\") {\n return doc;\n }\n const localizedFields: Field[] = getLocalizedFields({\n fields: collection.fields,\n });",
"score": 0.8228543400764465
}
] | typescript | ? fieldCrowdinFileType(field as FieldWithName) === type
: true; |
import type { Config } from "payload/config";
import type { PluginOptions } from "./types";
import {
getAfterChangeHook,
getGlobalAfterChangeHook,
} from "./hooks/collections/afterChange";
import { getAfterDeleteHook } from "./hooks/collections/afterDelete";
import { getFields } from "./fields/getFields";
import CrowdinFiles from "./collections/CrowdinFiles";
import CrowdinCollectionDirectories from "./collections/CrowdinCollectionDirectories";
import CrowdinArticleDirectories from "./collections/CrowdinArticleDirectories";
import { containsLocalizedFields } from "./utilities";
import { getReviewTranslationEndpoint } from "./endpoints/globals/reviewTranslation";
import { getReviewFieldsEndpoint } from "./endpoints/globals/reviewFields";
import Joi from "joi";
/**
* This plugin extends all collections that contain localized fields
* by uploading all translation-enabled field content in the default
* language to Crowdin for translation. Crowdin translations are
* are synced to fields in all other locales (except the default language).
*
**/
export const crowdinSync =
(pluginOptions: PluginOptions) =>
(config: Config): Config => {
const initFunctions: (() => void)[] = [];
// schema validation
const schema = Joi.object({
projectId: Joi.number().required(),
directoryId: Joi.number(),
// optional - if not provided, the plugin will not do anything in the afterChange hook.
token: Joi.string().required(),
localeMap: Joi.object().pattern(
/./,
Joi.object({
crowdinId: Joi.string().required(),
}).pattern(/./, Joi.any())
),
sourceLocale: Joi.string().required(),
});
const validate = schema.validate(pluginOptions);
if (validate.error) {
console.log(
"Payload Crowdin Sync option validation errors:",
validate.error
);
}
return {
...config,
admin: {
...(config.admin || {}),
},
collections: [
...(config.collections || []).map((existingCollection) => {
if (containsLocalizedFields({ fields: existingCollection.fields })) {
| const fields = getFields({ |
collection: existingCollection,
});
return {
...existingCollection,
hooks: {
...(existingCollection.hooks || {}),
afterChange: [
...(existingCollection.hooks?.afterChange || []),
getAfterChangeHook({
collection: existingCollection,
pluginOptions,
}),
],
afterDelete: [
...(existingCollection.hooks?.afterDelete || []),
getAfterDeleteHook({
pluginOptions,
}),
],
},
fields,
};
}
return existingCollection;
}),
CrowdinFiles,
CrowdinCollectionDirectories,
{
...CrowdinArticleDirectories,
fields: [
...(CrowdinArticleDirectories.fields || []),
{
name: "excludeLocales",
type: "select",
options: Object.keys(pluginOptions.localeMap),
hasMany: true,
admin: {
description:
"Select locales to exclude from translation synchronization.",
},
},
],
endpoints: [
...(CrowdinArticleDirectories.endpoints || []),
getReviewTranslationEndpoint({
pluginOptions,
}),
getReviewTranslationEndpoint({
pluginOptions,
type: "update",
}),
getReviewFieldsEndpoint({
pluginOptions
})
],
},
],
globals: [
...(config.globals || []).map((existingGlobal) => {
if (containsLocalizedFields({ fields: existingGlobal.fields })) {
const fields = getFields({
collection: existingGlobal,
});
return {
...existingGlobal,
hooks: {
...(existingGlobal.hooks || {}),
afterChange: [
...(existingGlobal.hooks?.afterChange || []),
getGlobalAfterChangeHook({
global: existingGlobal,
pluginOptions,
}),
],
},
fields,
};
}
return existingGlobal;
}),
],
onInit: async (payload) => {
initFunctions.forEach((fn) => fn());
if (config.onInit) await config.onInit(payload);
},
};
};
| src/plugin.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": " }\n const filteredFields = topLevel\n ? getLocalizedFields({\n fields,\n type: !crowdinHtmlObject ? \"json\" : undefined,\n })\n : fields;\n filteredFields.forEach((field) => {\n if (!crowdinJsonObject[field.name]) {\n return;",
"score": 0.8554486036300659
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": " .map((field) => {\n const localizedParent = hasLocalizedProp(field);\n if (field.type === \"group\" || field.type === \"array\") {\n return {\n ...field,\n fields: getLocalizedFields({\n fields: field.fields,\n type,\n localizedParent,\n }),",
"score": 0.8509751558303833
},
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " async getLatestDocumentTranslation({\n collection,\n doc,\n locale,\n global = false,\n }: IgetLatestDocumentTranslation) {\n const collectionConfig = this.getCollectionConfig(collection, global);\n const localizedFields = getLocalizedFields({\n fields: collectionConfig.fields,\n });",
"score": 0.8472775220870972
},
{
"filename": "src/endpoints/globals/reviewFields.ts",
"retrieved_chunk": " req.payload\n );\n try {\n const collectionConfig = await translationsApi.getCollectionConfig(global ? articleDirectory.name : articleDirectory.crowdinCollectionDirectory.collectionSlug, global)\n const response = {\n fields: collectionConfig.fields,\n localizedFields: getLocalizedFields({ fields: collectionConfig.fields })\n }\n res.status(200).send(response);\n } catch (error) {",
"score": 0.845445990562439
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/group-field-type.spec.ts",
"retrieved_chunk": " localized: true,\n },\n {\n name: \"groupField\",\n type: \"group\",\n localized: true,\n fields: basicNonLocalizedFields,\n },\n ];\n const localizedFields = getLocalizedFields({ fields });",
"score": 0.8380609750747681
}
] | typescript | const fields = getFields({ |
import crowdin, {
Credentials,
Translations,
} from "@crowdin/crowdin-api-client";
import { payloadCrowdinSyncFilesApi } from "./files";
import { mockCrowdinClient } from "../mock/crowdin-client";
import { Payload } from "payload";
import { PluginOptions } from "../../types";
import deepEqual from "deep-equal";
import {
CollectionConfig,
GlobalConfig,
SanitizedCollectionConfig,
SanitizedGlobalConfig,
} from "payload/types";
import { htmlToSlate, payloadHtmlToSlateConfig } from "slate-serializers";
import {
getLocalizedFields,
getFieldSlugs,
buildCrowdinJsonObject,
buildCrowdinHtmlObject,
buildPayloadUpdateObject,
getLocalizedRequiredFields,
} from "../../utilities";
interface IgetLatestDocumentTranslation {
collection: string;
doc: any;
locale: string;
global?: boolean;
}
interface IgetCurrentDocumentTranslation {
doc: any;
collection: string;
locale: string;
global?: boolean;
}
interface IgetTranslation {
documentId: string;
fieldName: string;
locale: string;
global?: boolean;
}
interface IupdateTranslation {
documentId: string;
collection: string;
dryRun?: boolean;
global?: boolean;
excludeLocales?: string[];
}
export class payloadCrowdinSyncTranslationsApi {
translationsApi: Translations;
filesApi: payloadCrowdinSyncFilesApi; // our wrapper for file operations
projectId: number;
directoryId?: number;
payload: Payload;
| localeMap: PluginOptions["localeMap"]; |
sourceLocale: PluginOptions["sourceLocale"];
constructor(pluginOptions: PluginOptions, payload: Payload) {
// credentials
const credentials: Credentials = {
token: pluginOptions.token,
};
const { translationsApi } = new crowdin(credentials);
this.projectId = pluginOptions.projectId;
this.directoryId = pluginOptions.directoryId;
this.translationsApi =
process.env.NODE_ENV === "test"
? (mockCrowdinClient(pluginOptions) as any)
: translationsApi;
this.filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, payload);
this.payload = payload;
this.localeMap = pluginOptions.localeMap;
this.sourceLocale = pluginOptions.sourceLocale;
}
async updateTranslation({
documentId,
collection,
dryRun = true,
global = false,
excludeLocales = [],
}: IupdateTranslation) {
/**
* Get existing document
*
* * check document exists
* * check for `meta` field (which can be added by @payloadcms/seo)
*
*/
let doc: { crowdinArticleDirectory: { id: any } };
if (global) {
doc = await this.payload.findGlobal({
slug: collection,
locale: this.sourceLocale,
});
} else {
doc = await this.payload.findByID({
collection: collection,
id: documentId,
locale: this.sourceLocale,
});
}
const report: { [key: string]: any } = {};
for (const locale of Object.keys(this.localeMap)) {
if (excludeLocales.includes(locale)) {
continue;
}
report[locale] = {};
report[locale].currentTranslations =
await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
report[locale].latestTranslations =
await this.getLatestDocumentTranslation({
collection: collection,
doc: doc,
locale: locale,
global,
});
report[locale].changed = !deepEqual(
report[locale].currentTranslations,
report[locale].latestTranslations
);
if (report[locale].changed && !dryRun) {
if (global) {
try {
await this.payload.updateGlobal({
slug: collection,
locale: locale,
data: {
...report[locale].latestTranslations,
// error on update without the following line.
// see https://github.com/thompsonsj/payload-crowdin-sync/pull/13/files#r1209271660
crowdinArticleDirectory: doc.crowdinArticleDirectory.id,
},
});
} catch (error) {
console.log(error);
}
} else {
try {
await this.payload.update({
collection: collection,
locale: locale,
id: documentId,
data: report[locale].latestTranslations,
});
} catch (error) {
console.log(error);
}
}
}
}
return {
source: doc,
translations: { ...report },
};
}
getCollectionConfig(
collection: string,
global: boolean
): CollectionConfig | GlobalConfig {
let collectionConfig:
| SanitizedGlobalConfig
| SanitizedCollectionConfig
| undefined;
if (global) {
collectionConfig = this.payload.config.globals.find(
(col: GlobalConfig) => col.slug === collection
);
} else {
collectionConfig = this.payload.config.collections.find(
(col: CollectionConfig) => col.slug === collection
);
}
if (!collectionConfig)
throw new Error(`Collection ${collection} not found in payload config`);
return collectionConfig;
}
async getCurrentDocumentTranslation({
doc,
collection,
locale,
global = false,
}: IgetCurrentDocumentTranslation) {
// get document
let document: any;
if (global) {
document = await this.payload.findGlobal({
slug: collection,
locale: locale,
});
} else {
document = await this.payload.findByID({
collection: collection,
id: doc.id,
locale: locale,
});
}
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
// build crowdin json object
const crowdinJsonObject = buildCrowdinJsonObject({
doc: document,
fields: localizedFields,
});
const crowdinHtmlObject = buildCrowdinHtmlObject({
doc: document,
fields: localizedFields,
});
try {
const docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document,
});
return docTranslations;
} catch (error) {
console.log(error);
throw new Error(`${error}`);
}
}
/**
* Retrieve translations from Crowdin for a document in a given locale
*/
async getLatestDocumentTranslation({
collection,
doc,
locale,
global = false,
}: IgetLatestDocumentTranslation) {
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
if (!localizedFields) {
return { message: "no localized fields" };
}
let docTranslations: { [key: string]: any } = {};
// add json fields
const crowdinJsonObject =
(await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: "fields",
locale: locale,
})) || {};
// add html fields
const localizedHtmlFields = await this.getHtmlFieldSlugs(
global ? collectionConfig.slug : doc.id
);
let crowdinHtmlObject: { [key: string]: any } = {};
for (const field of localizedHtmlFields) {
crowdinHtmlObject[field] = await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: field,
locale: locale,
});
}
docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document: doc,
});
// Add required fields if not present
const requiredFieldSlugs = getFieldSlugs(
getLocalizedRequiredFields(collectionConfig)
);
if (requiredFieldSlugs.length > 0) {
const currentTranslations = await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
requiredFieldSlugs.forEach((slug) => {
if (!docTranslations.hasOwnProperty(slug)) {
docTranslations[slug] = currentTranslations[slug];
}
});
}
return docTranslations;
}
async getHtmlFieldSlugs(documentId: string) {
const files = await this.filesApi.getFilesByDocumentID(documentId);
return files
.filter((file: any) => file.type === "html")
.map((file: any) => file.field);
}
/**
* Retrieve translations for a document field name
*
* * returns Slate object for html fields
* * returns all json fields if fieldName is 'fields'
*/
async getTranslation({ documentId, fieldName, locale }: IgetTranslation) {
const articleDirectory = await this.filesApi.getArticleDirectory(
documentId
);
const file = await this.filesApi.getFile(fieldName, articleDirectory.id);
// it is possible a file doesn't exist yet - e.g. an article with localized text fields that contains an empty html field.
if (!file) {
return;
}
try {
const response = await this.translationsApi.buildProjectFileTranslation(
this.projectId,
file.originalId,
{
targetLanguageId: this.localeMap[locale].crowdinId,
}
);
const data = await this.getFileDataFromUrl(response.data.url);
return file.type === "html"
? htmlToSlate(data, payloadHtmlToSlateConfig)
: JSON.parse(data);
} catch (error) {
console.log(error);
}
}
private async getFileDataFromUrl(url: string) {
const response = await fetch(url);
const body = await response.text();
return body;
}
/**
* Restore id and blockType to translations
*
* In order to update a document, we need to know the id and blockType of each block.
*
* Ideally, id and blockType are not sent to Crowdin - hence
* we need to restore them from the original document.
*
* This currently only works for a top-level `layout` blocks field.
*
* TODO: make this work for nested blocks.
*/
restoreIdAndBlockType = (
document: any,
translations: any,
key: string = "layout"
) => {
if (translations.hasOwnProperty(key)) {
translations[key] = translations[key].map(
(block: any, index: number) => ({
...block,
id: document[key][index].id,
blockType: document[key][index].blockType,
})
);
}
return translations;
};
}
| src/api/payload-crowdin-sync/translations.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": "interface IupdateCrowdinFile extends IcreateOrUpdateFile {\n fileId: number;\n}\ninterface IgetTranslation {\n documentId: string;\n fieldName: string;\n locale: string;\n global?: boolean;\n}\nexport class payloadCrowdinSyncFilesApi {",
"score": 0.8853855133056641
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { Field } from \"payload/types\";\nexport interface CollectionOptions {\n directory?: string;\n}\nexport interface PluginOptions {\n projectId: number;\n /** This should be optional? */\n directoryId?: number;\n token: string;\n //client: crowdinAPIService,",
"score": 0.8733884692192078
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " sourceFilesApi: SourceFiles;\n uploadStorageApi: UploadStorage;\n projectId: number;\n directoryId?: number;\n payload: Payload;\n constructor(pluginOptions: PluginOptions, payload: Payload) {\n // credentials\n const credentials: Credentials = {\n token: pluginOptions.token,\n };",
"score": 0.8374347686767578
},
{
"filename": "src/fields/getFields.ts",
"retrieved_chunk": "import type { CollectionConfig, Field, GlobalConfig } from \"payload/types\";\ninterface Args {\n collection: CollectionConfig | GlobalConfig;\n}\nexport const getFields = ({ collection }: Args): Field[] => {\n const fields = [...collection.fields];\n const crowdinArticleDirectoryField: Field = {\n name: \"crowdinArticleDirectory\",\n type: \"relationship\",\n relationTo: \"crowdin-article-directories\",",
"score": 0.8135849833488464
},
{
"filename": "src/api/mock/crowdin-client.ts",
"retrieved_chunk": " });\n return file;\n }\n async buildProjectFileTranslation(\n projectId: number,\n fileId: number,\n { targetLanguageId }: TranslationsModel.BuildProjectFileTranslationRequest\n ): Promise<\n ResponseObject<TranslationsModel.BuildProjectFileTranslationResponse>\n > {",
"score": 0.8072811365127563
}
] | typescript | localeMap: PluginOptions["localeMap"]; |
import JSON5 from 'json5'
import { validate } from 'jsonschema'
import { AudienceIntentInfo, PostOutline, SeoInfo } from '../types'
export class PostOutlineValidationError extends Error {
constructor (message: string, public readonly errors: any[]) {
super(message)
}
}
const schemaValidiation = {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
properties: {
title: {
type: 'string'
},
headings: {
type: 'array',
items: {
$ref: '#/definitions/Heading'
}
},
slug: {
type: 'string'
},
seoTitle: {
type: 'string'
},
seoDescription: {
type: 'string'
}
},
required: [
'title',
'headings',
'slug',
'seoTitle',
'seoDescription'
],
additionalProperties: false,
definitions: {
Heading: {
type: 'object',
properties: {
title: {
type: 'string'
},
keywords: {
type: 'array',
items: {
type: 'string'
}
},
headings: {
type: 'array',
items: {
$ref: '#/definitions/Heading'
}
}
},
required: [
'title'
],
additionalProperties: false
}
}
}
export function extractCodeBlock (text: string): string {
// Extract code blocks with specified tags
const codeBlockTags = ['markdown', 'html', 'json']
for (const tag of codeBlockTags) {
const regex = new RegExp(`\`\`\`${tag}((.|\\n|\\r)*?)\`\`\``, 'i')
const match = text.match(regex)
if (match) {
return match[1]
}
}
// Extract code blocks without specified tags
const genericRegex = /```\n?((.|\\n|\\r)*?)```/
const genericMatch = text.match(genericRegex)
if (genericMatch) {
return genericMatch[1]
}
// No code blocks found
return text
}
export function extractPostOutlineFromCodeBlock (text: string | ) : PostOutline { |
// Use JSON5 because it supports trailing comma and comments in the json text
const jsonData = JSON5.parse(extractCodeBlock(text))
const v = validate(jsonData, schemaValidiation)
if (!v.valid) {
const errorList = v.errors.map((val) => val.toString())
throw new PostOutlineValidationError('Invalid json for the post outline', errorList)
}
return jsonData
}
export function extractJsonArray (text : string) : string[] {
return JSON5.parse(extractCodeBlock(text))
}
export function extractSeoInfo (text : string) : SeoInfo {
return JSON5.parse(extractCodeBlock(text))
}
export function extractAudienceIntentInfo (text : string) : AudienceIntentInfo {
return JSON5.parse(extractCodeBlock(text))
}
| src/lib/extractor.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/template.ts",
"retrieved_chunk": "export function extractPrompts (template: string): string[] {\n const regex = /{\\d+:((?:.|\\n)*?)}/g\n return Array.from(template.matchAll(regex)).map((match) => match[1].trim())\n}\nexport function replacePrompt (template: string, index: number, content: string): string {\n const regex = new RegExp(`{${index}:((?:.|\\n)*?)}`)\n return template.replace(regex, content)\n}\nexport function replaceAllPrompts (template: string, contents: string[]): string {\n // We are removing the first prompt because it is the system prompt",
"score": 0.8066145181655884
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " async generateConclusion () {\n const response = await this.sendRequest(getPromptForConclusion(), this.completionParams)\n return extractCodeBlock(response.text)\n }\n async generateHeadingContents (postOutline : PostOutline) {\n const headingLevel = 2\n return await this.buildContent(postOutline.headings, headingLevel)\n }\n private async buildContent (headings: Heading[], headingLevel : number, previousContent: string = ''): Promise<string> {\n if (headings.length === 0) {",
"score": 0.7764686942100525
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": "}\nfunction getFileExtension (options : Options) {\n // in custom mode, we use the template extension\n // in auto/default mode, we use the markdown extension in all cases\n return isCustom(options) ? options.templateFile.split('.').pop() : 'md'\n}\nfunction buildMDPage (post: Post) {\n return '# ' + post.title + '\\n' + post.content\n}\nfunction buildHTMLPage (post : Post) {",
"score": 0.7655256986618042
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " return this.buildContent(remainingHeadings, headingLevel, content)\n }\n private async getContent (heading: Heading): Promise<string> {\n if (this.postPrompt.debug) {\n console.log(`\\nHeading : ${heading.title} ...'\\n`)\n }\n const response = await this.sendRequest(getPromptForHeading(this.postPrompt.tone, heading.title, heading.keywords), this.completionParams)\n return `${extractCodeBlock(response.text)}\\n`\n }\n // -----------------------------------------------",
"score": 0.7607646584510803
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " log('---------- SEO INFO ----------')\n console.log(this.chatParentMessage.text)\n }\n return extractSeoInfo(this.chatParentMessage.text)\n }\n private async readTemplate () : Promise<string> {\n const templatePath = this.postPrompt.templateFile\n return await readFile(templatePath, 'utf-8')\n }\n // -----------------------------------------------",
"score": 0.7574090957641602
}
] | typescript | ) : PostOutline { |
import * as dotenv from 'dotenv'
import { readFile as rd } from 'fs'
import { promisify } from 'util'
import { ChatGPTAPI, ChatGPTError, ChatMessage, SendMessageOptions } from 'chatgpt'
import pRetry, { AbortError, FailedAttemptError } from 'p-retry'
import { extractJsonArray, extractCodeBlock, extractPostOutlineFromCodeBlock, extractSeoInfo, extractAudienceIntentInfo } from './extractor'
import {
getPromptForMainKeyword,
getPromptForOutline,
getPromptForIntroduction,
getPromptForHeading,
getPromptForConclusion,
getAutoSystemPrompt,
getPromptForSeoInfo,
getCustomSystemPrompt,
getSeoSystemPrompt,
getPromptForIntentAudience as getPromptForAudienceIntent
} from './prompts'
import {
Heading,
PostOutline,
PostPrompt,
TotalTokens,
SeoInfo
} from '../types'
import { encode } from './tokenizer'
import { extractPrompts } from './template'
import { log } from 'console'
import { NoApiKeyError } from './errors'
dotenv.config()
const readFile = promisify(rd)
/**
* Specific Open AI API parameters for the completion
*/
export type CompletionParams = {
temperature?: number | null,
top_p?: number | null,
max_tokens?: number,
presence_penalty?: number | null,
frequency_penalty?: number | null,
logit_bias?: object | null,
}
/**
* Interface for the helper class for generating a post. it defines how to generate a post
* Each helper class must implement this interface
* @interface
*/
export interface GeneratorHelperInterface {
init () : Promise<void>
isCustom() : boolean
generateContentOutline () : Promise<PostOutline>
generateMainKeyword () : Promise<string[]>
generateIntroduction () : Promise<string>
generateConclusion () : Promise<string>
generateHeadingContents (tableOfContent : PostOutline) : Promise<string>
generateCustomPrompt(prompt : string) : Promise<string>
generateSeoInfo () : Promise<SeoInfo>
getTotalTokens() : TotalTokens
getPrompt() : PostPrompt
}
/**
* Helper implementation for generating a post using the ChatGPT API
* @class
*/
export class ChatGptHelper implements GeneratorHelperInterface {
private postPrompt : PostPrompt
private api : ChatGPTAPI
// The parent message is either the previous one in the conversation (if a template is used)
// or the generated outline (if we are in auto mode)
private chatParentMessage : ChatMessage
private completionParams : CompletionParams
private totalTokens : TotalTokens = {
promptTokens: 0,
completionTokens: 0,
total: 0
}
// -----------------------------------------------
// CONSTRUCTOR AND INITIALIZATION
// -----------------------------------------------
public constructor (postPrompt : PostPrompt) {
this.postPrompt = postPrompt
}
isCustom () : boolean {
return this.postPrompt?.templateFile !== undefined
}
getPrompt (): PostPrompt {
return this.postPrompt
}
getTotalTokens (): TotalTokens {
return this.totalTokens
}
async init () {
if (this.isCustom()) {
if (this.postPrompt.debug) {
console.log(`Use template : ${this.postPrompt.templateFile}`)
}
this.postPrompt.templateContent = await this.readTemplate()
this.postPrompt. | prompts = extractPrompts(this.postPrompt.templateContent)
} |
const systemMessage = this.isCustom() ? getCustomSystemPrompt(this.postPrompt) : getAutoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemMessage)
}
private async buildChatGPTAPI (systemMessage : string) {
try {
this.api = new ChatGPTAPI({
apiKey: this.postPrompt?.apiKey || process.env.OPENAI_API_KEY,
completionParams: {
model: this.postPrompt.model
},
systemMessage,
debug: this.postPrompt.debugapi
})
} catch (error) {
throw new NoApiKeyError()
}
if (this.postPrompt.debug) {
console.log(`OpenAI API initialized with model : ${this.postPrompt.model}`)
}
this.completionParams = {
temperature: this.postPrompt.temperature ?? 0.8,
frequency_penalty: this.postPrompt.frequencyPenalty ?? 0,
presence_penalty: this.postPrompt.presencePenalty ?? 1
}
if (this.postPrompt.logitBias) {
const mainKwWords = await this.generateMainKeyword()
// set the logit bias in order to force the model to minimize the usage of the main keyword
const logitBiais: Record<number, number> = {}
mainKwWords.forEach((kw) => {
const encoded = encode(kw)
encoded.forEach((element) => {
logitBiais[element] = Number(this.postPrompt.logitBias) || -1
})
})
this.completionParams.logit_bias = logitBiais
}
if (this.postPrompt.debug) {
console.log('---------- COMPLETION PARAMETERS ----------')
console.log('Max Tokens : ' + this.completionParams.max_tokens)
console.log('Temperature : ' + this.completionParams.temperature)
console.log('Frequency Penalty : ' + this.completionParams.frequency_penalty)
console.log('Presence Penalty : ' + this.completionParams.presence_penalty)
console.log('Logit Biais : ' + this.completionParams.logit_bias)
}
}
// -----------------------------------------------
// METHODS FOR THE AUTOMATIC MODE
// -----------------------------------------------
async generateMainKeyword () {
const prompt = getPromptForMainKeyword()
if (this.postPrompt.debug) {
console.log('---------- PROMPT MAIN KEYWORD ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- MAIN KEYWORD ----------')
console.log(response.text)
}
return extractJsonArray(response.text)
}
async generateContentOutline () {
if (this.postPrompt.generate) {
const audienceIntent = await this.generateAudienceIntent()
this.postPrompt = {
...audienceIntent,
...this.postPrompt
}
}
const prompt = getPromptForOutline(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT OUTLINE ----------')
console.log(prompt)
}
// the parent message is the outline for the upcoming content
// By this way, we can decrease the cost of the API call by minimizing the number of prompt tokens
// TODO : add an option to disable this feature
this.chatParentMessage = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- OUTLINE ----------')
console.log(this.chatParentMessage.text)
}
return extractPostOutlineFromCodeBlock(this.chatParentMessage.text)
}
async generateAudienceIntent () {
const prompt = getPromptForAudienceIntent(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT AUDIENCE INTENT ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- AUDIENCE INTENT ----------')
console.log(response.text)
}
return extractAudienceIntentInfo(response.text)
}
async generateIntroduction () {
const response = await this.sendRequest(getPromptForIntroduction(this.postPrompt), this.completionParams)
return extractCodeBlock(response.text)
}
async generateConclusion () {
const response = await this.sendRequest(getPromptForConclusion(), this.completionParams)
return extractCodeBlock(response.text)
}
async generateHeadingContents (postOutline : PostOutline) {
const headingLevel = 2
return await this.buildContent(postOutline.headings, headingLevel)
}
private async buildContent (headings: Heading[], headingLevel : number, previousContent: string = ''): Promise<string> {
if (headings.length === 0) {
return previousContent
}
const [currentHeading, ...remainingHeadings] = headings
const mdHeading = Array(headingLevel).fill('#').join('')
let content = previousContent + '\n' + mdHeading + ' ' + currentHeading.title
if (currentHeading.headings && currentHeading.headings.length > 0) {
content = await this.buildContent(currentHeading.headings, headingLevel + 1, content)
} else {
content += '\n' + await this.getContent(currentHeading)
}
return this.buildContent(remainingHeadings, headingLevel, content)
}
private async getContent (heading: Heading): Promise<string> {
if (this.postPrompt.debug) {
console.log(`\nHeading : ${heading.title} ...'\n`)
}
const response = await this.sendRequest(getPromptForHeading(this.postPrompt.tone, heading.title, heading.keywords), this.completionParams)
return `${extractCodeBlock(response.text)}\n`
}
// -----------------------------------------------
// METHODS FOR THE CUSTOM MODE base on a template
// -----------------------------------------------
/**
* Generate a content based on one of prompt defined in the template
* @param customPrompt : the prompt defined in the template
* @returns the AI answer
*/
async generateCustomPrompt (customPrompt : string) {
this.chatParentMessage = await this.sendRequest(customPrompt, this.completionParams)
return extractCodeBlock(this.chatParentMessage.text)
}
/**
* Generate the SEO info for the post based on the template
* @returns the SEO info
*/
async generateSeoInfo (): Promise<SeoInfo> {
const systemPrompt = getSeoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemPrompt)
this.chatParentMessage = await this.sendRequest(getPromptForSeoInfo(this.postPrompt), this.completionParams)
if (this.postPrompt.debug) {
log('---------- SEO INFO ----------')
console.log(this.chatParentMessage.text)
}
return extractSeoInfo(this.chatParentMessage.text)
}
private async readTemplate () : Promise<string> {
const templatePath = this.postPrompt.templateFile
return await readFile(templatePath, 'utf-8')
}
// -----------------------------------------------
// SEND REQUEST TO OPENAI API
// -----------------------------------------------
private async sendRequest (prompt : string, completionParams? : CompletionParams) {
return await pRetry(async () => {
const options : SendMessageOptions = { parentMessageId: this.chatParentMessage?.id }
if (completionParams) {
options.completionParams = completionParams
}
const response = await this.api.sendMessage(prompt, options)
this.totalTokens.promptTokens += response.detail.usage.prompt_tokens
this.totalTokens.completionTokens += response.detail.usage.completion_tokens
this.totalTokens.total += response.detail.usage.total_tokens
return response
}, {
retries: 10,
onFailedAttempt: async (error) => {
this.manageError(error)
}
})
}
private manageError (error: FailedAttemptError) {
if (this.postPrompt.debug) {
console.log('---------- OPENAI REQUEST ERROR ----------')
console.log(error)
}
if (error instanceof ChatGPTError) {
const chatGPTError = error as ChatGPTError
if (chatGPTError.statusCode === 401) {
console.log('OpenAI API Error : Invalid API key: please check your API key in the option -k or in the OPENAI_API_KEY env var.')
process.exit(1)
}
if (chatGPTError.statusCode === 404) {
console.log(`OpenAI API Error : Invalid model for your OpenAI subscription. Check if you can use : ${this.postPrompt.model}.`)
console.log(this.postPrompt.model === 'gpt-4' || this.postPrompt.model === 'gpt-4-32k' ? 'You need to join the waiting list to use the GPT-4 API : https://openai.com/waitlist/gpt-4-api' : '')
process.exit(1)
}
}
if (error instanceof AbortError) {
console.log(`OpenAI API - Request aborted. ${error.message}`)
} else {
console.log(`OpenAI API - Request failed - Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left. ${error.message}`)
}
}
}
| src/lib/post-helpers.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " })\n}\nasync function generatePost (options: Options) {\n let answers : any = {}\n if (isInteractive(options)) {\n answers = isCustom(options) ? await askCustomQuestions() : await askQuestions()\n }\n const defaultPostPrompt = buildDefaultPostPrompt()\n const postPrompt : PostPrompt = {\n ...defaultPostPrompt,",
"score": 0.7803657054901123
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " ...post,\n content: isCustom(options)\n ? (isMarkdown(options)\n ? marked(post.content)\n : post.content)\n : marked(post.content)\n }\n const jsonFile = `${postPrompt.filename}.json`\n const contentFile = `${postPrompt.filename}.${getFileExtension(options)}`\n const writeJSONPromise = fs.promises.writeFile(jsonFile, JSON.stringify(jsonData), 'utf8')",
"score": 0.7742851972579956
},
{
"filename": "src/post.ts",
"retrieved_chunk": " )\n promptContents.push(content)\n }\n // We replace the prompts by the AI answer in the template content\n const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)\n const seoInfo = await oraPromise(\n this.helper.generateSeoInfo(),\n {\n text: 'Generating SEO info ...'\n }",
"score": 0.7717841863632202
},
{
"filename": "src/post.ts",
"retrieved_chunk": " }\n )\n content += await oraPromise(\n this.helper.generateHeadingContents(tableOfContent),\n {\n text: 'Generating content ...'\n }\n )\n if (this.helper.getPrompt().withConclusion) {\n content += await oraPromise(",
"score": 0.7577898502349854
},
{
"filename": "src/post.ts",
"retrieved_chunk": " // We remove the first prompt because it is the system prompt\n const prompts = this.helper.getPrompt().prompts.slice(1)\n // for each prompt, we generate the content\n const templatePrompts = prompts.entries()\n for (const [index, prompt] of templatePrompts) {\n const content = await oraPromise(\n this.helper.generateCustomPrompt(prompt),\n {\n text: `Generating the prompt num. ${index + 1} ...`\n }",
"score": 0.7509905695915222
}
] | typescript | prompts = extractPrompts(this.postPrompt.templateContent)
} |
import fs from 'fs'
import util from 'util'
import { Command } from 'commander'
import {
getAllWordpress,
getWordpress,
addWordpress,
removeWordpress,
exportWordpressList,
importWordpressList
} from '../../lib/store/store'
import { getCategories, createPost, updatePost } from '../../lib/wp/wp-api'
import { Post } from '../../types'
const readFile = util.promisify(fs.readFile)
type UpdateOptions = {
date : string
}
export function buildWpCommands (program: Command) {
const wpCommand = program
.command('wp')
.description('Wordpress related commands. The wp list is stored in the local store : ~/.julius/wordpress.json')
.action(() => {
console.log('Please provide a sub-command: "add" or "ls" or "rm" , ... ')
})
wpCommand
.command('ls')
.description('List all Wordpress sites')
.action(async () => {
await getAllWp()
})
wpCommand
.command('info <domain|index>')
.description('Info on a Wordpress site')
.action(async (domain) => {
const domainFound = await getWordpress(domain)
if (domainFound) {
console.log('\nWordpress site found :\n')
console.log(`\ndomain : ${domainFound.domain}`)
console.log(`username : ${domainFound.username}`)
console.log(`password : ${domainFound.password}\n`)
} else {
console.log(`\nWordpress site ${domain} not found\n`)
}
})
wpCommand
.command('add <domain:username:password>')
.description('Add a new Wordpress site')
.action(async (site) => {
await addWpSite(site)
})
wpCommand
.command('rm <domain|index>')
.description('Remove Wordpress site')
.action(async (domain) => {
const deleted = await removeWordpress(domain)
console.log(deleted ? `\nWordpress site ${domain} removed successfully\n` : `Wordpress site ${domain} not found\n`)
})
wpCommand
.command('export <file>')
.description('Export the list of wordpress sites (with credentials) the console')
.action(async (file) => {
await exportWordpressList(file)
})
wpCommand
.command('import <file>')
.description('Import the list of wordpress sites (with credentials) from a file')
.action(async (file) => {
await importWordpressList(file)
})
wpCommand
.command('categories <domain|index>')
.description('Fetch the categories for one Wordpress site')
.action(async (domain) => {
const domainFound = await getWordpress(domain)
if (domainFound) {
| const categories = await getCategories(domainFound)
console.log(categories)
} else { |
console.log(`\nWordpress site ${domain} not found\n`)
}
})
wpCommand
.command('post <domain> <categoryId> <jsonfile>')
.description('Create a new post to a Wordpress site. The file has to be a json file containing : { content, categories, seoTitle, seoDescription }')
.action(async (domain, categoryId, jsonFile) => {
const domainFound = await getWordpress(domain)
if (!domainFound) {
console.log(`\nWordpress site ${domain} not found\n`)
return
}
const jsonContent = await readFile(jsonFile, 'utf8')
const post: Post = JSON.parse(jsonContent)
post.categories = [categoryId]
post.status = 'draft'
await createPost(domainFound, post)
console.log(`\nContent has been published on https://${domainFound.domain}/${post.slug}\n`)
})
wpCommand
.command('update <domain> <slug> <jsonfile>')
.option('-d, --date <date>', 'Update the publish date of the post. Use the format YYYY-MM-DD:HH:MM:SS')
.description('Update a new post to a Wordpress site. The file has to be a json file containing : { content, seoTitle, seoDescription }')
.action(async (domain, slug, jsonFile, options : UpdateOptions) => {
const domainFound = await getWordpress(domain)
if (!domainFound) {
console.log(`\nWordpress site ${domain} not found\n`)
return
}
const jsonContent = await readFile(jsonFile, 'utf8')
const newContent: Post = JSON.parse(jsonContent)
await updatePost(domainFound, slug, newContent, options.date)
console.log(`\nContent has been updated on https://${domainFound.domain}${slug}\n\n`)
})
}
async function getAllWp () {
const wpSites = await getAllWordpress()
if (wpSites.length === 0) {
console.log('\nNo Wordpress site found\n')
return
}
console.log('\nWordpress sites :\n')
console.log(wpSites.map((wp, index) => `${index + 1}. ${wp.domain} (${wp.username})`).join('\n') + '\n')
}
async function addWpSite (site) {
const [domain, username, password] = site.split(':')
if (!domain || !username || !password) {
console.error('Invalid format for adding a new wp site. Expected : domain:username:password')
return
}
await addWordpress({ domain, username, password })
console.log(`\nWordpress site ${domain} added successfully\n`)
}
| src/bin/command/wp.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/wp/wp-api.ts",
"retrieved_chunk": " };\n date?: string;\n date_gmt?: string;\n}\nexport async function getCategories (wp : Wordpress) {\n const { domain, username, password } = wp\n const response = await axios.get(`${getApiUrl(domain)}/categories`, authenticate(username, password))\n return response.data.map((category) => {\n return {\n id: category.id,",
"score": 0.8217255473136902
},
{
"filename": "src/lib/store/store.ts",
"retrieved_chunk": "}\nexport async function removeWordpress (domain: string): Promise<Boolean> {\n const wpSites = await getAllWordpress()\n const index = !isNaN(Number(domain)) ? Number(domain) - 1 : wpSites.findIndex((wp) => wp.domain === domain)\n if (index < 0) {\n return false\n }\n wpSites.splice(index, 1)\n await fs.promises.writeFile(WORDPRESS_FILE, JSON.stringify(wpSites), 'utf8')\n return true",
"score": 0.8190585970878601
},
{
"filename": "src/lib/store/store.ts",
"retrieved_chunk": " return JSON.parse(data)\n}\nexport async function addWordpress (wp: Wordpress): Promise<void> {\n const wpSites = [...await getAllWordpress(), wp].sort((a, b) => a.domain.localeCompare(b.domain))\n await fs.promises.writeFile(WORDPRESS_FILE, JSON.stringify(wpSites), 'utf8')\n}\nexport async function getWordpress (domain: string): Promise<Wordpress | undefined> {\n const wpSites = await getAllWordpress()\n const index = !isNaN(Number(domain)) ? Number(domain) - 1 : wpSites.findIndex((wp) => wp.domain === domain)\n return wpSites[index]",
"score": 0.79350745677948
},
{
"filename": "src/lib/wp/wp-api.ts",
"retrieved_chunk": " name: category.name,\n slug: category.slug\n }\n })\n}\nexport async function createPost (wp : Wordpress, post : Post) {\n const { domain, username, password } = wp\n const postData : any = {\n ...post\n }",
"score": 0.7776350975036621
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " .action(async (options) => {\n try {\n await generatePost(options)\n } catch (error) {\n if (error instanceof NoApiKeyError) {\n console.error('Unable to initialize the ChatGPT API. Please make sure that you have set the OPENAI_API_KEY environment variable or use the -K option for setting the API key')\n } else {\n console.error(`Error during the generation of the post : ${error}`)\n }\n }",
"score": 0.7389602065086365
}
] | typescript | const categories = await getCategories(domainFound)
console.log(categories)
} else { |
import crowdin, {
Credentials,
SourceFiles,
UploadStorage,
} from "@crowdin/crowdin-api-client";
import { mockCrowdinClient } from "../mock/crowdin-client";
import { Payload } from "payload";
import { PluginOptions } from "../../types";
import { toWords } from "payload/dist/utilities/formatLabels";
import {
getArticleDirectory,
getFile,
getFiles,
getFileByDocumentID,
getFilesByDocumentID,
} from "../helpers";
import { isEmpty } from "lodash";
export interface IcrowdinFile {
id: string;
originalId: number;
fileData: {
json?: Object;
html?: string;
};
}
interface IfindOrCreateCollectionDirectory {
collectionSlug: string;
}
interface IfindOrCreateArticleDirectory
extends IfindOrCreateCollectionDirectory {
document: any;
global?: boolean;
}
interface IupdateOrCreateFile {
name: string;
value: string | object;
fileType: "html" | "json";
articleDirectory: any;
}
interface IcreateOrUpdateFile {
name: string;
fileData: string | object;
fileType: "html" | "json";
}
interface IcreateFile extends IcreateOrUpdateFile {
directoryId: number;
}
interface IupdateFile extends IcreateOrUpdateFile {
crowdinFile: IcrowdinFile;
}
interface IupdateCrowdinFile extends IcreateOrUpdateFile {
fileId: number;
}
interface IgetTranslation {
documentId: string;
fieldName: string;
locale: string;
global?: boolean;
}
export class payloadCrowdinSyncFilesApi {
sourceFilesApi: SourceFiles;
uploadStorageApi: UploadStorage;
projectId: number;
directoryId?: number;
payload: Payload;
constructor(pluginOptions: PluginOptions, payload: Payload) {
// credentials
const credentials: Credentials = {
token: pluginOptions.token,
};
const { sourceFilesApi, uploadStorageApi } = new crowdin(credentials);
this.projectId = pluginOptions.projectId;
this.directoryId = pluginOptions.directoryId;
this.sourceFilesApi =
process.env.NODE_ENV === "test"
? ( | mockCrowdinClient(pluginOptions) as any)
: sourceFilesApi; |
this.uploadStorageApi =
process.env.NODE_ENV === "test"
? (mockCrowdinClient(pluginOptions) as any)
: uploadStorageApi;
this.payload = payload;
}
async findOrCreateArticleDirectory({
document,
collectionSlug,
global = false,
}: IfindOrCreateArticleDirectory) {
let crowdinPayloadArticleDirectory;
if (document.crowdinArticleDirectory) {
// Update not possible. Article name needs to be updated manually on Crowdin.
// The name of the directory is Crowdin specific helper text to give
// context to translators.
// See https://developer.crowdin.com/api/v2/#operation/api.projects.directories.getMany
crowdinPayloadArticleDirectory = await this.payload.findByID({
collection: "crowdin-article-directories",
id:
document.crowdinArticleDirectory.id ||
document.crowdinArticleDirectory,
});
} else {
const crowdinPayloadCollectionDirectory =
await this.findOrCreateCollectionDirectory({
collectionSlug: global ? "globals" : collectionSlug,
});
// Create article directory on Crowdin
const crowdinDirectory = await this.sourceFilesApi.createDirectory(
this.projectId,
{
directoryId: crowdinPayloadCollectionDirectory.originalId,
name: global ? collectionSlug : document.id,
title: global
? toWords(collectionSlug)
: document.title || document.name, // no tests for this Crowdin metadata, but makes it easier for translators
}
);
// Store result in Payload CMS
crowdinPayloadArticleDirectory = await this.payload.create({
collection: "crowdin-article-directories",
data: {
crowdinCollectionDirectory: crowdinPayloadCollectionDirectory.id,
originalId: crowdinDirectory.data.id,
projectId: this.projectId,
directoryId: crowdinDirectory.data.directoryId,
name: crowdinDirectory.data.name,
createdAt: crowdinDirectory.data.createdAt,
updatedAt: crowdinDirectory.data.updatedAt,
},
});
// Associate result with document
if (global) {
const update = await this.payload.updateGlobal({
slug: collectionSlug,
data: {
crowdinArticleDirectory: crowdinPayloadArticleDirectory.id,
},
});
} else {
const update = await this.payload.update({
collection: collectionSlug,
id: document.id,
data: {
crowdinArticleDirectory: crowdinPayloadArticleDirectory.id,
},
});
}
}
return crowdinPayloadArticleDirectory;
}
private async findOrCreateCollectionDirectory({
collectionSlug,
}: IfindOrCreateCollectionDirectory) {
let crowdinPayloadCollectionDirectory;
// Check whether collection directory exists on Crowdin
const query = await this.payload.find({
collection: "crowdin-collection-directories",
where: {
collectionSlug: {
equals: collectionSlug,
},
},
});
if (query.totalDocs === 0) {
// Create collection directory on Crowdin
const crowdinDirectory = await this.sourceFilesApi.createDirectory(
this.projectId,
{
directoryId: this.directoryId,
name: collectionSlug,
title: toWords(collectionSlug), // is this transformed value available on the collection object?
}
);
// Store result in Payload CMS
crowdinPayloadCollectionDirectory = await this.payload.create({
collection: "crowdin-collection-directories",
data: {
collectionSlug: collectionSlug,
originalId: crowdinDirectory.data.id,
projectId: this.projectId,
directoryId: crowdinDirectory.data.directoryId,
name: crowdinDirectory.data.name,
title: crowdinDirectory.data.title,
createdAt: crowdinDirectory.data.createdAt,
updatedAt: crowdinDirectory.data.updatedAt,
},
});
} else {
crowdinPayloadCollectionDirectory = query.docs[0];
}
return crowdinPayloadCollectionDirectory;
}
async getFile(name: string, crowdinArticleDirectoryId: string): Promise<any> {
return getFile(name, crowdinArticleDirectoryId, this.payload);
}
async getFiles(crowdinArticleDirectoryId: string): Promise<any> {
return getFiles(crowdinArticleDirectoryId, this.payload);
}
/**
* Create/Update/Delete a file on Crowdin
*
* Records the file in Payload CMS under the `crowdin-files` collection.
*
* - Create a file if it doesn't exist on Crowdin and the supplied content is not empty
* - Update a file if it exists on Crowdin and the supplied content is not empty
* - Delete a file if it exists on Crowdin and the supplied file content is empty
*/
async createOrUpdateFile({
name,
value,
fileType,
articleDirectory,
}: IupdateOrCreateFile) {
const empty = isEmpty(value);
// Check whether file exists on Crowdin
let crowdinFile = await this.getFile(name, articleDirectory.id);
let updatedCrowdinFile;
if (!empty) {
if (!crowdinFile) {
updatedCrowdinFile = await this.createFile({
name,
value,
fileType,
articleDirectory,
});
} else {
updatedCrowdinFile = await this.updateFile({
crowdinFile,
name: name,
fileData: value,
fileType: fileType,
});
}
} else {
if (crowdinFile) {
updatedCrowdinFile = await this.deleteFile(crowdinFile);
}
}
return updatedCrowdinFile;
}
private async updateFile({
crowdinFile,
name,
fileData,
fileType,
}: IupdateFile) {
// Update file on Crowdin
const updatedCrowdinFile = await this.crowdinUpdateFile({
fileId: crowdinFile.originalId,
name,
fileData,
fileType,
});
const payloadCrowdinFile = await this.payload.update({
collection: "crowdin-files", // required
id: crowdinFile.id,
data: {
// required
updatedAt: updatedCrowdinFile.data.updatedAt,
revisionId: updatedCrowdinFile.data.revisionId,
...(fileType === "json" && { fileData: { json: fileData } }),
...(fileType === "html" && { fileData: { html: fileData } }),
},
});
}
private async createFile({
name,
value,
fileType,
articleDirectory,
}: IupdateOrCreateFile) {
// Create file on Crowdin
const crowdinFile = await this.crowdinCreateFile({
directoryId: articleDirectory.originalId,
name: name,
fileData: value,
fileType: fileType,
});
// createFile has been intermittent in not being available
// perhaps logic goes wrong somewhere and express middleware
// is hard to debug?
/*const crowdinFile = {data: {
revisionId: 5,
status: 'active',
priority: 'normal',
importOptions: { contentSegmentation: true, customSegmentation: false },
exportOptions: null,
excludedTargetLanguages: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
id: 1079,
projectId: 323731,
branchId: null,
directoryId: 1077,
name: name,
title: null,
type: fileType,
path: `/policies/security-and-privacy/${name}.${fileType}`
}}*/
// Store result on Payload CMS
if (crowdinFile) {
const payloadCrowdinFile = await this.payload.create({
collection: "crowdin-files", // required
data: {
// required
title: crowdinFile.data.name,
field: name,
crowdinArticleDirectory: articleDirectory.id,
createdAt: crowdinFile.data.createdAt,
updatedAt: crowdinFile.data.updatedAt,
originalId: crowdinFile.data.id,
projectId: crowdinFile.data.projectId,
directoryId: crowdinFile.data.directoryId,
revisionId: crowdinFile.data.revisionId,
name: crowdinFile.data.name,
type: crowdinFile.data.type,
path: crowdinFile.data.path,
...(fileType === "json" && { fileData: { json: value } }),
...(fileType === "html" && { fileData: { html: value } }),
},
});
return payloadCrowdinFile;
}
}
async deleteFile(crowdinFile: IcrowdinFile) {
const file = await this.sourceFilesApi.deleteFile(
this.projectId,
crowdinFile.originalId
);
const payloadFile = await this.payload.delete({
collection: "crowdin-files", // required
id: crowdinFile.id, // required
});
return payloadFile;
}
private async crowdinUpdateFile({
fileId,
name,
fileData,
fileType,
}: IupdateCrowdinFile) {
const storage = await this.uploadStorageApi.addStorage(
name,
fileData,
fileType
);
//const file = await sourceFilesApi.deleteFile(projectId, 1161)
const file = await this.sourceFilesApi.updateOrRestoreFile(
this.projectId,
fileId,
{
storageId: storage.data.id,
}
);
return file;
}
private async crowdinCreateFile({
name,
fileData,
fileType,
directoryId,
}: IcreateFile) {
const storage = await this.uploadStorageApi.addStorage(
name,
fileData,
fileType
);
const options = {
name: `${name}.${fileType}`,
title: name,
storageId: storage.data.id,
directoryId,
type: fileType,
};
try {
const file = await this.sourceFilesApi.createFile(
this.projectId,
options
);
return file;
} catch (error) {
console.error(error, options);
}
}
async getArticleDirectory(documentId: string) {
const result = await getArticleDirectory(documentId, this.payload);
return result;
}
async deleteFilesAndDirectory(documentId: string) {
const files = await this.getFilesByDocumentID(documentId);
for (const file of files) {
await this.deleteFile(file);
}
await this.deleteArticleDirectory(documentId);
}
async deleteArticleDirectory(documentId: string) {
const crowdinPayloadArticleDirectory = await this.getArticleDirectory(
documentId
);
await this.sourceFilesApi.deleteDirectory(
this.projectId,
crowdinPayloadArticleDirectory.originalId
);
await this.payload.delete({
collection: "crowdin-article-directories",
id: crowdinPayloadArticleDirectory.id,
});
}
async getFileByDocumentID(name: string, documentId: string) {
const result = await getFileByDocumentID(name, documentId, this.payload);
return result;
}
async getFilesByDocumentID(documentId: string) {
const result = await getFilesByDocumentID(documentId, this.payload);
return result;
}
}
| src/api/payload-crowdin-sync/files.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " token: pluginOptions.token,\n };\n const { translationsApi } = new crowdin(credentials);\n this.projectId = pluginOptions.projectId;\n this.directoryId = pluginOptions.directoryId;\n this.translationsApi =\n process.env.NODE_ENV === \"test\"\n ? (mockCrowdinClient(pluginOptions) as any)\n : translationsApi;\n this.filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, payload);",
"score": 0.9584046602249146
},
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " translationsApi: Translations;\n filesApi: payloadCrowdinSyncFilesApi; // our wrapper for file operations\n projectId: number;\n directoryId?: number;\n payload: Payload;\n localeMap: PluginOptions[\"localeMap\"];\n sourceLocale: PluginOptions[\"sourceLocale\"];\n constructor(pluginOptions: PluginOptions, payload: Payload) {\n // credentials\n const credentials: Credentials = {",
"score": 0.8209938406944275
},
{
"filename": "src/api/mock/crowdin-client.ts",
"retrieved_chunk": " directoryId?: number;\n branchId: number;\n constructor(pluginOptions: PluginOptions) {\n this.projectId = pluginOptions.projectId;\n this.directoryId = pluginOptions.directoryId;\n this.branchId = 4;\n }\n async listFileRevisions(projectId: number, fileId: number) {\n return await Promise.resolve(1).then(() => undefined);\n }",
"score": 0.8112301826477051
},
{
"filename": "src/hooks/collections/afterDelete.ts",
"retrieved_chunk": " /**\n * Initialize Crowdin client sourceFilesApi\n */\n const filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, req.payload);\n await filesApi.deleteFilesAndDirectory(`${id}`);\n };",
"score": 0.798954963684082
},
{
"filename": "src/hooks/collections/afterChange.ts",
"retrieved_chunk": " value: convertSlateToHtml(value),\n fileType: \"html\",\n articleDirectory,\n });\n };\n const createOrUpdateJsonSource = async () => {\n if (\n (!deepEqual(currentCrowdinJsonData, prevCrowdinJsonData) &&\n Object.keys(currentCrowdinJsonData).length !== 0) ||\n process.env.PAYLOAD_CROWDIN_SYNC_ALWAYS_UPDATE === \"true\"",
"score": 0.7926929593086243
}
] | typescript | mockCrowdinClient(pluginOptions) as any)
: sourceFilesApi; |
import * as dotenv from 'dotenv'
import { readFile as rd } from 'fs'
import { promisify } from 'util'
import { ChatGPTAPI, ChatGPTError, ChatMessage, SendMessageOptions } from 'chatgpt'
import pRetry, { AbortError, FailedAttemptError } from 'p-retry'
import { extractJsonArray, extractCodeBlock, extractPostOutlineFromCodeBlock, extractSeoInfo, extractAudienceIntentInfo } from './extractor'
import {
getPromptForMainKeyword,
getPromptForOutline,
getPromptForIntroduction,
getPromptForHeading,
getPromptForConclusion,
getAutoSystemPrompt,
getPromptForSeoInfo,
getCustomSystemPrompt,
getSeoSystemPrompt,
getPromptForIntentAudience as getPromptForAudienceIntent
} from './prompts'
import {
Heading,
PostOutline,
PostPrompt,
TotalTokens,
SeoInfo
} from '../types'
import { encode } from './tokenizer'
import { extractPrompts } from './template'
import { log } from 'console'
import { NoApiKeyError } from './errors'
dotenv.config()
const readFile = promisify(rd)
/**
* Specific Open AI API parameters for the completion
*/
export type CompletionParams = {
temperature?: number | null,
top_p?: number | null,
max_tokens?: number,
presence_penalty?: number | null,
frequency_penalty?: number | null,
logit_bias?: object | null,
}
/**
* Interface for the helper class for generating a post. it defines how to generate a post
* Each helper class must implement this interface
* @interface
*/
export interface GeneratorHelperInterface {
init () : Promise<void>
isCustom() : boolean
generateContentOutline () : Promise<PostOutline>
generateMainKeyword () : Promise<string[]>
generateIntroduction () : Promise<string>
generateConclusion () : Promise<string>
generateHeadingContents (tableOfContent : PostOutline) : Promise<string>
generateCustomPrompt(prompt : string) : Promise<string>
generateSeoInfo () : Promise<SeoInfo>
getTotalTokens() : TotalTokens
getPrompt() : PostPrompt
}
/**
* Helper implementation for generating a post using the ChatGPT API
* @class
*/
export class ChatGptHelper implements GeneratorHelperInterface {
private postPrompt : PostPrompt
private api : ChatGPTAPI
// The parent message is either the previous one in the conversation (if a template is used)
// or the generated outline (if we are in auto mode)
private chatParentMessage : ChatMessage
private completionParams : CompletionParams
private totalTokens : TotalTokens = {
promptTokens: 0,
completionTokens: 0,
total: 0
}
// -----------------------------------------------
// CONSTRUCTOR AND INITIALIZATION
// -----------------------------------------------
public constructor (postPrompt : PostPrompt) {
this.postPrompt = postPrompt
}
isCustom () : boolean {
return this.postPrompt?.templateFile !== undefined
}
getPrompt (): PostPrompt {
return this.postPrompt
}
getTotalTokens (): TotalTokens {
return this.totalTokens
}
async init () {
if (this.isCustom()) {
if (this.postPrompt.debug) {
console.log(`Use template : ${this.postPrompt.templateFile}`)
}
this.postPrompt.templateContent = await this.readTemplate()
this.postPrompt.prompts = extractPrompts(this.postPrompt.templateContent)
}
const systemMessage = this.isCustom() ? getCustomSystemPrompt(this.postPrompt) : getAutoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemMessage)
}
private async buildChatGPTAPI (systemMessage : string) {
try {
this.api = new ChatGPTAPI({
apiKey: this.postPrompt?.apiKey || process.env.OPENAI_API_KEY,
completionParams: {
model: this.postPrompt.model
},
systemMessage,
debug: this.postPrompt.debugapi
})
} catch (error) {
throw new NoApiKeyError()
}
if (this.postPrompt.debug) {
console.log(`OpenAI API initialized with model : ${this.postPrompt.model}`)
}
this.completionParams = {
temperature: this.postPrompt.temperature ?? 0.8,
frequency_penalty: this.postPrompt.frequencyPenalty ?? 0,
presence_penalty: this.postPrompt.presencePenalty ?? 1
}
if (this.postPrompt.logitBias) {
const mainKwWords = await this.generateMainKeyword()
// set the logit bias in order to force the model to minimize the usage of the main keyword
const logitBiais: Record<number, number> = {}
mainKwWords.forEach((kw) => {
const encoded = encode(kw)
encoded.forEach((element) => {
logitBiais[element] = Number(this.postPrompt.logitBias) || -1
})
})
this.completionParams.logit_bias = logitBiais
}
if (this.postPrompt.debug) {
console.log('---------- COMPLETION PARAMETERS ----------')
console.log('Max Tokens : ' + this.completionParams.max_tokens)
console.log('Temperature : ' + this.completionParams.temperature)
console.log('Frequency Penalty : ' + this.completionParams.frequency_penalty)
console.log('Presence Penalty : ' + this.completionParams.presence_penalty)
console.log('Logit Biais : ' + this.completionParams.logit_bias)
}
}
// -----------------------------------------------
// METHODS FOR THE AUTOMATIC MODE
// -----------------------------------------------
async generateMainKeyword () {
const prompt = getPromptForMainKeyword()
if (this.postPrompt.debug) {
console.log('---------- PROMPT MAIN KEYWORD ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- MAIN KEYWORD ----------')
console.log(response.text)
}
return extractJsonArray(response.text)
}
async generateContentOutline () {
if (this.postPrompt.generate) {
const audienceIntent = await this.generateAudienceIntent()
this.postPrompt = {
...audienceIntent,
...this.postPrompt
}
}
const prompt = getPromptForOutline(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT OUTLINE ----------')
console.log(prompt)
}
// the parent message is the outline for the upcoming content
// By this way, we can decrease the cost of the API call by minimizing the number of prompt tokens
// TODO : add an option to disable this feature
this.chatParentMessage = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- OUTLINE ----------')
console.log(this.chatParentMessage.text)
}
| return extractPostOutlineFromCodeBlock(this.chatParentMessage.text)
} |
async generateAudienceIntent () {
const prompt = getPromptForAudienceIntent(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT AUDIENCE INTENT ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- AUDIENCE INTENT ----------')
console.log(response.text)
}
return extractAudienceIntentInfo(response.text)
}
async generateIntroduction () {
const response = await this.sendRequest(getPromptForIntroduction(this.postPrompt), this.completionParams)
return extractCodeBlock(response.text)
}
async generateConclusion () {
const response = await this.sendRequest(getPromptForConclusion(), this.completionParams)
return extractCodeBlock(response.text)
}
async generateHeadingContents (postOutline : PostOutline) {
const headingLevel = 2
return await this.buildContent(postOutline.headings, headingLevel)
}
private async buildContent (headings: Heading[], headingLevel : number, previousContent: string = ''): Promise<string> {
if (headings.length === 0) {
return previousContent
}
const [currentHeading, ...remainingHeadings] = headings
const mdHeading = Array(headingLevel).fill('#').join('')
let content = previousContent + '\n' + mdHeading + ' ' + currentHeading.title
if (currentHeading.headings && currentHeading.headings.length > 0) {
content = await this.buildContent(currentHeading.headings, headingLevel + 1, content)
} else {
content += '\n' + await this.getContent(currentHeading)
}
return this.buildContent(remainingHeadings, headingLevel, content)
}
private async getContent (heading: Heading): Promise<string> {
if (this.postPrompt.debug) {
console.log(`\nHeading : ${heading.title} ...'\n`)
}
const response = await this.sendRequest(getPromptForHeading(this.postPrompt.tone, heading.title, heading.keywords), this.completionParams)
return `${extractCodeBlock(response.text)}\n`
}
// -----------------------------------------------
// METHODS FOR THE CUSTOM MODE base on a template
// -----------------------------------------------
/**
* Generate a content based on one of prompt defined in the template
* @param customPrompt : the prompt defined in the template
* @returns the AI answer
*/
async generateCustomPrompt (customPrompt : string) {
this.chatParentMessage = await this.sendRequest(customPrompt, this.completionParams)
return extractCodeBlock(this.chatParentMessage.text)
}
/**
* Generate the SEO info for the post based on the template
* @returns the SEO info
*/
async generateSeoInfo (): Promise<SeoInfo> {
const systemPrompt = getSeoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemPrompt)
this.chatParentMessage = await this.sendRequest(getPromptForSeoInfo(this.postPrompt), this.completionParams)
if (this.postPrompt.debug) {
log('---------- SEO INFO ----------')
console.log(this.chatParentMessage.text)
}
return extractSeoInfo(this.chatParentMessage.text)
}
private async readTemplate () : Promise<string> {
const templatePath = this.postPrompt.templateFile
return await readFile(templatePath, 'utf-8')
}
// -----------------------------------------------
// SEND REQUEST TO OPENAI API
// -----------------------------------------------
private async sendRequest (prompt : string, completionParams? : CompletionParams) {
return await pRetry(async () => {
const options : SendMessageOptions = { parentMessageId: this.chatParentMessage?.id }
if (completionParams) {
options.completionParams = completionParams
}
const response = await this.api.sendMessage(prompt, options)
this.totalTokens.promptTokens += response.detail.usage.prompt_tokens
this.totalTokens.completionTokens += response.detail.usage.completion_tokens
this.totalTokens.total += response.detail.usage.total_tokens
return response
}, {
retries: 10,
onFailedAttempt: async (error) => {
this.manageError(error)
}
})
}
private manageError (error: FailedAttemptError) {
if (this.postPrompt.debug) {
console.log('---------- OPENAI REQUEST ERROR ----------')
console.log(error)
}
if (error instanceof ChatGPTError) {
const chatGPTError = error as ChatGPTError
if (chatGPTError.statusCode === 401) {
console.log('OpenAI API Error : Invalid API key: please check your API key in the option -k or in the OPENAI_API_KEY env var.')
process.exit(1)
}
if (chatGPTError.statusCode === 404) {
console.log(`OpenAI API Error : Invalid model for your OpenAI subscription. Check if you can use : ${this.postPrompt.model}.`)
console.log(this.postPrompt.model === 'gpt-4' || this.postPrompt.model === 'gpt-4-32k' ? 'You need to join the waiting list to use the GPT-4 API : https://openai.com/waitlist/gpt-4-api' : '')
process.exit(1)
}
}
if (error instanceof AbortError) {
console.log(`OpenAI API - Request aborted. ${error.message}`)
} else {
console.log(`OpenAI API - Request failed - Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left. ${error.message}`)
}
}
}
| src/lib/post-helpers.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/post.ts",
"retrieved_chunk": " )\n promptContents.push(content)\n }\n // We replace the prompts by the AI answer in the template content\n const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)\n const seoInfo = await oraPromise(\n this.helper.generateSeoInfo(),\n {\n text: 'Generating SEO info ...'\n }",
"score": 0.8202300071716309
},
{
"filename": "src/post.ts",
"retrieved_chunk": " * Generate a post using the custom prompt based on a template\n */\n private async customGenerate () : Promise<Post> {\n const promptContents = []\n await oraPromise(\n this.helper.init(),\n {\n text: ' Init the completion parameters ...'\n }\n )",
"score": 0.8187968134880066
},
{
"filename": "src/post.ts",
"retrieved_chunk": " const tableOfContent = await oraPromise(\n this.helper.generateContentOutline(),\n {\n text: 'Generating post outline ...'\n }\n )\n let content = await oraPromise(\n this.helper.generateIntroduction(),\n {\n text: 'Generating introduction...'",
"score": 0.8166769742965698
},
{
"filename": "src/post.ts",
"retrieved_chunk": " // We remove the first prompt because it is the system prompt\n const prompts = this.helper.getPrompt().prompts.slice(1)\n // for each prompt, we generate the content\n const templatePrompts = prompts.entries()\n for (const [index, prompt] of templatePrompts) {\n const content = await oraPromise(\n this.helper.generateCustomPrompt(prompt),\n {\n text: `Generating the prompt num. ${index + 1} ...`\n }",
"score": 0.8147428035736084
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " .action(async (options) => {\n try {\n await generatePost(options)\n } catch (error) {\n if (error instanceof NoApiKeyError) {\n console.error('Unable to initialize the ChatGPT API. Please make sure that you have set the OPENAI_API_KEY environment variable or use the -K option for setting the API key')\n } else {\n console.error(`Error during the generation of the post : ${error}`)\n }\n }",
"score": 0.8127272725105286
}
] | typescript | return extractPostOutlineFromCodeBlock(this.chatParentMessage.text)
} |
import { CollectionConfig, Field } from "payload/types";
import { buildCrowdinJsonObject } from "../..";
import {
field,
fieldJsonCrowdinObject,
fieldDocValue,
} from "../fixtures/blocks-field-type.fixture";
describe("fn: buildCrowdinHtmlObject: blocks field type", () => {
it("includes localized fields", () => {
const doc = {
id: "638641358b1a140462752076",
title: "Test Policy created with title",
blocksField: fieldDocValue,
status: "draft",
createdAt: "2022-11-29T17:28:21.644Z",
updatedAt: "2022-11-29T17:28:21.644Z",
};
const fields: Field[] = [
{
name: "title",
type: "text",
localized: true,
},
// select not supported yet
{
name: "select",
type: "select",
localized: true,
options: ["one", "two"],
},
field,
];
const expected = {
title: "Test Policy created with title",
...fieldJsonCrowdinObject(),
};
expect( | buildCrowdinJsonObject({ doc, fields })).toEqual(expected); |
});
it("includes localized fields within a collapsible field", () => {
const doc = {
id: "638641358b1a140462752076",
title: "Test Policy created with title",
blocksField: fieldDocValue,
status: "draft",
createdAt: "2022-11-29T17:28:21.644Z",
updatedAt: "2022-11-29T17:28:21.644Z",
};
const fields: Field[] = [
{
name: "title",
type: "text",
localized: true,
},
// select not supported yet
{
name: "select",
type: "select",
localized: true,
options: ["one", "two"],
},
{
label: "Array fields",
type: "collapsible",
fields: [field],
},
];
const expected = {
title: "Test Policy created with title",
...fieldJsonCrowdinObject(),
};
expect(buildCrowdinJsonObject({ doc, fields })).toEqual(expected);
});
it("includes localized fields within an array field", () => {
const doc = {
id: "638641358b1a140462752076",
title: "Test Policy created with title",
arrayField: [
{
blocksField: fieldDocValue,
id: "63ea4adb6ff825cddad3c1f2",
},
],
status: "draft",
createdAt: "2022-11-29T17:28:21.644Z",
updatedAt: "2022-11-29T17:28:21.644Z",
};
const fields: Field[] = [
{
name: "title",
type: "text",
localized: true,
},
// select not supported yet
{
name: "select",
type: "select",
localized: true,
options: ["one", "two"],
},
{
name: "arrayField",
type: "array",
fields: [field],
},
];
const expected = {
title: "Test Policy created with title",
...fieldJsonCrowdinObject("arrayField.63ea4adb6ff825cddad3c1f2"),
};
expect(buildCrowdinJsonObject({ doc, fields })).toEqual(expected);
});
});
| src/utilities/tests/buildJsonCrowdinObject/blocks-field-type-fixture.spec.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/blocks-field-type.spec.ts",
"retrieved_chunk": " name: \"blocksField\",\n type: \"blocks\",\n blocks: [TestBlockArrayOfRichText],\n },\n ];\n const localizedFields = getLocalizedFields({ fields, type: \"json\" });\n const expected = {\n title: \"Test Policy created with title\",\n };\n expect(buildCrowdinJsonObject({ doc, fields: localizedFields })).toEqual(",
"score": 0.92232346534729
},
{
"filename": "src/utilities/tests/buildPayloadUpdateObject/add-rich-text-fields.spec.ts",
"retrieved_chunk": " const crowdinJsonObject = {\n title: \"Test Policy created with title\",\n ...fieldJsonCrowdinObject(),\n };\n const crowdinHtmlObject = fieldHtmlCrowdinObject();\n const expected = {\n title: \"Test Policy created with title\",\n blocksField: fieldDocValue,\n };\n expect(",
"score": 0.9190838932991028
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/group-field-type.spec.ts",
"retrieved_chunk": " const expected = {\n title: \"Test Policy created with title\",\n groupField: {\n nestedGroupField: fieldJsonCrowdinObject(),\n secondNestedGroupField: fieldJsonCrowdinObject(),\n },\n };\n expect(buildCrowdinJsonObject({ doc, fields: localizedFields })).toEqual(\n expected\n );",
"score": 0.9180446267127991
},
{
"filename": "src/utilities/tests/buildHtmlCrowdinObject/blocks-field-type.spec.ts",
"retrieved_chunk": " fields: [field],\n },\n ];\n const expected = fieldHtmlCrowdinObject();\n expect(buildCrowdinHtmlObject({ doc, fields })).toEqual(expected);\n });\n it(\"includes localized fields within an array field\", () => {\n const doc = {\n id: \"638641358b1a140462752076\",\n title: \"Test Policy created with title\",",
"score": 0.9093157052993774
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/group-field-type.spec.ts",
"retrieved_chunk": " const expected = {\n title: \"Test Policy created with title\",\n groupField: fieldJsonCrowdinObject(),\n };\n expect(buildCrowdinJsonObject({ doc, fields: localizedFields })).toEqual(\n expected\n );\n });\n it(\"includes localized fields and meta @payloadcms/plugin-seo \", () => {\n const doc = {",
"score": 0.9079537391662598
}
] | typescript | buildCrowdinJsonObject({ doc, fields })).toEqual(expected); |
import JSON5 from 'json5'
import { validate } from 'jsonschema'
import { AudienceIntentInfo, PostOutline, SeoInfo } from '../types'
export class PostOutlineValidationError extends Error {
constructor (message: string, public readonly errors: any[]) {
super(message)
}
}
const schemaValidiation = {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
properties: {
title: {
type: 'string'
},
headings: {
type: 'array',
items: {
$ref: '#/definitions/Heading'
}
},
slug: {
type: 'string'
},
seoTitle: {
type: 'string'
},
seoDescription: {
type: 'string'
}
},
required: [
'title',
'headings',
'slug',
'seoTitle',
'seoDescription'
],
additionalProperties: false,
definitions: {
Heading: {
type: 'object',
properties: {
title: {
type: 'string'
},
keywords: {
type: 'array',
items: {
type: 'string'
}
},
headings: {
type: 'array',
items: {
$ref: '#/definitions/Heading'
}
}
},
required: [
'title'
],
additionalProperties: false
}
}
}
export function extractCodeBlock (text: string): string {
// Extract code blocks with specified tags
const codeBlockTags = ['markdown', 'html', 'json']
for (const tag of codeBlockTags) {
const regex = new RegExp(`\`\`\`${tag}((.|\\n|\\r)*?)\`\`\``, 'i')
const match = text.match(regex)
if (match) {
return match[1]
}
}
// Extract code blocks without specified tags
const genericRegex = /```\n?((.|\\n|\\r)*?)```/
const genericMatch = text.match(genericRegex)
if (genericMatch) {
return genericMatch[1]
}
// No code blocks found
return text
}
export function extractPostOutlineFromCodeBlock (text: string) : PostOutline {
// Use JSON5 because it supports trailing comma and comments in the json text
const jsonData = JSON5.parse(extractCodeBlock(text))
const v = validate(jsonData, schemaValidiation)
if (!v.valid) {
const errorList = v.errors.map((val) => val.toString())
throw new PostOutlineValidationError('Invalid json for the post outline', errorList)
}
return jsonData
}
export function extractJsonArray (text : string) : string[] {
return JSON5.parse(extractCodeBlock(text))
}
export function | extractSeoInfo (text : string) : SeoInfo { |
return JSON5.parse(extractCodeBlock(text))
}
export function extractAudienceIntentInfo (text : string) : AudienceIntentInfo {
return JSON5.parse(extractCodeBlock(text))
}
| src/lib/extractor.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " log('---------- SEO INFO ----------')\n console.log(this.chatParentMessage.text)\n }\n return extractSeoInfo(this.chatParentMessage.text)\n }\n private async readTemplate () : Promise<string> {\n const templatePath = this.postPrompt.templateFile\n return await readFile(templatePath, 'utf-8')\n }\n // -----------------------------------------------",
"score": 0.7922927737236023
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " generateContentOutline () : Promise<PostOutline>\n generateMainKeyword () : Promise<string[]>\n generateIntroduction () : Promise<string>\n generateConclusion () : Promise<string>\n generateHeadingContents (tableOfContent : PostOutline) : Promise<string>\n generateCustomPrompt(prompt : string) : Promise<string>\n generateSeoInfo () : Promise<SeoInfo>\n getTotalTokens() : TotalTokens\n getPrompt() : PostPrompt\n}",
"score": 0.7692885398864746
},
{
"filename": "src/post.ts",
"retrieved_chunk": " seoDescription: tableOfContent.seoDescription,\n content,\n totalTokens: this.helper.getTotalTokens()\n }\n }\n}\n/**\n * Class for generating a post using the OpenAI API\n */\nexport class OpenAIPostGenerator extends PostGenerator {",
"score": 0.7685768604278564
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": "}\nfunction getFileExtension (options : Options) {\n // in custom mode, we use the template extension\n // in auto/default mode, we use the markdown extension in all cases\n return isCustom(options) ? options.templateFile.split('.').pop() : 'md'\n}\nfunction buildMDPage (post: Post) {\n return '# ' + post.title + '\\n' + post.content\n}\nfunction buildHTMLPage (post : Post) {",
"score": 0.7653985023498535
},
{
"filename": "src/lib/wp/wp-api.ts",
"retrieved_chunk": " name: category.name,\n slug: category.slug\n }\n })\n}\nexport async function createPost (wp : Wordpress, post : Post) {\n const { domain, username, password } = wp\n const postData : any = {\n ...post\n }",
"score": 0.7649575471878052
}
] | typescript | extractSeoInfo (text : string) : SeoInfo { |
import { CollectionConfig, Field } from "payload/types";
import { buildCrowdinJsonObject, getLocalizedFields } from "../..";
import { FieldWithName } from "../../../types";
describe("fn: buildCrowdinJsonObject: group nested in array", () => {
const doc = {
id: "6474a81bef389b66642035ff",
title: "Experience the magic of our product!",
text: "Get in touch with us or try it out yourself",
ctas: [
{
link: {
text: "Talk to us",
href: "#",
type: "ctaPrimary",
},
id: "6474a80221baea4f5f169757",
},
{
link: {
text: "Try for free",
href: "#",
type: "ctaSecondary",
},
id: "6474a81021baea4f5f169758",
},
],
createdAt: "2023-05-29T13:26:51.734Z",
updatedAt: "2023-05-29T14:47:45.957Z",
crowdinArticleDirectory: {
id: "6474baaf73b854f4d464e38f",
updatedAt: "2023-05-29T14:46:07.000Z",
createdAt: "2023-05-29T14:46:07.000Z",
name: "6474a81bef389b66642035ff",
crowdinCollectionDirectory: {
id: "6474baaf73b854f4d464e38d",
updatedAt: "2023-05-29T14:46:07.000Z",
createdAt: "2023-05-29T14:46:07.000Z",
name: "promos",
title: "Promos",
collectionSlug: "promos",
originalId: 1633,
projectId: 323731,
directoryId: 1169,
},
originalId: 1635,
projectId: 323731,
directoryId: 1633,
},
};
const linkField: Field = {
name: "link",
type: "group",
fields: [
{
name: "text",
type: "text",
localized: true,
},
{
name: "href",
type: "text",
},
{
name: "type",
type: "select",
options: ["ctaPrimary", "ctaSecondary"],
},
],
};
const Promos: CollectionConfig = {
slug: "promos",
admin: {
defaultColumns: ["title", "updatedAt"],
useAsTitle: "title",
group: "Shared",
},
access: {
read: () => true,
},
fields: [
{
name: "title",
type: "text",
localized: true,
},
{
name: "text",
type: "text",
localized: true,
},
{
name: "ctas",
type: "array",
minRows: 1,
maxRows: 2,
fields: [linkField],
},
],
};
const expected: any = {
ctas: {
"6474a80221baea4f5f169757": {
link: {
text: "Talk to us",
},
},
"6474a81021baea4f5f169758": {
link: {
text: "Try for free",
},
},
},
text: "Get in touch with us or try it out yourself",
title: "Experience the magic of our product!",
};
it("includes group json fields nested inside of array field items", () => {
expect(
buildCrowdinJsonObject({
doc,
| fields: getLocalizedFields({ fields: Promos.fields, type: "json" }),
})
).toEqual(expected); |
});
it("includes group json fields nested inside of array field items even when getLocalizedFields is run twice", () => {
expect(
buildCrowdinJsonObject({
doc,
fields: getLocalizedFields({
fields: getLocalizedFields({ fields: Promos.fields }),
type: "json",
}),
})
).toEqual(expected);
});
/**
* afterChange builds a JSON object for the previous version of
* a document to compare with the current version. Ensure this
* function works in that scenario. Also important for dealing
* with non-required empty fields.
*/
it("can work with an empty document", () => {
expect(
buildCrowdinJsonObject({
doc: {},
fields: getLocalizedFields({ fields: Promos.fields }),
})
).toEqual({});
});
it("can work with an empty array field", () => {
expect(
buildCrowdinJsonObject({
doc: {
...doc,
ctas: undefined,
},
fields: getLocalizedFields({ fields: Promos.fields }),
})
).toEqual({
text: "Get in touch with us or try it out yourself",
title: "Experience the magic of our product!",
});
});
it("can work with an empty group field in an array", () => {
expect(
buildCrowdinJsonObject({
doc: {
...doc,
ctas: [{}, {}],
},
fields: getLocalizedFields({ fields: Promos.fields }),
})
).toEqual({
text: "Get in touch with us or try it out yourself",
title: "Experience the magic of our product!",
});
});
});
| src/utilities/tests/buildJsonCrowdinObject/combined-field-types.spec.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/array-field-type.spec.ts",
"retrieved_chunk": " text: \"Array field text content two\",\n },\n },\n };\n expect(buildCrowdinJsonObject({ doc, fields: localizedFields })).toEqual(\n expected\n );\n });\n it(\"does not include localized fields richText fields nested in an array field in the `fields.json` file\", () => {\n const doc = {",
"score": 0.9249154329299927
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/array-field-type.spec.ts",
"retrieved_chunk": " const localizedFields = getLocalizedFields({ fields });\n const expected = {\n title: \"Test Policy created with title\",\n };\n expect(buildCrowdinJsonObject({ doc, fields: localizedFields })).toEqual(\n expected\n );\n });\n it(\"includes localized fields nested in an array\", () => {\n const doc = {",
"score": 0.9212038516998291
},
{
"filename": "src/utilities/tests/buildHtmlCrowdinObject/array-field-type.spec.ts",
"retrieved_chunk": " ],\n },\n ],\n };\n it(\"includes group json fields nested inside of array field items\", () => {\n expect(buildCrowdinHtmlObject({ doc, fields: Promos.fields })).toEqual(\n expected\n );\n });\n it(\"can work with an empty group field in an array\", () => {",
"score": 0.9207565784454346
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/blocks-field-type.spec.ts",
"retrieved_chunk": " };\n expect(buildCrowdinJsonObject({ doc, fields: localizedFields })).toEqual(\n expected\n );\n });\n it(\"excludes block with no localized fields - more blocks\", () => {\n const doc = {\n title: \"Test Policy created with title\",\n blocksField: [\n {",
"score": 0.9192994832992554
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/blocks-field-type-fixture.spec.ts",
"retrieved_chunk": " field,\n ];\n const expected = {\n title: \"Test Policy created with title\",\n ...fieldJsonCrowdinObject(),\n };\n expect(buildCrowdinJsonObject({ doc, fields })).toEqual(expected);\n });\n it(\"includes localized fields within a collapsible field\", () => {\n const doc = {",
"score": 0.9181150794029236
}
] | typescript | fields: getLocalizedFields({ fields: Promos.fields, type: "json" }),
})
).toEqual(expected); |
import {
CollectionAfterChangeHook,
CollectionConfig,
Field,
GlobalConfig,
GlobalAfterChangeHook,
PayloadRequest,
} from "payload/types";
import { Descendant } from "slate";
import { PluginOptions } from "../../types";
import {
buildCrowdinHtmlObject,
buildCrowdinJsonObject,
convertSlateToHtml,
fieldChanged,
} from "../../utilities";
import deepEqual from "deep-equal";
import { getLocalizedFields } from "../../utilities";
import { payloadCrowdinSyncFilesApi } from "../../api/payload-crowdin-sync/files";
/**
* Update Crowdin collections and make updates in Crowdin
*
* This functionality used to be split into field hooks.
* However, it is more reliable to loop through localized
* fields and perform opeerations in one place. The
* asynchronous nature of operations means that
* we need to be careful updates are not made sooner than
* expected.
*/
interface CommonArgs {
pluginOptions: PluginOptions;
}
interface Args extends CommonArgs {
collection: CollectionConfig;
}
interface GlobalArgs extends CommonArgs {
global: GlobalConfig;
}
export const getGlobalAfterChangeHook =
({ global, pluginOptions }: GlobalArgs): GlobalAfterChangeHook =>
async ({
doc, // full document data
previousDoc, // document data before updating the collection
req, // full express request
}) => {
const operation = previousDoc ? "update" : "create";
return performAfterChange({
doc,
req,
previousDoc,
operation,
collection: global,
global: true,
pluginOptions,
});
};
export const getAfterChangeHook =
({ collection, pluginOptions }: Args): CollectionAfterChangeHook =>
async ({
doc, // full document data
req, // full express request
previousDoc, // document data before updating the collection
operation, // name of the operation ie. 'create', 'update'
}) => {
return performAfterChange({
doc,
req,
previousDoc,
operation,
collection,
pluginOptions,
});
};
interface IPerformChange {
doc: any;
req: PayloadRequest;
previousDoc: any;
operation: string;
collection: CollectionConfig | GlobalConfig;
global?: boolean;
pluginOptions: PluginOptions;
}
const performAfterChange = async ({
doc, // full document data
req, // full express request
previousDoc,
operation,
collection,
global = false,
pluginOptions,
}: IPerformChange) => {
/**
* Abort if token not set and not in test mode
*/
if (!pluginOptions.token && process.env.NODE_ENV !== "test") {
return doc;
}
| const localizedFields: Field[] = getLocalizedFields({ |
fields: collection.fields,
});
/**
* Abort if there are no fields to localize
*/
if (localizedFields.length === 0) {
return doc;
}
/**
* Abort if locale is unavailable or this
* is an update from the API to the source
* locale.
*/
if (!req.locale || req.locale !== pluginOptions.sourceLocale) {
return doc;
}
/**
* Prepare JSON objects
*
* `text` fields are compiled into a single JSON file
* on Crowdin. Prepare previous and current objects.
*/
const currentCrowdinJsonData = buildCrowdinJsonObject({
doc,
fields: localizedFields,
});
const prevCrowdinJsonData = buildCrowdinJsonObject({
doc: previousDoc,
fields: localizedFields,
});
/**
* Initialize Crowdin client sourceFilesApi
*/
const filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, req.payload);
/**
* Retrieve the Crowdin Article Directory article
*
* Records of Crowdin directories are stored in Payload.
*/
const articleDirectory = await filesApi.findOrCreateArticleDirectory({
document: doc,
collectionSlug: collection.slug,
global,
});
// START: function definitions
const createOrUpdateJsonFile = async () => {
await filesApi.createOrUpdateFile({
name: "fields",
value: currentCrowdinJsonData,
fileType: "json",
articleDirectory,
});
};
const createOrUpdateHtmlFile = async ({
name,
value,
}: {
name: string;
value: Descendant[];
}) => {
await filesApi.createOrUpdateFile({
name: name,
value: convertSlateToHtml(value),
fileType: "html",
articleDirectory,
});
};
const createOrUpdateJsonSource = async () => {
if (
(!deepEqual(currentCrowdinJsonData, prevCrowdinJsonData) &&
Object.keys(currentCrowdinJsonData).length !== 0) ||
process.env.PAYLOAD_CROWDIN_SYNC_ALWAYS_UPDATE === "true"
) {
await createOrUpdateJsonFile();
}
};
/**
* Recursively send rich text fields to Crowdin as HTML
*
* Name these HTML files with dot notation. Examples:
*
* * `localizedRichTextField`
* * `groupField.localizedRichTextField`
* * `arrayField[0].localizedRichTextField`
* * `arrayField[1].localizedRichTextField`
*/
const createOrUpdateHtmlSource = async () => {
const currentCrowdinHtmlData = buildCrowdinHtmlObject({
doc,
fields: localizedFields,
});
const prevCrowdinHtmlData = buildCrowdinHtmlObject({
doc: previousDoc,
fields: localizedFields,
});
Object.keys(currentCrowdinHtmlData).forEach(async (name) => {
const currentValue = currentCrowdinHtmlData[name];
const prevValue = prevCrowdinHtmlData[name];
if (
!fieldChanged(prevValue, currentValue, "richText") &&
process.env.PAYLOAD_CROWDIN_SYNC_ALWAYS_UPDATE !== "true"
) {
return;
}
const file = await createOrUpdateHtmlFile({
name,
value: currentValue as Descendant[],
});
});
};
// END: function definitions
await createOrUpdateJsonSource();
await createOrUpdateHtmlSource();
return doc;
};
| src/hooks/collections/afterChange.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/hooks/collections/afterDelete.ts",
"retrieved_chunk": " req, // full express request\n id, // id of document to delete\n doc, // deleted document\n }) => {\n /**\n * Abort if token not set and not in test mode\n */\n if (!pluginOptions.token && process.env.NODE_ENV !== \"test\") {\n return doc;\n }",
"score": 0.9388753175735474
},
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " });\n return docTranslations;\n } catch (error) {\n console.log(error);\n throw new Error(`${error}`);\n }\n }\n /**\n * Retrieve translations from Crowdin for a document in a given locale\n */",
"score": 0.8614969849586487
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": " doc,\n fields,\n topLevel = true,\n}: {\n doc: { [key: string]: any };\n /** Use getLocalizedFields to pass localized fields only */\n fields: Field[];\n /** Flag used internally to filter json fields before recursion. */\n topLevel?: boolean;\n}) => {",
"score": 0.8478776216506958
},
{
"filename": "src/utilities/getLocalizedFields.spec.ts",
"retrieved_chunk": " type: \"array\",\n fields: [...localizedFieldCollection],\n },\n ];\n expect(getLocalizedFields({ fields })).toEqual(expected);\n });\n /**\n * * help ensure no errors during version 0 development\n * * mitigate against errors if a new field type is introduced by Payload CMS\n */",
"score": 0.8464628458023071
},
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " }: IupdateTranslation) {\n /**\n * Get existing document\n *\n * * check document exists\n * * check for `meta` field (which can be added by @payloadcms/seo)\n *\n */\n let doc: { crowdinArticleDirectory: { id: any } };\n if (global) {",
"score": 0.8445558547973633
}
] | typescript | const localizedFields: Field[] = getLocalizedFields({ |
import * as dotenv from 'dotenv'
import { readFile as rd } from 'fs'
import { promisify } from 'util'
import { ChatGPTAPI, ChatGPTError, ChatMessage, SendMessageOptions } from 'chatgpt'
import pRetry, { AbortError, FailedAttemptError } from 'p-retry'
import { extractJsonArray, extractCodeBlock, extractPostOutlineFromCodeBlock, extractSeoInfo, extractAudienceIntentInfo } from './extractor'
import {
getPromptForMainKeyword,
getPromptForOutline,
getPromptForIntroduction,
getPromptForHeading,
getPromptForConclusion,
getAutoSystemPrompt,
getPromptForSeoInfo,
getCustomSystemPrompt,
getSeoSystemPrompt,
getPromptForIntentAudience as getPromptForAudienceIntent
} from './prompts'
import {
Heading,
PostOutline,
PostPrompt,
TotalTokens,
SeoInfo
} from '../types'
import { encode } from './tokenizer'
import { extractPrompts } from './template'
import { log } from 'console'
import { NoApiKeyError } from './errors'
dotenv.config()
const readFile = promisify(rd)
/**
* Specific Open AI API parameters for the completion
*/
export type CompletionParams = {
temperature?: number | null,
top_p?: number | null,
max_tokens?: number,
presence_penalty?: number | null,
frequency_penalty?: number | null,
logit_bias?: object | null,
}
/**
* Interface for the helper class for generating a post. it defines how to generate a post
* Each helper class must implement this interface
* @interface
*/
export interface GeneratorHelperInterface {
init () : Promise<void>
isCustom() : boolean
generateContentOutline () : Promise<PostOutline>
generateMainKeyword () : Promise<string[]>
generateIntroduction () : Promise<string>
generateConclusion () : Promise<string>
generateHeadingContents (tableOfContent : PostOutline) : Promise<string>
generateCustomPrompt(prompt : string) : Promise<string>
generateSeoInfo () : Promise<SeoInfo>
getTotalTokens() : TotalTokens
getPrompt() : PostPrompt
}
/**
* Helper implementation for generating a post using the ChatGPT API
* @class
*/
export class ChatGptHelper implements GeneratorHelperInterface {
private postPrompt : PostPrompt
private api : ChatGPTAPI
// The parent message is either the previous one in the conversation (if a template is used)
// or the generated outline (if we are in auto mode)
private chatParentMessage : ChatMessage
private completionParams : CompletionParams
private totalTokens : TotalTokens = {
promptTokens: 0,
completionTokens: 0,
total: 0
}
// -----------------------------------------------
// CONSTRUCTOR AND INITIALIZATION
// -----------------------------------------------
public constructor (postPrompt : PostPrompt) {
this.postPrompt = postPrompt
}
isCustom () : boolean {
return this.postPrompt?.templateFile !== undefined
}
getPrompt (): PostPrompt {
return this.postPrompt
}
getTotalTokens (): TotalTokens {
return this.totalTokens
}
async init () {
if (this.isCustom()) {
if (this.postPrompt.debug) {
console.log(`Use template : ${this.postPrompt.templateFile}`)
}
this.postPrompt.templateContent = await this.readTemplate()
this.postPrompt.prompts = extractPrompts(this.postPrompt.templateContent)
}
const systemMessage = this.isCustom() ? getCustomSystemPrompt(this.postPrompt) : getAutoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemMessage)
}
private async buildChatGPTAPI (systemMessage : string) {
try {
this.api = new ChatGPTAPI({
apiKey: this.postPrompt?.apiKey || process.env.OPENAI_API_KEY,
completionParams: {
model: this.postPrompt.model
},
systemMessage,
debug: this.postPrompt.debugapi
})
} catch (error) {
throw new NoApiKeyError()
}
if (this.postPrompt.debug) {
console.log(`OpenAI API initialized with model : ${this.postPrompt.model}`)
}
this.completionParams = {
temperature: this.postPrompt.temperature ?? 0.8,
frequency_penalty: this.postPrompt.frequencyPenalty ?? 0,
presence_penalty: this.postPrompt.presencePenalty ?? 1
}
if (this.postPrompt.logitBias) {
const mainKwWords = await this.generateMainKeyword()
// set the logit bias in order to force the model to minimize the usage of the main keyword
const logitBiais: Record<number, number> = {}
mainKwWords.forEach((kw) => {
const encoded = encode(kw)
encoded.forEach((element) => {
logitBiais[element] = Number(this.postPrompt.logitBias) || -1
})
})
this.completionParams.logit_bias = logitBiais
}
if (this.postPrompt.debug) {
console.log('---------- COMPLETION PARAMETERS ----------')
console.log('Max Tokens : ' + this.completionParams.max_tokens)
console.log('Temperature : ' + this.completionParams.temperature)
console.log('Frequency Penalty : ' + this.completionParams.frequency_penalty)
console.log('Presence Penalty : ' + this.completionParams.presence_penalty)
console.log('Logit Biais : ' + this.completionParams.logit_bias)
}
}
// -----------------------------------------------
// METHODS FOR THE AUTOMATIC MODE
// -----------------------------------------------
async generateMainKeyword () {
const prompt = getPromptForMainKeyword()
if (this.postPrompt.debug) {
console.log('---------- PROMPT MAIN KEYWORD ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- MAIN KEYWORD ----------')
console.log(response.text)
}
return extractJsonArray(response.text)
}
async generateContentOutline () {
if (this.postPrompt.generate) {
const audienceIntent = await this.generateAudienceIntent()
this.postPrompt = {
...audienceIntent,
...this.postPrompt
}
}
const prompt = getPromptForOutline(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT OUTLINE ----------')
console.log(prompt)
}
// the parent message is the outline for the upcoming content
// By this way, we can decrease the cost of the API call by minimizing the number of prompt tokens
// TODO : add an option to disable this feature
this.chatParentMessage = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- OUTLINE ----------')
console.log(this.chatParentMessage.text)
}
return extractPostOutlineFromCodeBlock(this.chatParentMessage.text)
}
async generateAudienceIntent () {
const prompt = getPromptForAudienceIntent(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT AUDIENCE INTENT ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- AUDIENCE INTENT ----------')
console.log(response.text)
}
return extractAudienceIntentInfo(response.text)
}
async generateIntroduction () {
const response = await this.sendRequest(getPromptForIntroduction(this.postPrompt), this.completionParams)
| return extractCodeBlock(response.text)
} |
async generateConclusion () {
const response = await this.sendRequest(getPromptForConclusion(), this.completionParams)
return extractCodeBlock(response.text)
}
async generateHeadingContents (postOutline : PostOutline) {
const headingLevel = 2
return await this.buildContent(postOutline.headings, headingLevel)
}
private async buildContent (headings: Heading[], headingLevel : number, previousContent: string = ''): Promise<string> {
if (headings.length === 0) {
return previousContent
}
const [currentHeading, ...remainingHeadings] = headings
const mdHeading = Array(headingLevel).fill('#').join('')
let content = previousContent + '\n' + mdHeading + ' ' + currentHeading.title
if (currentHeading.headings && currentHeading.headings.length > 0) {
content = await this.buildContent(currentHeading.headings, headingLevel + 1, content)
} else {
content += '\n' + await this.getContent(currentHeading)
}
return this.buildContent(remainingHeadings, headingLevel, content)
}
private async getContent (heading: Heading): Promise<string> {
if (this.postPrompt.debug) {
console.log(`\nHeading : ${heading.title} ...'\n`)
}
const response = await this.sendRequest(getPromptForHeading(this.postPrompt.tone, heading.title, heading.keywords), this.completionParams)
return `${extractCodeBlock(response.text)}\n`
}
// -----------------------------------------------
// METHODS FOR THE CUSTOM MODE base on a template
// -----------------------------------------------
/**
* Generate a content based on one of prompt defined in the template
* @param customPrompt : the prompt defined in the template
* @returns the AI answer
*/
async generateCustomPrompt (customPrompt : string) {
this.chatParentMessage = await this.sendRequest(customPrompt, this.completionParams)
return extractCodeBlock(this.chatParentMessage.text)
}
/**
* Generate the SEO info for the post based on the template
* @returns the SEO info
*/
async generateSeoInfo (): Promise<SeoInfo> {
const systemPrompt = getSeoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemPrompt)
this.chatParentMessage = await this.sendRequest(getPromptForSeoInfo(this.postPrompt), this.completionParams)
if (this.postPrompt.debug) {
log('---------- SEO INFO ----------')
console.log(this.chatParentMessage.text)
}
return extractSeoInfo(this.chatParentMessage.text)
}
private async readTemplate () : Promise<string> {
const templatePath = this.postPrompt.templateFile
return await readFile(templatePath, 'utf-8')
}
// -----------------------------------------------
// SEND REQUEST TO OPENAI API
// -----------------------------------------------
private async sendRequest (prompt : string, completionParams? : CompletionParams) {
return await pRetry(async () => {
const options : SendMessageOptions = { parentMessageId: this.chatParentMessage?.id }
if (completionParams) {
options.completionParams = completionParams
}
const response = await this.api.sendMessage(prompt, options)
this.totalTokens.promptTokens += response.detail.usage.prompt_tokens
this.totalTokens.completionTokens += response.detail.usage.completion_tokens
this.totalTokens.total += response.detail.usage.total_tokens
return response
}, {
retries: 10,
onFailedAttempt: async (error) => {
this.manageError(error)
}
})
}
private manageError (error: FailedAttemptError) {
if (this.postPrompt.debug) {
console.log('---------- OPENAI REQUEST ERROR ----------')
console.log(error)
}
if (error instanceof ChatGPTError) {
const chatGPTError = error as ChatGPTError
if (chatGPTError.statusCode === 401) {
console.log('OpenAI API Error : Invalid API key: please check your API key in the option -k or in the OPENAI_API_KEY env var.')
process.exit(1)
}
if (chatGPTError.statusCode === 404) {
console.log(`OpenAI API Error : Invalid model for your OpenAI subscription. Check if you can use : ${this.postPrompt.model}.`)
console.log(this.postPrompt.model === 'gpt-4' || this.postPrompt.model === 'gpt-4-32k' ? 'You need to join the waiting list to use the GPT-4 API : https://openai.com/waitlist/gpt-4-api' : '')
process.exit(1)
}
}
if (error instanceof AbortError) {
console.log(`OpenAI API - Request aborted. ${error.message}`)
} else {
console.log(`OpenAI API - Request failed - Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left. ${error.message}`)
}
}
}
| src/lib/post-helpers.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/post.ts",
"retrieved_chunk": " )\n promptContents.push(content)\n }\n // We replace the prompts by the AI answer in the template content\n const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)\n const seoInfo = await oraPromise(\n this.helper.generateSeoInfo(),\n {\n text: 'Generating SEO info ...'\n }",
"score": 0.8134030699729919
},
{
"filename": "src/post.ts",
"retrieved_chunk": " const tableOfContent = await oraPromise(\n this.helper.generateContentOutline(),\n {\n text: 'Generating post outline ...'\n }\n )\n let content = await oraPromise(\n this.helper.generateIntroduction(),\n {\n text: 'Generating introduction...'",
"score": 0.8043810129165649
},
{
"filename": "src/post.ts",
"retrieved_chunk": " }\n )\n content += await oraPromise(\n this.helper.generateHeadingContents(tableOfContent),\n {\n text: 'Generating content ...'\n }\n )\n if (this.helper.getPrompt().withConclusion) {\n content += await oraPromise(",
"score": 0.8012921214103699
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " })\n}\nasync function generatePost (options: Options) {\n let answers : any = {}\n if (isInteractive(options)) {\n answers = isCustom(options) ? await askCustomQuestions() : await askQuestions()\n }\n const defaultPostPrompt = buildDefaultPostPrompt()\n const postPrompt : PostPrompt = {\n ...defaultPostPrompt,",
"score": 0.7968320250511169
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " ...options,\n ...answers,\n maxModelTokens: answers.model === 'gpt-4' ? 8000 : 4000\n }\n if (!postPrompt.topic) {\n throw new Error('The topic is mandatory, use the option -tp or --topic')\n }\n const postGenerator = new OpenAIPostGenerator(postPrompt)\n const post = await postGenerator.generate()\n const jsonData = {",
"score": 0.7858225107192993
}
] | typescript | return extractCodeBlock(response.text)
} |
import * as dotenv from 'dotenv'
import { readFile as rd } from 'fs'
import { promisify } from 'util'
import { ChatGPTAPI, ChatGPTError, ChatMessage, SendMessageOptions } from 'chatgpt'
import pRetry, { AbortError, FailedAttemptError } from 'p-retry'
import { extractJsonArray, extractCodeBlock, extractPostOutlineFromCodeBlock, extractSeoInfo, extractAudienceIntentInfo } from './extractor'
import {
getPromptForMainKeyword,
getPromptForOutline,
getPromptForIntroduction,
getPromptForHeading,
getPromptForConclusion,
getAutoSystemPrompt,
getPromptForSeoInfo,
getCustomSystemPrompt,
getSeoSystemPrompt,
getPromptForIntentAudience as getPromptForAudienceIntent
} from './prompts'
import {
Heading,
PostOutline,
PostPrompt,
TotalTokens,
SeoInfo
} from '../types'
import { encode } from './tokenizer'
import { extractPrompts } from './template'
import { log } from 'console'
import { NoApiKeyError } from './errors'
dotenv.config()
const readFile = promisify(rd)
/**
* Specific Open AI API parameters for the completion
*/
export type CompletionParams = {
temperature?: number | null,
top_p?: number | null,
max_tokens?: number,
presence_penalty?: number | null,
frequency_penalty?: number | null,
logit_bias?: object | null,
}
/**
* Interface for the helper class for generating a post. it defines how to generate a post
* Each helper class must implement this interface
* @interface
*/
export interface GeneratorHelperInterface {
init () : Promise<void>
isCustom() : boolean
generateContentOutline () : Promise<PostOutline>
generateMainKeyword () : Promise<string[]>
generateIntroduction () : Promise<string>
generateConclusion () : Promise<string>
generateHeadingContents (tableOfContent : PostOutline) : Promise<string>
generateCustomPrompt(prompt : string) : Promise<string>
generateSeoInfo () : Promise<SeoInfo>
getTotalTokens() : TotalTokens
getPrompt() : PostPrompt
}
/**
* Helper implementation for generating a post using the ChatGPT API
* @class
*/
export class ChatGptHelper implements GeneratorHelperInterface {
private postPrompt : PostPrompt
private api : ChatGPTAPI
// The parent message is either the previous one in the conversation (if a template is used)
// or the generated outline (if we are in auto mode)
private chatParentMessage : ChatMessage
private completionParams : CompletionParams
private totalTokens : TotalTokens = {
promptTokens: 0,
completionTokens: 0,
total: 0
}
// -----------------------------------------------
// CONSTRUCTOR AND INITIALIZATION
// -----------------------------------------------
public constructor (postPrompt : PostPrompt) {
this.postPrompt = postPrompt
}
isCustom () : boolean {
return this.postPrompt?.templateFile !== undefined
}
getPrompt (): PostPrompt {
return this.postPrompt
}
getTotalTokens (): TotalTokens {
return this.totalTokens
}
async init () {
if (this.isCustom()) {
if (this.postPrompt.debug) {
console.log(`Use template : ${this.postPrompt.templateFile}`)
}
this.postPrompt.templateContent = await this.readTemplate()
this.postPrompt.prompts = extractPrompts(this.postPrompt.templateContent)
}
const systemMessage = this.isCustom() ? getCustomSystemPrompt(this.postPrompt) : getAutoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemMessage)
}
private async buildChatGPTAPI (systemMessage : string) {
try {
this.api = new ChatGPTAPI({
apiKey: this.postPrompt?.apiKey || process.env.OPENAI_API_KEY,
completionParams: {
model: this.postPrompt.model
},
systemMessage,
debug: this.postPrompt.debugapi
})
} catch (error) {
throw new NoApiKeyError()
}
if (this.postPrompt.debug) {
console.log(`OpenAI API initialized with model : ${this.postPrompt.model}`)
}
this.completionParams = {
temperature: this.postPrompt.temperature ?? 0.8,
frequency_penalty: this.postPrompt.frequencyPenalty ?? 0,
presence_penalty: this.postPrompt.presencePenalty ?? 1
}
if (this.postPrompt.logitBias) {
const mainKwWords = await this.generateMainKeyword()
// set the logit bias in order to force the model to minimize the usage of the main keyword
const logitBiais: Record<number, number> = {}
mainKwWords.forEach((kw) => {
const encoded = encode(kw)
encoded.forEach((element) => {
logitBiais[element] = Number(this.postPrompt.logitBias) || -1
})
})
this.completionParams.logit_bias = logitBiais
}
if (this.postPrompt.debug) {
console.log('---------- COMPLETION PARAMETERS ----------')
console.log('Max Tokens : ' + this.completionParams.max_tokens)
console.log('Temperature : ' + this.completionParams.temperature)
console.log('Frequency Penalty : ' + this.completionParams.frequency_penalty)
console.log('Presence Penalty : ' + this.completionParams.presence_penalty)
console.log('Logit Biais : ' + this.completionParams.logit_bias)
}
}
// -----------------------------------------------
// METHODS FOR THE AUTOMATIC MODE
// -----------------------------------------------
async generateMainKeyword () {
const prompt = getPromptForMainKeyword()
if (this.postPrompt.debug) {
console.log('---------- PROMPT MAIN KEYWORD ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- MAIN KEYWORD ----------')
console.log(response.text)
}
| return extractJsonArray(response.text)
} |
async generateContentOutline () {
if (this.postPrompt.generate) {
const audienceIntent = await this.generateAudienceIntent()
this.postPrompt = {
...audienceIntent,
...this.postPrompt
}
}
const prompt = getPromptForOutline(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT OUTLINE ----------')
console.log(prompt)
}
// the parent message is the outline for the upcoming content
// By this way, we can decrease the cost of the API call by minimizing the number of prompt tokens
// TODO : add an option to disable this feature
this.chatParentMessage = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- OUTLINE ----------')
console.log(this.chatParentMessage.text)
}
return extractPostOutlineFromCodeBlock(this.chatParentMessage.text)
}
async generateAudienceIntent () {
const prompt = getPromptForAudienceIntent(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT AUDIENCE INTENT ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- AUDIENCE INTENT ----------')
console.log(response.text)
}
return extractAudienceIntentInfo(response.text)
}
async generateIntroduction () {
const response = await this.sendRequest(getPromptForIntroduction(this.postPrompt), this.completionParams)
return extractCodeBlock(response.text)
}
async generateConclusion () {
const response = await this.sendRequest(getPromptForConclusion(), this.completionParams)
return extractCodeBlock(response.text)
}
async generateHeadingContents (postOutline : PostOutline) {
const headingLevel = 2
return await this.buildContent(postOutline.headings, headingLevel)
}
private async buildContent (headings: Heading[], headingLevel : number, previousContent: string = ''): Promise<string> {
if (headings.length === 0) {
return previousContent
}
const [currentHeading, ...remainingHeadings] = headings
const mdHeading = Array(headingLevel).fill('#').join('')
let content = previousContent + '\n' + mdHeading + ' ' + currentHeading.title
if (currentHeading.headings && currentHeading.headings.length > 0) {
content = await this.buildContent(currentHeading.headings, headingLevel + 1, content)
} else {
content += '\n' + await this.getContent(currentHeading)
}
return this.buildContent(remainingHeadings, headingLevel, content)
}
private async getContent (heading: Heading): Promise<string> {
if (this.postPrompt.debug) {
console.log(`\nHeading : ${heading.title} ...'\n`)
}
const response = await this.sendRequest(getPromptForHeading(this.postPrompt.tone, heading.title, heading.keywords), this.completionParams)
return `${extractCodeBlock(response.text)}\n`
}
// -----------------------------------------------
// METHODS FOR THE CUSTOM MODE base on a template
// -----------------------------------------------
/**
* Generate a content based on one of prompt defined in the template
* @param customPrompt : the prompt defined in the template
* @returns the AI answer
*/
async generateCustomPrompt (customPrompt : string) {
this.chatParentMessage = await this.sendRequest(customPrompt, this.completionParams)
return extractCodeBlock(this.chatParentMessage.text)
}
/**
* Generate the SEO info for the post based on the template
* @returns the SEO info
*/
async generateSeoInfo (): Promise<SeoInfo> {
const systemPrompt = getSeoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemPrompt)
this.chatParentMessage = await this.sendRequest(getPromptForSeoInfo(this.postPrompt), this.completionParams)
if (this.postPrompt.debug) {
log('---------- SEO INFO ----------')
console.log(this.chatParentMessage.text)
}
return extractSeoInfo(this.chatParentMessage.text)
}
private async readTemplate () : Promise<string> {
const templatePath = this.postPrompt.templateFile
return await readFile(templatePath, 'utf-8')
}
// -----------------------------------------------
// SEND REQUEST TO OPENAI API
// -----------------------------------------------
private async sendRequest (prompt : string, completionParams? : CompletionParams) {
return await pRetry(async () => {
const options : SendMessageOptions = { parentMessageId: this.chatParentMessage?.id }
if (completionParams) {
options.completionParams = completionParams
}
const response = await this.api.sendMessage(prompt, options)
this.totalTokens.promptTokens += response.detail.usage.prompt_tokens
this.totalTokens.completionTokens += response.detail.usage.completion_tokens
this.totalTokens.total += response.detail.usage.total_tokens
return response
}, {
retries: 10,
onFailedAttempt: async (error) => {
this.manageError(error)
}
})
}
private manageError (error: FailedAttemptError) {
if (this.postPrompt.debug) {
console.log('---------- OPENAI REQUEST ERROR ----------')
console.log(error)
}
if (error instanceof ChatGPTError) {
const chatGPTError = error as ChatGPTError
if (chatGPTError.statusCode === 401) {
console.log('OpenAI API Error : Invalid API key: please check your API key in the option -k or in the OPENAI_API_KEY env var.')
process.exit(1)
}
if (chatGPTError.statusCode === 404) {
console.log(`OpenAI API Error : Invalid model for your OpenAI subscription. Check if you can use : ${this.postPrompt.model}.`)
console.log(this.postPrompt.model === 'gpt-4' || this.postPrompt.model === 'gpt-4-32k' ? 'You need to join the waiting list to use the GPT-4 API : https://openai.com/waitlist/gpt-4-api' : '')
process.exit(1)
}
}
if (error instanceof AbortError) {
console.log(`OpenAI API - Request aborted. ${error.message}`)
} else {
console.log(`OpenAI API - Request failed - Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left. ${error.message}`)
}
}
}
| src/lib/post-helpers.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/post.ts",
"retrieved_chunk": " )\n promptContents.push(content)\n }\n // We replace the prompts by the AI answer in the template content\n const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)\n const seoInfo = await oraPromise(\n this.helper.generateSeoInfo(),\n {\n text: 'Generating SEO info ...'\n }",
"score": 0.7962223291397095
},
{
"filename": "src/post.ts",
"retrieved_chunk": " }\n )\n content += await oraPromise(\n this.helper.generateHeadingContents(tableOfContent),\n {\n text: 'Generating content ...'\n }\n )\n if (this.helper.getPrompt().withConclusion) {\n content += await oraPromise(",
"score": 0.7882646322250366
},
{
"filename": "src/lib/prompts.ts",
"retrieved_chunk": " return prompt\n}\nexport function getPromptForMainKeyword () {\n const prompt = 'Give me the most important SEO keyword in a JSON array in which each item matches a word without the stop words.'\n return prompt\n}\nexport function getPromptForIntroduction (postPrompt : PostPrompt) {\n return (!postPrompt.tone) || postPrompt.tone === 'informative' ? INFORMATIVE_INTRO_PROMPT : CAPTIVATING_INTO_PROMPT\n}\nexport function getPromptForHeading (tone : string, title : string, keywords : string[] | null) {",
"score": 0.787566065788269
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " ...options,\n ...answers,\n maxModelTokens: answers.model === 'gpt-4' ? 8000 : 4000\n }\n if (!postPrompt.topic) {\n throw new Error('The topic is mandatory, use the option -tp or --topic')\n }\n const postGenerator = new OpenAIPostGenerator(postPrompt)\n const post = await postGenerator.generate()\n const jsonData = {",
"score": 0.7827599048614502
},
{
"filename": "src/post.ts",
"retrieved_chunk": " // We remove the first prompt because it is the system prompt\n const prompts = this.helper.getPrompt().prompts.slice(1)\n // for each prompt, we generate the content\n const templatePrompts = prompts.entries()\n for (const [index, prompt] of templatePrompts) {\n const content = await oraPromise(\n this.helper.generateCustomPrompt(prompt),\n {\n text: `Generating the prompt num. ${index + 1} ...`\n }",
"score": 0.77918541431427
}
] | typescript | return extractJsonArray(response.text)
} |
import {
Body,
Controller,
Delete,
Get,
Logger,
Param,
Post,
Put,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { TodoListService } from './todolist.service';
import TodoList from '../models/todolist/todolist';
import Task from '../models/task/task';
@Controller('todolist')
export class TodoListController {
constructor(private readonly appService: TodoListService) {}
@Post()
@UsePipes(new ValidationPipe())
createTodoList(@Body() list: TodoList): TodoList {
try {
const id = this.appService.AddList(list);
return this.appService.GetList(id);
} catch (error) {
Logger.error(error);
}
}
@Get(':id')
getTodoList(@Param('id') listId: string): TodoList {
return this.appService.GetList(listId);
}
@Delete(':id')
@UsePipes(new ValidationPipe())
deleteList(@Param('id') listId: string): string {
this.appService.RemoveList(listId);
return 'done';
}
@Put(':id')
@UsePipes(new ValidationPipe())
updateList(
@Param('id') listId: string,
@Body('Name') newName: string,
): TodoList {
this.appService.UpdateListName(listId, newName);
return this.appService.GetList(listId);
}
@Post(':id/task')
@UsePipes(new ValidationPipe())
createTask(@Body() | task: Task, @Param('id') listId: string): string { |
const id = this.appService.AddTask(listId, task);
return id;
}
}
| src/todolist/todolist.controller.ts | nitzan8897-TodoListNestJS-72123e7 | [
{
"filename": "src/models/task/task.ts",
"retrieved_chunk": " doneStatus: boolean;\n @IsString()\n @IsNotEmpty()\n description: string;\n @ManyToOne(() => TodoList, (todoList) => todoList.Tasks)\n todoList: TodoList;\n}",
"score": 0.7825431823730469
},
{
"filename": "src/todolist/todolist.service.ts",
"retrieved_chunk": " delete this.RAMMemory[listId];\n }\n GetList(listId: string): TodoList | undefined {\n listIdValidation(this.RAMMemory, listId);\n return this.RAMMemory[listId];\n }\n UpdateListName(listId: string, listNewName: string): void {\n listIdValidation(this.RAMMemory, listId);\n this.RAMMemory[listId].Name = listNewName;\n }",
"score": 0.7614057064056396
},
{
"filename": "src/todolist/todolist.service.ts",
"retrieved_chunk": " AddTask(listId: string, task: Task): string {\n listIdValidation(this.RAMMemory, listId);\n const taskId = uuidv4();\n task.taskId = taskId;\n this.RAMMemory[listId].Tasks.push(task);\n Logger.log(`Added new Task, ${task.description} to the list: ${listId}`);\n return taskId;\n }\n}",
"score": 0.7489855289459229
},
{
"filename": "src/models/todolist/todolist-actions.module.ts",
"retrieved_chunk": "import IList from \"./todolist.module\";\nexport default interface ITodoListActions {\n AddList(list: IList): string;\n RemoveList(listId: string): void;\n GetList(listId: string): IList | undefined;\n UpdateListName(listId: string, listNewName: string): void;\n}",
"score": 0.7436429262161255
},
{
"filename": "src/utils/index.ts",
"retrieved_chunk": "import { HttpException, HttpStatus } from '@nestjs/common';\nimport TodoList from '../models/todolist/todolist';\nimport { ListNotFound } from './messages';\nexport const listIdValidation = (\n RAMMemory: Record<string, TodoList>,\n listId: string,\n) => {\n if (!RAMMemory[listId]) {\n throw new HttpException(ListNotFound(listId), HttpStatus.NOT_FOUND);\n }",
"score": 0.7221975326538086
}
] | typescript | task: Task, @Param('id') listId: string): string { |
import JSON5 from 'json5'
import { validate } from 'jsonschema'
import { AudienceIntentInfo, PostOutline, SeoInfo } from '../types'
export class PostOutlineValidationError extends Error {
constructor (message: string, public readonly errors: any[]) {
super(message)
}
}
const schemaValidiation = {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
properties: {
title: {
type: 'string'
},
headings: {
type: 'array',
items: {
$ref: '#/definitions/Heading'
}
},
slug: {
type: 'string'
},
seoTitle: {
type: 'string'
},
seoDescription: {
type: 'string'
}
},
required: [
'title',
'headings',
'slug',
'seoTitle',
'seoDescription'
],
additionalProperties: false,
definitions: {
Heading: {
type: 'object',
properties: {
title: {
type: 'string'
},
keywords: {
type: 'array',
items: {
type: 'string'
}
},
headings: {
type: 'array',
items: {
$ref: '#/definitions/Heading'
}
}
},
required: [
'title'
],
additionalProperties: false
}
}
}
export function extractCodeBlock (text: string): string {
// Extract code blocks with specified tags
const codeBlockTags = ['markdown', 'html', 'json']
for (const tag of codeBlockTags) {
const regex = new RegExp(`\`\`\`${tag}((.|\\n|\\r)*?)\`\`\``, 'i')
const match = text.match(regex)
if (match) {
return match[1]
}
}
// Extract code blocks without specified tags
const genericRegex = /```\n?((.|\\n|\\r)*?)```/
const genericMatch = text.match(genericRegex)
if (genericMatch) {
return genericMatch[1]
}
// No code blocks found
return text
}
export function extractPostOutlineFromCodeBlock (text: string) : PostOutline {
// Use JSON5 because it supports trailing comma and comments in the json text
const jsonData = JSON5.parse(extractCodeBlock(text))
const v = validate(jsonData, schemaValidiation)
if (!v.valid) {
const errorList = v.errors.map((val) => val.toString())
throw new PostOutlineValidationError('Invalid json for the post outline', errorList)
}
return jsonData
}
export function extractJsonArray (text : string) : string[] {
return JSON5.parse(extractCodeBlock(text))
}
| export function extractSeoInfo (text : string) : SeoInfo { |
return JSON5.parse(extractCodeBlock(text))
}
export function extractAudienceIntentInfo (text : string) : AudienceIntentInfo {
return JSON5.parse(extractCodeBlock(text))
}
| src/lib/extractor.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " log('---------- SEO INFO ----------')\n console.log(this.chatParentMessage.text)\n }\n return extractSeoInfo(this.chatParentMessage.text)\n }\n private async readTemplate () : Promise<string> {\n const templatePath = this.postPrompt.templateFile\n return await readFile(templatePath, 'utf-8')\n }\n // -----------------------------------------------",
"score": 0.8014512062072754
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " async generateConclusion () {\n const response = await this.sendRequest(getPromptForConclusion(), this.completionParams)\n return extractCodeBlock(response.text)\n }\n async generateHeadingContents (postOutline : PostOutline) {\n const headingLevel = 2\n return await this.buildContent(postOutline.headings, headingLevel)\n }\n private async buildContent (headings: Heading[], headingLevel : number, previousContent: string = ''): Promise<string> {\n if (headings.length === 0) {",
"score": 0.7762673497200012
},
{
"filename": "src/bin/command/wp.ts",
"retrieved_chunk": " .description('Update a new post to a Wordpress site. The file has to be a json file containing : { content, seoTitle, seoDescription }')\n .action(async (domain, slug, jsonFile, options : UpdateOptions) => {\n const domainFound = await getWordpress(domain)\n if (!domainFound) {\n console.log(`\\nWordpress site ${domain} not found\\n`)\n return\n }\n const jsonContent = await readFile(jsonFile, 'utf8')\n const newContent: Post = JSON.parse(jsonContent)\n await updatePost(domainFound, slug, newContent, options.date)",
"score": 0.7748700380325317
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": "}\nfunction getFileExtension (options : Options) {\n // in custom mode, we use the template extension\n // in auto/default mode, we use the markdown extension in all cases\n return isCustom(options) ? options.templateFile.split('.').pop() : 'md'\n}\nfunction buildMDPage (post: Post) {\n return '# ' + post.title + '\\n' + post.content\n}\nfunction buildHTMLPage (post : Post) {",
"score": 0.7738438844680786
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " if (this.postPrompt.debug) {\n console.log('---------- AUDIENCE INTENT ----------')\n console.log(response.text)\n }\n return extractAudienceIntentInfo(response.text)\n }\n async generateIntroduction () {\n const response = await this.sendRequest(getPromptForIntroduction(this.postPrompt), this.completionParams)\n return extractCodeBlock(response.text)\n }",
"score": 0.7712899446487427
}
] | typescript | export function extractSeoInfo (text : string) : SeoInfo { |
import * as dotenv from 'dotenv'
import { readFile as rd } from 'fs'
import { promisify } from 'util'
import { ChatGPTAPI, ChatGPTError, ChatMessage, SendMessageOptions } from 'chatgpt'
import pRetry, { AbortError, FailedAttemptError } from 'p-retry'
import { extractJsonArray, extractCodeBlock, extractPostOutlineFromCodeBlock, extractSeoInfo, extractAudienceIntentInfo } from './extractor'
import {
getPromptForMainKeyword,
getPromptForOutline,
getPromptForIntroduction,
getPromptForHeading,
getPromptForConclusion,
getAutoSystemPrompt,
getPromptForSeoInfo,
getCustomSystemPrompt,
getSeoSystemPrompt,
getPromptForIntentAudience as getPromptForAudienceIntent
} from './prompts'
import {
Heading,
PostOutline,
PostPrompt,
TotalTokens,
SeoInfo
} from '../types'
import { encode } from './tokenizer'
import { extractPrompts } from './template'
import { log } from 'console'
import { NoApiKeyError } from './errors'
dotenv.config()
const readFile = promisify(rd)
/**
* Specific Open AI API parameters for the completion
*/
export type CompletionParams = {
temperature?: number | null,
top_p?: number | null,
max_tokens?: number,
presence_penalty?: number | null,
frequency_penalty?: number | null,
logit_bias?: object | null,
}
/**
* Interface for the helper class for generating a post. it defines how to generate a post
* Each helper class must implement this interface
* @interface
*/
export interface GeneratorHelperInterface {
init () : Promise<void>
isCustom() : boolean
generateContentOutline () : Promise<PostOutline>
generateMainKeyword () : Promise<string[]>
generateIntroduction () : Promise<string>
generateConclusion () : Promise<string>
generateHeadingContents (tableOfContent : PostOutline) : Promise<string>
generateCustomPrompt(prompt : string) : Promise<string>
generateSeoInfo () : Promise<SeoInfo>
getTotalTokens() : TotalTokens
getPrompt() : PostPrompt
}
/**
* Helper implementation for generating a post using the ChatGPT API
* @class
*/
export class ChatGptHelper implements GeneratorHelperInterface {
private postPrompt : PostPrompt
private api : ChatGPTAPI
// The parent message is either the previous one in the conversation (if a template is used)
// or the generated outline (if we are in auto mode)
private chatParentMessage : ChatMessage
private completionParams : CompletionParams
private totalTokens : TotalTokens = {
promptTokens: 0,
completionTokens: 0,
total: 0
}
// -----------------------------------------------
// CONSTRUCTOR AND INITIALIZATION
// -----------------------------------------------
public constructor (postPrompt : PostPrompt) {
this.postPrompt = postPrompt
}
isCustom () : boolean {
return this.postPrompt?.templateFile !== undefined
}
getPrompt (): PostPrompt {
return this.postPrompt
}
getTotalTokens (): TotalTokens {
return this.totalTokens
}
async init () {
if (this.isCustom()) {
if (this.postPrompt.debug) {
console.log(`Use template : ${this.postPrompt.templateFile}`)
}
this.postPrompt.templateContent = await this.readTemplate()
this.postPrompt.prompts = extractPrompts(this.postPrompt.templateContent)
}
const systemMessage = this.isCustom() ? getCustomSystemPrompt(this.postPrompt) : getAutoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemMessage)
}
private async buildChatGPTAPI (systemMessage : string) {
try {
this.api = new ChatGPTAPI({
apiKey: this.postPrompt?.apiKey || process.env.OPENAI_API_KEY,
completionParams: {
model: this.postPrompt.model
},
systemMessage,
debug: this.postPrompt.debugapi
})
} catch (error) {
throw new NoApiKeyError()
}
if (this.postPrompt.debug) {
console.log(`OpenAI API initialized with model : ${this.postPrompt.model}`)
}
this.completionParams = {
temperature: this.postPrompt.temperature ?? 0.8,
frequency_penalty: this.postPrompt.frequencyPenalty ?? 0,
presence_penalty: this.postPrompt.presencePenalty ?? 1
}
if (this.postPrompt.logitBias) {
const mainKwWords = await this.generateMainKeyword()
// set the logit bias in order to force the model to minimize the usage of the main keyword
const logitBiais: Record<number, number> = {}
mainKwWords.forEach((kw) => {
| const encoded = encode(kw)
encoded.forEach((element) => { |
logitBiais[element] = Number(this.postPrompt.logitBias) || -1
})
})
this.completionParams.logit_bias = logitBiais
}
if (this.postPrompt.debug) {
console.log('---------- COMPLETION PARAMETERS ----------')
console.log('Max Tokens : ' + this.completionParams.max_tokens)
console.log('Temperature : ' + this.completionParams.temperature)
console.log('Frequency Penalty : ' + this.completionParams.frequency_penalty)
console.log('Presence Penalty : ' + this.completionParams.presence_penalty)
console.log('Logit Biais : ' + this.completionParams.logit_bias)
}
}
// -----------------------------------------------
// METHODS FOR THE AUTOMATIC MODE
// -----------------------------------------------
async generateMainKeyword () {
const prompt = getPromptForMainKeyword()
if (this.postPrompt.debug) {
console.log('---------- PROMPT MAIN KEYWORD ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- MAIN KEYWORD ----------')
console.log(response.text)
}
return extractJsonArray(response.text)
}
async generateContentOutline () {
if (this.postPrompt.generate) {
const audienceIntent = await this.generateAudienceIntent()
this.postPrompt = {
...audienceIntent,
...this.postPrompt
}
}
const prompt = getPromptForOutline(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT OUTLINE ----------')
console.log(prompt)
}
// the parent message is the outline for the upcoming content
// By this way, we can decrease the cost of the API call by minimizing the number of prompt tokens
// TODO : add an option to disable this feature
this.chatParentMessage = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- OUTLINE ----------')
console.log(this.chatParentMessage.text)
}
return extractPostOutlineFromCodeBlock(this.chatParentMessage.text)
}
async generateAudienceIntent () {
const prompt = getPromptForAudienceIntent(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT AUDIENCE INTENT ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- AUDIENCE INTENT ----------')
console.log(response.text)
}
return extractAudienceIntentInfo(response.text)
}
async generateIntroduction () {
const response = await this.sendRequest(getPromptForIntroduction(this.postPrompt), this.completionParams)
return extractCodeBlock(response.text)
}
async generateConclusion () {
const response = await this.sendRequest(getPromptForConclusion(), this.completionParams)
return extractCodeBlock(response.text)
}
async generateHeadingContents (postOutline : PostOutline) {
const headingLevel = 2
return await this.buildContent(postOutline.headings, headingLevel)
}
private async buildContent (headings: Heading[], headingLevel : number, previousContent: string = ''): Promise<string> {
if (headings.length === 0) {
return previousContent
}
const [currentHeading, ...remainingHeadings] = headings
const mdHeading = Array(headingLevel).fill('#').join('')
let content = previousContent + '\n' + mdHeading + ' ' + currentHeading.title
if (currentHeading.headings && currentHeading.headings.length > 0) {
content = await this.buildContent(currentHeading.headings, headingLevel + 1, content)
} else {
content += '\n' + await this.getContent(currentHeading)
}
return this.buildContent(remainingHeadings, headingLevel, content)
}
private async getContent (heading: Heading): Promise<string> {
if (this.postPrompt.debug) {
console.log(`\nHeading : ${heading.title} ...'\n`)
}
const response = await this.sendRequest(getPromptForHeading(this.postPrompt.tone, heading.title, heading.keywords), this.completionParams)
return `${extractCodeBlock(response.text)}\n`
}
// -----------------------------------------------
// METHODS FOR THE CUSTOM MODE base on a template
// -----------------------------------------------
/**
* Generate a content based on one of prompt defined in the template
* @param customPrompt : the prompt defined in the template
* @returns the AI answer
*/
async generateCustomPrompt (customPrompt : string) {
this.chatParentMessage = await this.sendRequest(customPrompt, this.completionParams)
return extractCodeBlock(this.chatParentMessage.text)
}
/**
* Generate the SEO info for the post based on the template
* @returns the SEO info
*/
async generateSeoInfo (): Promise<SeoInfo> {
const systemPrompt = getSeoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemPrompt)
this.chatParentMessage = await this.sendRequest(getPromptForSeoInfo(this.postPrompt), this.completionParams)
if (this.postPrompt.debug) {
log('---------- SEO INFO ----------')
console.log(this.chatParentMessage.text)
}
return extractSeoInfo(this.chatParentMessage.text)
}
private async readTemplate () : Promise<string> {
const templatePath = this.postPrompt.templateFile
return await readFile(templatePath, 'utf-8')
}
// -----------------------------------------------
// SEND REQUEST TO OPENAI API
// -----------------------------------------------
private async sendRequest (prompt : string, completionParams? : CompletionParams) {
return await pRetry(async () => {
const options : SendMessageOptions = { parentMessageId: this.chatParentMessage?.id }
if (completionParams) {
options.completionParams = completionParams
}
const response = await this.api.sendMessage(prompt, options)
this.totalTokens.promptTokens += response.detail.usage.prompt_tokens
this.totalTokens.completionTokens += response.detail.usage.completion_tokens
this.totalTokens.total += response.detail.usage.total_tokens
return response
}, {
retries: 10,
onFailedAttempt: async (error) => {
this.manageError(error)
}
})
}
private manageError (error: FailedAttemptError) {
if (this.postPrompt.debug) {
console.log('---------- OPENAI REQUEST ERROR ----------')
console.log(error)
}
if (error instanceof ChatGPTError) {
const chatGPTError = error as ChatGPTError
if (chatGPTError.statusCode === 401) {
console.log('OpenAI API Error : Invalid API key: please check your API key in the option -k or in the OPENAI_API_KEY env var.')
process.exit(1)
}
if (chatGPTError.statusCode === 404) {
console.log(`OpenAI API Error : Invalid model for your OpenAI subscription. Check if you can use : ${this.postPrompt.model}.`)
console.log(this.postPrompt.model === 'gpt-4' || this.postPrompt.model === 'gpt-4-32k' ? 'You need to join the waiting list to use the GPT-4 API : https://openai.com/waitlist/gpt-4-api' : '')
process.exit(1)
}
}
if (error instanceof AbortError) {
console.log(`OpenAI API - Request aborted. ${error.message}`)
} else {
console.log(`OpenAI API - Request failed - Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left. ${error.message}`)
}
}
}
| src/lib/post-helpers.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " language: 'english',\n tone: 'informative',\n withConclusion: true,\n temperature: 0.8,\n frequencyPenalty: 0,\n presencePenalty: 1,\n logitBias: 0\n }\n}\nfunction buildContent (options : Options, post : Post) {",
"score": 0.7862181663513184
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " ...options,\n ...answers,\n maxModelTokens: answers.model === 'gpt-4' ? 8000 : 4000\n }\n if (!postPrompt.topic) {\n throw new Error('The topic is mandatory, use the option -tp or --topic')\n }\n const postGenerator = new OpenAIPostGenerator(postPrompt)\n const post = await postGenerator.generate()\n const jsonData = {",
"score": 0.769019603729248
},
{
"filename": "src/post.ts",
"retrieved_chunk": " // We remove the first prompt because it is the system prompt\n const prompts = this.helper.getPrompt().prompts.slice(1)\n // for each prompt, we generate the content\n const templatePrompts = prompts.entries()\n for (const [index, prompt] of templatePrompts) {\n const content = await oraPromise(\n this.helper.generateCustomPrompt(prompt),\n {\n text: `Generating the prompt num. ${index + 1} ...`\n }",
"score": 0.7671258449554443
},
{
"filename": "src/lib/prompts.ts",
"retrieved_chunk": " return prompt\n}\nexport function getPromptForMainKeyword () {\n const prompt = 'Give me the most important SEO keyword in a JSON array in which each item matches a word without the stop words.'\n return prompt\n}\nexport function getPromptForIntroduction (postPrompt : PostPrompt) {\n return (!postPrompt.tone) || postPrompt.tone === 'informative' ? INFORMATIVE_INTRO_PROMPT : CAPTIVATING_INTO_PROMPT\n}\nexport function getPromptForHeading (tone : string, title : string, keywords : string[] | null) {",
"score": 0.7648569345474243
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " })\n}\nasync function generatePost (options: Options) {\n let answers : any = {}\n if (isInteractive(options)) {\n answers = isCustom(options) ? await askCustomQuestions() : await askQuestions()\n }\n const defaultPostPrompt = buildDefaultPostPrompt()\n const postPrompt : PostPrompt = {\n ...defaultPostPrompt,",
"score": 0.7559821009635925
}
] | typescript | const encoded = encode(kw)
encoded.forEach((element) => { |
import * as dotenv from 'dotenv'
import { readFile as rd } from 'fs'
import { promisify } from 'util'
import { ChatGPTAPI, ChatGPTError, ChatMessage, SendMessageOptions } from 'chatgpt'
import pRetry, { AbortError, FailedAttemptError } from 'p-retry'
import { extractJsonArray, extractCodeBlock, extractPostOutlineFromCodeBlock, extractSeoInfo, extractAudienceIntentInfo } from './extractor'
import {
getPromptForMainKeyword,
getPromptForOutline,
getPromptForIntroduction,
getPromptForHeading,
getPromptForConclusion,
getAutoSystemPrompt,
getPromptForSeoInfo,
getCustomSystemPrompt,
getSeoSystemPrompt,
getPromptForIntentAudience as getPromptForAudienceIntent
} from './prompts'
import {
Heading,
PostOutline,
PostPrompt,
TotalTokens,
SeoInfo
} from '../types'
import { encode } from './tokenizer'
import { extractPrompts } from './template'
import { log } from 'console'
import { NoApiKeyError } from './errors'
dotenv.config()
const readFile = promisify(rd)
/**
* Specific Open AI API parameters for the completion
*/
export type CompletionParams = {
temperature?: number | null,
top_p?: number | null,
max_tokens?: number,
presence_penalty?: number | null,
frequency_penalty?: number | null,
logit_bias?: object | null,
}
/**
* Interface for the helper class for generating a post. it defines how to generate a post
* Each helper class must implement this interface
* @interface
*/
export interface GeneratorHelperInterface {
init () : Promise<void>
isCustom() : boolean
generateContentOutline () : Promise<PostOutline>
generateMainKeyword () : Promise<string[]>
generateIntroduction () : Promise<string>
generateConclusion () : Promise<string>
generateHeadingContents (tableOfContent : PostOutline) : Promise<string>
generateCustomPrompt(prompt : string) : Promise<string>
generateSeoInfo () : Promise<SeoInfo>
getTotalTokens() : TotalTokens
getPrompt() : PostPrompt
}
/**
* Helper implementation for generating a post using the ChatGPT API
* @class
*/
export class ChatGptHelper implements GeneratorHelperInterface {
private postPrompt : PostPrompt
private api : ChatGPTAPI
// The parent message is either the previous one in the conversation (if a template is used)
// or the generated outline (if we are in auto mode)
private chatParentMessage : ChatMessage
private completionParams : CompletionParams
private totalTokens : TotalTokens = {
promptTokens: 0,
completionTokens: 0,
total: 0
}
// -----------------------------------------------
// CONSTRUCTOR AND INITIALIZATION
// -----------------------------------------------
public constructor (postPrompt : PostPrompt) {
this.postPrompt = postPrompt
}
isCustom () : boolean {
return this.postPrompt?.templateFile !== undefined
}
getPrompt (): PostPrompt {
return this.postPrompt
}
getTotalTokens (): TotalTokens {
return this.totalTokens
}
async init () {
if (this.isCustom()) {
if (this.postPrompt.debug) {
console.log(`Use template : ${this.postPrompt.templateFile}`)
}
this.postPrompt.templateContent = await this.readTemplate()
this.postPrompt.prompts = extractPrompts(this.postPrompt.templateContent)
}
const systemMessage = this.isCustom() ? getCustomSystemPrompt(this.postPrompt) : getAutoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemMessage)
}
private async buildChatGPTAPI (systemMessage : string) {
try {
this.api = new ChatGPTAPI({
apiKey: this.postPrompt?.apiKey || process.env.OPENAI_API_KEY,
completionParams: {
model: this.postPrompt.model
},
systemMessage,
debug: this.postPrompt.debugapi
})
} catch (error) {
throw new NoApiKeyError()
}
if (this.postPrompt.debug) {
console.log(`OpenAI API initialized with model : ${this.postPrompt.model}`)
}
this.completionParams = {
temperature: this.postPrompt.temperature ?? 0.8,
frequency_penalty: this.postPrompt.frequencyPenalty ?? 0,
presence_penalty: this.postPrompt.presencePenalty ?? 1
}
if (this.postPrompt.logitBias) {
const mainKwWords = await this.generateMainKeyword()
// set the logit bias in order to force the model to minimize the usage of the main keyword
const logitBiais: Record<number, number> = {}
mainKwWords.forEach((kw) => {
const encoded = encode(kw)
encoded.forEach((element) => {
logitBiais[element] = Number(this.postPrompt.logitBias) || -1
})
})
this.completionParams.logit_bias = logitBiais
}
if (this.postPrompt.debug) {
console.log('---------- COMPLETION PARAMETERS ----------')
console.log('Max Tokens : ' + this.completionParams.max_tokens)
console.log('Temperature : ' + this.completionParams.temperature)
console.log('Frequency Penalty : ' + this.completionParams.frequency_penalty)
console.log('Presence Penalty : ' + this.completionParams.presence_penalty)
console.log('Logit Biais : ' + this.completionParams.logit_bias)
}
}
// -----------------------------------------------
// METHODS FOR THE AUTOMATIC MODE
// -----------------------------------------------
async generateMainKeyword () {
const prompt = getPromptForMainKeyword()
if (this.postPrompt.debug) {
console.log('---------- PROMPT MAIN KEYWORD ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- MAIN KEYWORD ----------')
console.log(response.text)
}
return extractJsonArray(response.text)
}
async generateContentOutline () {
if (this.postPrompt.generate) {
const audienceIntent = await this.generateAudienceIntent()
this.postPrompt = {
...audienceIntent,
...this.postPrompt
}
}
const prompt = getPromptForOutline(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT OUTLINE ----------')
console.log(prompt)
}
// the parent message is the outline for the upcoming content
// By this way, we can decrease the cost of the API call by minimizing the number of prompt tokens
// TODO : add an option to disable this feature
this.chatParentMessage = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- OUTLINE ----------')
console.log(this.chatParentMessage.text)
}
return extractPostOutlineFromCodeBlock(this.chatParentMessage.text)
}
async generateAudienceIntent () {
const prompt = getPromptForAudienceIntent(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT AUDIENCE INTENT ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- AUDIENCE INTENT ----------')
console.log(response.text)
}
return extractAudienceIntentInfo(response.text)
}
async generateIntroduction () {
const response = await this.sendRequest(getPromptForIntroduction(this.postPrompt), this.completionParams)
return extractCodeBlock(response.text)
}
async generateConclusion () {
const response = await this.sendRequest(getPromptForConclusion(), this.completionParams)
return extractCodeBlock(response.text)
}
async generateHeadingContents (postOutline : PostOutline) {
const headingLevel = 2
return await this.buildContent(postOutline.headings, headingLevel)
}
private async buildContent (headings: Heading[], headingLevel : number, previousContent: string = ''): Promise<string> {
if (headings.length === 0) {
return previousContent
}
const [currentHeading, ...remainingHeadings] = headings
const mdHeading = Array(headingLevel).fill('#').join('')
let content = previousContent + '\n' + mdHeading + ' ' + currentHeading.title
if (currentHeading.headings && currentHeading.headings.length > 0) {
content = await this.buildContent(currentHeading.headings, headingLevel + 1, content)
} else {
content += '\n' + await this.getContent(currentHeading)
}
return this.buildContent(remainingHeadings, headingLevel, content)
}
private async getContent (heading: Heading): Promise<string> {
if (this.postPrompt.debug) {
console.log(`\nHeading : ${heading.title} ...'\n`)
}
const response = await this.sendRequest(getPromptForHeading(this.postPrompt.tone, heading.title, heading.keywords), this.completionParams)
return `${extractCodeBlock(response.text)}\n`
}
// -----------------------------------------------
// METHODS FOR THE CUSTOM MODE base on a template
// -----------------------------------------------
/**
* Generate a content based on one of prompt defined in the template
* @param customPrompt : the prompt defined in the template
* @returns the AI answer
*/
async generateCustomPrompt (customPrompt : string) {
this.chatParentMessage = await this.sendRequest(customPrompt, this.completionParams)
return extractCodeBlock(this.chatParentMessage.text)
}
/**
* Generate the SEO info for the post based on the template
* @returns the SEO info
*/
async generateSeoInfo (): Promise<SeoInfo> {
const systemPrompt = getSeoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemPrompt)
this.chatParentMessage = await this.sendRequest(getPromptForSeoInfo(this.postPrompt), this.completionParams)
if (this.postPrompt.debug) {
log('---------- SEO INFO ----------')
console.log(this.chatParentMessage.text)
}
| return extractSeoInfo(this.chatParentMessage.text)
} |
private async readTemplate () : Promise<string> {
const templatePath = this.postPrompt.templateFile
return await readFile(templatePath, 'utf-8')
}
// -----------------------------------------------
// SEND REQUEST TO OPENAI API
// -----------------------------------------------
private async sendRequest (prompt : string, completionParams? : CompletionParams) {
return await pRetry(async () => {
const options : SendMessageOptions = { parentMessageId: this.chatParentMessage?.id }
if (completionParams) {
options.completionParams = completionParams
}
const response = await this.api.sendMessage(prompt, options)
this.totalTokens.promptTokens += response.detail.usage.prompt_tokens
this.totalTokens.completionTokens += response.detail.usage.completion_tokens
this.totalTokens.total += response.detail.usage.total_tokens
return response
}, {
retries: 10,
onFailedAttempt: async (error) => {
this.manageError(error)
}
})
}
private manageError (error: FailedAttemptError) {
if (this.postPrompt.debug) {
console.log('---------- OPENAI REQUEST ERROR ----------')
console.log(error)
}
if (error instanceof ChatGPTError) {
const chatGPTError = error as ChatGPTError
if (chatGPTError.statusCode === 401) {
console.log('OpenAI API Error : Invalid API key: please check your API key in the option -k or in the OPENAI_API_KEY env var.')
process.exit(1)
}
if (chatGPTError.statusCode === 404) {
console.log(`OpenAI API Error : Invalid model for your OpenAI subscription. Check if you can use : ${this.postPrompt.model}.`)
console.log(this.postPrompt.model === 'gpt-4' || this.postPrompt.model === 'gpt-4-32k' ? 'You need to join the waiting list to use the GPT-4 API : https://openai.com/waitlist/gpt-4-api' : '')
process.exit(1)
}
}
if (error instanceof AbortError) {
console.log(`OpenAI API - Request aborted. ${error.message}`)
} else {
console.log(`OpenAI API - Request failed - Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left. ${error.message}`)
}
}
}
| src/lib/post-helpers.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/post.ts",
"retrieved_chunk": " )\n promptContents.push(content)\n }\n // We replace the prompts by the AI answer in the template content\n const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)\n const seoInfo = await oraPromise(\n this.helper.generateSeoInfo(),\n {\n text: 'Generating SEO info ...'\n }",
"score": 0.8138747215270996
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " })\n}\nasync function generatePost (options: Options) {\n let answers : any = {}\n if (isInteractive(options)) {\n answers = isCustom(options) ? await askCustomQuestions() : await askQuestions()\n }\n const defaultPostPrompt = buildDefaultPostPrompt()\n const postPrompt : PostPrompt = {\n ...defaultPostPrompt,",
"score": 0.7527537941932678
},
{
"filename": "src/post.ts",
"retrieved_chunk": " }\n )\n content += await oraPromise(\n this.helper.generateHeadingContents(tableOfContent),\n {\n text: 'Generating content ...'\n }\n )\n if (this.helper.getPrompt().withConclusion) {\n content += await oraPromise(",
"score": 0.7439266443252563
},
{
"filename": "src/lib/prompts.ts",
"retrieved_chunk": "// ------------------------------------------------------\nexport function getCustomSystemPrompt (postPrompt : PostPrompt) {\n // The prompt with the index 0 in the template is the system prompt\n return postPrompt.prompts[0] + '\\n' + ' Language: ' + postPrompt.language + '. '\n}\nexport function getSeoSystemPrompt (postPrompt : PostPrompt) {\n return 'You are a SEO expert and you need to optimize a web page based on the following info in ' + postPrompt.language + ': ' +\n '\\n' + postPrompt.prompts[0]\n}\nexport function getPromptForSeoInfo (postPrompt : PostPrompt) {",
"score": 0.737547755241394
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " ...options,\n ...answers,\n maxModelTokens: answers.model === 'gpt-4' ? 8000 : 4000\n }\n if (!postPrompt.topic) {\n throw new Error('The topic is mandatory, use the option -tp or --topic')\n }\n const postGenerator = new OpenAIPostGenerator(postPrompt)\n const post = await postGenerator.generate()\n const jsonData = {",
"score": 0.7299261093139648
}
] | typescript | return extractSeoInfo(this.chatParentMessage.text)
} |
import {
Body,
Controller,
Delete,
Get,
Logger,
Param,
Post,
Put,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { TodoListService } from './todolist.service';
import TodoList from '../models/todolist/todolist';
import Task from '../models/task/task';
@Controller('todolist')
export class TodoListController {
constructor(private readonly appService: TodoListService) {}
@Post()
@UsePipes(new ValidationPipe())
createTodoList(@Body() list: TodoList): TodoList {
try {
const id = this.appService.AddList(list);
return this.appService.GetList(id);
} catch (error) {
Logger.error(error);
}
}
@Get(':id')
getTodoList(@Param('id') listId: string): TodoList {
return this.appService.GetList(listId);
}
@Delete(':id')
@UsePipes(new ValidationPipe())
deleteList(@Param('id') listId: string): string {
this.appService.RemoveList(listId);
return 'done';
}
@Put(':id')
@UsePipes(new ValidationPipe())
updateList(
@Param('id') listId: string,
@Body('Name') newName: string,
): TodoList {
this.appService.UpdateListName(listId, newName);
return this.appService.GetList(listId);
}
@Post(':id/task')
@UsePipes(new ValidationPipe())
| createTask(@Body() task: Task, @Param('id') listId: string): string { |
const id = this.appService.AddTask(listId, task);
return id;
}
}
| src/todolist/todolist.controller.ts | nitzan8897-TodoListNestJS-72123e7 | [
{
"filename": "src/models/task/task.ts",
"retrieved_chunk": " doneStatus: boolean;\n @IsString()\n @IsNotEmpty()\n description: string;\n @ManyToOne(() => TodoList, (todoList) => todoList.Tasks)\n todoList: TodoList;\n}",
"score": 0.764650285243988
},
{
"filename": "src/todolist/todolist.service.ts",
"retrieved_chunk": " delete this.RAMMemory[listId];\n }\n GetList(listId: string): TodoList | undefined {\n listIdValidation(this.RAMMemory, listId);\n return this.RAMMemory[listId];\n }\n UpdateListName(listId: string, listNewName: string): void {\n listIdValidation(this.RAMMemory, listId);\n this.RAMMemory[listId].Name = listNewName;\n }",
"score": 0.7481668591499329
},
{
"filename": "src/models/todolist/todolist-actions.module.ts",
"retrieved_chunk": "import IList from \"./todolist.module\";\nexport default interface ITodoListActions {\n AddList(list: IList): string;\n RemoveList(listId: string): void;\n GetList(listId: string): IList | undefined;\n UpdateListName(listId: string, listNewName: string): void;\n}",
"score": 0.7266733646392822
},
{
"filename": "src/todolist/todolist.service.ts",
"retrieved_chunk": " AddTask(listId: string, task: Task): string {\n listIdValidation(this.RAMMemory, listId);\n const taskId = uuidv4();\n task.taskId = taskId;\n this.RAMMemory[listId].Tasks.push(task);\n Logger.log(`Added new Task, ${task.description} to the list: ${listId}`);\n return taskId;\n }\n}",
"score": 0.7239487171173096
},
{
"filename": "src/todolist/todolist.service.ts",
"retrieved_chunk": " AddList(list: IList): string {\n const listId = uuidv4();\n this.RAMMemory[listId] = { Name: list.Name, Id: listId, Tasks: [] };\n Logger.log(\n `Added new list, listName: ${this.RAMMemory[listId].Name}, listId: ${listId}`,\n );\n return listId;\n }\n RemoveList(listId: string): void {\n listIdValidation(this.RAMMemory, listId);",
"score": 0.7044152617454529
}
] | typescript | createTask(@Body() task: Task, @Param('id') listId: string): string { |
import crowdin, {
Credentials,
Translations,
} from "@crowdin/crowdin-api-client";
import { payloadCrowdinSyncFilesApi } from "./files";
import { mockCrowdinClient } from "../mock/crowdin-client";
import { Payload } from "payload";
import { PluginOptions } from "../../types";
import deepEqual from "deep-equal";
import {
CollectionConfig,
GlobalConfig,
SanitizedCollectionConfig,
SanitizedGlobalConfig,
} from "payload/types";
import { htmlToSlate, payloadHtmlToSlateConfig } from "slate-serializers";
import {
getLocalizedFields,
getFieldSlugs,
buildCrowdinJsonObject,
buildCrowdinHtmlObject,
buildPayloadUpdateObject,
getLocalizedRequiredFields,
} from "../../utilities";
interface IgetLatestDocumentTranslation {
collection: string;
doc: any;
locale: string;
global?: boolean;
}
interface IgetCurrentDocumentTranslation {
doc: any;
collection: string;
locale: string;
global?: boolean;
}
interface IgetTranslation {
documentId: string;
fieldName: string;
locale: string;
global?: boolean;
}
interface IupdateTranslation {
documentId: string;
collection: string;
dryRun?: boolean;
global?: boolean;
excludeLocales?: string[];
}
export class payloadCrowdinSyncTranslationsApi {
translationsApi: Translations;
filesApi: payloadCrowdinSyncFilesApi; // our wrapper for file operations
projectId: number;
directoryId?: number;
payload: Payload;
localeMap: PluginOptions["localeMap"];
sourceLocale: PluginOptions["sourceLocale"];
constructor(pluginOptions: PluginOptions, payload: Payload) {
// credentials
const credentials: Credentials = {
token: pluginOptions.token,
};
const { translationsApi } = new crowdin(credentials);
this.projectId = pluginOptions.projectId;
this.directoryId = pluginOptions.directoryId;
this.translationsApi =
process.env.NODE_ENV === "test"
? (mockCrowdinClient(pluginOptions) as any)
: translationsApi;
this.filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, payload);
this.payload = payload;
this.localeMap = pluginOptions.localeMap;
this.sourceLocale = pluginOptions.sourceLocale;
}
async updateTranslation({
documentId,
collection,
dryRun = true,
global = false,
excludeLocales = [],
}: IupdateTranslation) {
/**
* Get existing document
*
* * check document exists
* * check for `meta` field (which can be added by @payloadcms/seo)
*
*/
let doc: { crowdinArticleDirectory: { id: any } };
if (global) {
doc = await this.payload.findGlobal({
slug: collection,
locale: this.sourceLocale,
});
} else {
doc = await this.payload.findByID({
collection: collection,
id: documentId,
locale: this.sourceLocale,
});
}
const report: { [key: string]: any } = {};
for (const locale of Object.keys(this.localeMap)) {
if (excludeLocales.includes(locale)) {
continue;
}
report[locale] = {};
report[locale].currentTranslations =
await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
report[locale].latestTranslations =
await this.getLatestDocumentTranslation({
collection: collection,
doc: doc,
locale: locale,
global,
});
report[locale].changed = !deepEqual(
report[locale].currentTranslations,
report[locale].latestTranslations
);
if (report[locale].changed && !dryRun) {
if (global) {
try {
await this.payload.updateGlobal({
slug: collection,
locale: locale,
data: {
...report[locale].latestTranslations,
// error on update without the following line.
// see https://github.com/thompsonsj/payload-crowdin-sync/pull/13/files#r1209271660
crowdinArticleDirectory: doc.crowdinArticleDirectory.id,
},
});
} catch (error) {
console.log(error);
}
} else {
try {
await this.payload.update({
collection: collection,
locale: locale,
id: documentId,
data: report[locale].latestTranslations,
});
} catch (error) {
console.log(error);
}
}
}
}
return {
source: doc,
translations: { ...report },
};
}
getCollectionConfig(
collection: string,
global: boolean
): CollectionConfig | GlobalConfig {
let collectionConfig:
| SanitizedGlobalConfig
| SanitizedCollectionConfig
| undefined;
if (global) {
collectionConfig = this.payload.config.globals.find(
(col: GlobalConfig) => col.slug === collection
);
} else {
collectionConfig = this.payload.config.collections.find(
(col: CollectionConfig) => col.slug === collection
);
}
if (!collectionConfig)
throw new Error(`Collection ${collection} not found in payload config`);
return collectionConfig;
}
async getCurrentDocumentTranslation({
doc,
collection,
locale,
global = false,
}: IgetCurrentDocumentTranslation) {
// get document
let document: any;
if (global) {
document = await this.payload.findGlobal({
slug: collection,
locale: locale,
});
} else {
document = await this.payload.findByID({
collection: collection,
id: doc.id,
locale: locale,
});
}
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
// build crowdin json object
const crowdinJsonObject = buildCrowdinJsonObject({
doc: document,
fields: localizedFields,
});
const crowdinHtmlObject = buildCrowdinHtmlObject({
doc: document,
fields: localizedFields,
});
try {
const docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document,
});
return docTranslations;
} catch (error) {
console.log(error);
throw new Error(`${error}`);
}
}
/**
* Retrieve translations from Crowdin for a document in a given locale
*/
async getLatestDocumentTranslation({
collection,
doc,
locale,
global = false,
}: IgetLatestDocumentTranslation) {
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
if (!localizedFields) {
return { message: "no localized fields" };
}
let docTranslations: { [key: string]: any } = {};
// add json fields
const crowdinJsonObject =
(await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: "fields",
locale: locale,
})) || {};
// add html fields
const localizedHtmlFields = await this.getHtmlFieldSlugs(
global ? collectionConfig.slug : doc.id
);
let crowdinHtmlObject: { [key: string]: any } = {};
for (const field of localizedHtmlFields) {
crowdinHtmlObject[field] = await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: field,
locale: locale,
});
}
docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document: doc,
});
// Add required fields if not present
const requiredFieldSlugs = getFieldSlugs(
getLocalizedRequiredFields(collectionConfig)
);
if (requiredFieldSlugs.length > 0) {
const currentTranslations = await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
requiredFieldSlugs.forEach((slug) => {
if (!docTranslations.hasOwnProperty(slug)) {
docTranslations[slug] = currentTranslations[slug];
}
});
}
return docTranslations;
}
async getHtmlFieldSlugs(documentId: string) {
const files = await this.filesApi.getFilesByDocumentID(documentId);
return files
.filter((file: any) => file.type === "html")
.map((file: any) => file.field);
}
/**
* Retrieve translations for a document field name
*
* * returns Slate object for html fields
* * returns all json fields if fieldName is 'fields'
*/
async getTranslation({ documentId, fieldName, locale }: IgetTranslation) {
const articleDirectory = await this.filesApi.getArticleDirectory(
documentId
);
| const file = await this.filesApi.getFile(fieldName, articleDirectory.id); |
// it is possible a file doesn't exist yet - e.g. an article with localized text fields that contains an empty html field.
if (!file) {
return;
}
try {
const response = await this.translationsApi.buildProjectFileTranslation(
this.projectId,
file.originalId,
{
targetLanguageId: this.localeMap[locale].crowdinId,
}
);
const data = await this.getFileDataFromUrl(response.data.url);
return file.type === "html"
? htmlToSlate(data, payloadHtmlToSlateConfig)
: JSON.parse(data);
} catch (error) {
console.log(error);
}
}
private async getFileDataFromUrl(url: string) {
const response = await fetch(url);
const body = await response.text();
return body;
}
/**
* Restore id and blockType to translations
*
* In order to update a document, we need to know the id and blockType of each block.
*
* Ideally, id and blockType are not sent to Crowdin - hence
* we need to restore them from the original document.
*
* This currently only works for a top-level `layout` blocks field.
*
* TODO: make this work for nested blocks.
*/
restoreIdAndBlockType = (
document: any,
translations: any,
key: string = "layout"
) => {
if (translations.hasOwnProperty(key)) {
translations[key] = translations[key].map(
(block: any, index: number) => ({
...block,
id: document[key][index].id,
blockType: document[key][index].blockType,
})
);
}
return translations;
};
}
| src/api/payload-crowdin-sync/translations.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/helpers.ts",
"retrieved_chunk": " return getFile(name, articleDirectory.id, payload);\n}\nexport async function getFilesByDocumentID(\n documentId: string,\n payload: Payload\n): Promise<IcrowdinFile[]> {\n const articleDirectory = await getArticleDirectory(documentId, payload);\n if (!articleDirectory) {\n // tests call this function to make sure files are deleted\n return [];",
"score": 0.8871794939041138
},
{
"filename": "src/hooks/collections/afterChange.ts",
"retrieved_chunk": " */\n const filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, req.payload);\n /**\n * Retrieve the Crowdin Article Directory article\n *\n * Records of Crowdin directories are stored in Payload.\n */\n const articleDirectory = await filesApi.findOrCreateArticleDirectory({\n document: doc,\n collectionSlug: collection.slug,",
"score": 0.8814769387245178
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " console.error(error, options);\n }\n }\n async getArticleDirectory(documentId: string) {\n const result = await getArticleDirectory(documentId, this.payload);\n return result;\n }\n async deleteFilesAndDirectory(documentId: string) {\n const files = await this.getFilesByDocumentID(documentId);\n for (const file of files) {",
"score": 0.8787026405334473
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " // Create file on Crowdin\n const crowdinFile = await this.crowdinCreateFile({\n directoryId: articleDirectory.originalId,\n name: name,\n fileData: value,\n fileType: fileType,\n });\n // createFile has been intermittent in not being available\n // perhaps logic goes wrong somewhere and express middleware\n // is hard to debug?",
"score": 0.8616490364074707
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": "): any[] => {\n const fields = getLocalizedFields({ fields: collection.fields, type });\n return fields.filter((field) => field.required);\n};\n/**\n * Not yet compatible with nested fields - this means nested HTML\n * field translations cannot be synced from Crowdin.\n */\nexport const getFieldSlugs = (fields: FieldWithName[]): string[] =>\n fields",
"score": 0.8602505326271057
}
] | typescript | const file = await this.filesApi.getFile(fieldName, articleDirectory.id); |
import { oraPromise } from 'ora'
import { ChatGptHelper, GeneratorHelperInterface } from './lib/post-helpers'
import {
PostPrompt,
Post
} from './types'
import { replaceAllPrompts } from './lib/template'
/**
* Class for generating a post. It need a helper class to generate the post
* Each helper class must implement the GeneratorHelperInterface
*/
export class PostGenerator {
private helper : GeneratorHelperInterface
public constructor (helper : GeneratorHelperInterface) {
this.helper = helper
}
public async generate () : Promise<Post> {
return this.helper.isCustom() ? await this.customGenerate() : await this.autoGenerate()
}
/**
* Generate a post using the custom prompt based on a template
*/
private async customGenerate () : Promise<Post> {
const promptContents = []
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
// We remove the first prompt because it is the system prompt
const prompts = this.helper.getPrompt().prompts.slice(1)
// for each prompt, we generate the content
const templatePrompts = prompts.entries()
for (const [index, prompt] of templatePrompts) {
const content = await oraPromise(
this.helper.generateCustomPrompt(prompt),
{
text: `Generating the prompt num. ${index + 1} ...`
}
)
promptContents.push(content)
}
// We replace the prompts by the AI answer in the template content
const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)
const seoInfo = await oraPromise(
this.helper.generateSeoInfo(),
{
text: 'Generating SEO info ...'
}
)
return {
title: seoInfo.h1,
slug: seoInfo.slug,
seoTitle: | seoInfo.seoTitle,
seoDescription: seoInfo.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
} |
}
/**
* Generate a post using the auto mode
*/
private async autoGenerate () : Promise<Post> {
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
const tableOfContent = await oraPromise(
this.helper.generateContentOutline(),
{
text: 'Generating post outline ...'
}
)
let content = await oraPromise(
this.helper.generateIntroduction(),
{
text: 'Generating introduction...'
}
)
content += await oraPromise(
this.helper.generateHeadingContents(tableOfContent),
{
text: 'Generating content ...'
}
)
if (this.helper.getPrompt().withConclusion) {
content += await oraPromise(
this.helper.generateConclusion(),
{
text: 'Generating conclusion...'
}
)
}
return {
title: tableOfContent.title,
slug: tableOfContent.slug,
seoTitle: tableOfContent.seoTitle,
seoDescription: tableOfContent.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
}
}
}
/**
* Class for generating a post using the OpenAI API
*/
export class OpenAIPostGenerator extends PostGenerator {
public constructor (postPrompt : PostPrompt) {
super(new ChatGptHelper(postPrompt))
}
}
| src/post.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/wp/wp-api.ts",
"retrieved_chunk": " if (response.data.length === 0) {\n throw new Error(`Post with ${slug} not found`)\n }\n const postId: number = response.data[0].id\n const updatedPost : UpdatePost = {\n content: newContent.content,\n title: newContent.title,\n meta: {\n yoast_wpseo_title: newContent.seoTitle,\n yoast_wpseo_metadesc: newContent.seoDescription",
"score": 0.7675725221633911
},
{
"filename": "src/types.ts",
"retrieved_chunk": "}\nexport type SeoInfo = {\n h1 : string\n slug : string\n seoTitle : string\n seoDescription : string\n}\nexport type AudienceIntentInfo = {\n audience : string\n intent : string",
"score": 0.7556467652320862
},
{
"filename": "src/types.ts",
"retrieved_chunk": "}\nexport type Post = {\n title : string\n content : string\n seoTitle : string\n seoDescription : string\n slug : string,\n categories? : number[],\n status? : string,\n totalTokens : TotalTokens",
"score": 0.7356804013252258
},
{
"filename": "src/lib/extractor.ts",
"retrieved_chunk": " },\n slug: {\n type: 'string'\n },\n seoTitle: {\n type: 'string'\n },\n seoDescription: {\n type: 'string'\n }",
"score": 0.7267615795135498
},
{
"filename": "src/types.ts",
"retrieved_chunk": " title: string\n keywords?: string[]\n headings?: Heading[]\n}\nexport type PostOutline = {\n title: string\n headings : Heading[],\n slug : string,\n seoTitle : string,\n seoDescription : string",
"score": 0.7218492031097412
}
] | typescript | seoInfo.seoTitle,
seoDescription: seoInfo.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
} |
import crowdin, {
Credentials,
Translations,
} from "@crowdin/crowdin-api-client";
import { payloadCrowdinSyncFilesApi } from "./files";
import { mockCrowdinClient } from "../mock/crowdin-client";
import { Payload } from "payload";
import { PluginOptions } from "../../types";
import deepEqual from "deep-equal";
import {
CollectionConfig,
GlobalConfig,
SanitizedCollectionConfig,
SanitizedGlobalConfig,
} from "payload/types";
import { htmlToSlate, payloadHtmlToSlateConfig } from "slate-serializers";
import {
getLocalizedFields,
getFieldSlugs,
buildCrowdinJsonObject,
buildCrowdinHtmlObject,
buildPayloadUpdateObject,
getLocalizedRequiredFields,
} from "../../utilities";
interface IgetLatestDocumentTranslation {
collection: string;
doc: any;
locale: string;
global?: boolean;
}
interface IgetCurrentDocumentTranslation {
doc: any;
collection: string;
locale: string;
global?: boolean;
}
interface IgetTranslation {
documentId: string;
fieldName: string;
locale: string;
global?: boolean;
}
interface IupdateTranslation {
documentId: string;
collection: string;
dryRun?: boolean;
global?: boolean;
excludeLocales?: string[];
}
export class payloadCrowdinSyncTranslationsApi {
translationsApi: Translations;
filesApi: payloadCrowdinSyncFilesApi; // our wrapper for file operations
projectId: number;
directoryId?: number;
payload: Payload;
localeMap: PluginOptions["localeMap"];
sourceLocale: PluginOptions["sourceLocale"];
constructor(pluginOptions: PluginOptions, payload: Payload) {
// credentials
const credentials: Credentials = {
token: pluginOptions.token,
};
const { translationsApi } = new crowdin(credentials);
this.projectId = pluginOptions.projectId;
this.directoryId = pluginOptions.directoryId;
this.translationsApi =
process.env.NODE_ENV === "test"
? (mockCrowdinClient(pluginOptions) as any)
: translationsApi;
this.filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, payload);
this.payload = payload;
this.localeMap = pluginOptions.localeMap;
this.sourceLocale = pluginOptions.sourceLocale;
}
async updateTranslation({
documentId,
collection,
dryRun = true,
global = false,
excludeLocales = [],
}: IupdateTranslation) {
/**
* Get existing document
*
* * check document exists
* * check for `meta` field (which can be added by @payloadcms/seo)
*
*/
let doc: { crowdinArticleDirectory: { id: any } };
if (global) {
doc = await this.payload.findGlobal({
slug: collection,
locale: this.sourceLocale,
});
} else {
doc = await this.payload.findByID({
collection: collection,
id: documentId,
locale: this.sourceLocale,
});
}
const report: { [key: string]: any } = {};
for (const locale of Object.keys(this.localeMap)) {
if (excludeLocales.includes(locale)) {
continue;
}
report[locale] = {};
report[locale].currentTranslations =
await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
report[locale].latestTranslations =
await this.getLatestDocumentTranslation({
collection: collection,
doc: doc,
locale: locale,
global,
});
report[locale].changed = !deepEqual(
report[locale].currentTranslations,
report[locale].latestTranslations
);
if (report[locale].changed && !dryRun) {
if (global) {
try {
await this.payload.updateGlobal({
slug: collection,
locale: locale,
data: {
...report[locale].latestTranslations,
// error on update without the following line.
// see https://github.com/thompsonsj/payload-crowdin-sync/pull/13/files#r1209271660
crowdinArticleDirectory: doc.crowdinArticleDirectory.id,
},
});
} catch (error) {
console.log(error);
}
} else {
try {
await this.payload.update({
collection: collection,
locale: locale,
id: documentId,
data: report[locale].latestTranslations,
});
} catch (error) {
console.log(error);
}
}
}
}
return {
source: doc,
translations: { ...report },
};
}
getCollectionConfig(
collection: string,
global: boolean
): CollectionConfig | GlobalConfig {
let collectionConfig:
| SanitizedGlobalConfig
| SanitizedCollectionConfig
| undefined;
if (global) {
collectionConfig = this.payload.config.globals.find(
(col: GlobalConfig) => col.slug === collection
);
} else {
collectionConfig = this.payload.config.collections.find(
(col: CollectionConfig) => col.slug === collection
);
}
if (!collectionConfig)
throw new Error(`Collection ${collection} not found in payload config`);
return collectionConfig;
}
async getCurrentDocumentTranslation({
doc,
collection,
locale,
global = false,
}: IgetCurrentDocumentTranslation) {
// get document
let document: any;
if (global) {
document = await this.payload.findGlobal({
slug: collection,
locale: locale,
});
} else {
document = await this.payload.findByID({
collection: collection,
id: doc.id,
locale: locale,
});
}
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
// build crowdin json object
const crowdinJsonObject = buildCrowdinJsonObject({
doc: document,
fields: localizedFields,
});
const crowdinHtmlObject = buildCrowdinHtmlObject({
doc: document,
fields: localizedFields,
});
try {
const docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document,
});
return docTranslations;
} catch (error) {
console.log(error);
throw new Error(`${error}`);
}
}
/**
* Retrieve translations from Crowdin for a document in a given locale
*/
async getLatestDocumentTranslation({
collection,
doc,
locale,
global = false,
}: IgetLatestDocumentTranslation) {
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
if (!localizedFields) {
return { message: "no localized fields" };
}
let docTranslations: { [key: string]: any } = {};
// add json fields
const crowdinJsonObject =
(await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: "fields",
locale: locale,
})) || {};
// add html fields
const localizedHtmlFields = await this.getHtmlFieldSlugs(
global ? collectionConfig.slug : doc.id
);
let crowdinHtmlObject: { [key: string]: any } = {};
for (const field of localizedHtmlFields) {
crowdinHtmlObject[field] = await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: field,
locale: locale,
});
}
docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document: doc,
});
// Add required fields if not present
const requiredFieldSlugs = getFieldSlugs(
getLocalizedRequiredFields(collectionConfig)
);
if (requiredFieldSlugs.length > 0) {
const currentTranslations = await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
requiredFieldSlugs.forEach((slug) => {
if (!docTranslations.hasOwnProperty(slug)) {
docTranslations[slug] = currentTranslations[slug];
}
});
}
return docTranslations;
}
async getHtmlFieldSlugs(documentId: string) {
| const files = await this.filesApi.getFilesByDocumentID(documentId); |
return files
.filter((file: any) => file.type === "html")
.map((file: any) => file.field);
}
/**
* Retrieve translations for a document field name
*
* * returns Slate object for html fields
* * returns all json fields if fieldName is 'fields'
*/
async getTranslation({ documentId, fieldName, locale }: IgetTranslation) {
const articleDirectory = await this.filesApi.getArticleDirectory(
documentId
);
const file = await this.filesApi.getFile(fieldName, articleDirectory.id);
// it is possible a file doesn't exist yet - e.g. an article with localized text fields that contains an empty html field.
if (!file) {
return;
}
try {
const response = await this.translationsApi.buildProjectFileTranslation(
this.projectId,
file.originalId,
{
targetLanguageId: this.localeMap[locale].crowdinId,
}
);
const data = await this.getFileDataFromUrl(response.data.url);
return file.type === "html"
? htmlToSlate(data, payloadHtmlToSlateConfig)
: JSON.parse(data);
} catch (error) {
console.log(error);
}
}
private async getFileDataFromUrl(url: string) {
const response = await fetch(url);
const body = await response.text();
return body;
}
/**
* Restore id and blockType to translations
*
* In order to update a document, we need to know the id and blockType of each block.
*
* Ideally, id and blockType are not sent to Crowdin - hence
* we need to restore them from the original document.
*
* This currently only works for a top-level `layout` blocks field.
*
* TODO: make this work for nested blocks.
*/
restoreIdAndBlockType = (
document: any,
translations: any,
key: string = "layout"
) => {
if (translations.hasOwnProperty(key)) {
translations[key] = translations[key].map(
(block: any, index: number) => ({
...block,
id: document[key][index].id,
blockType: document[key][index].blockType,
})
);
}
return translations;
};
}
| src/api/payload-crowdin-sync/translations.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/endpoints/globals/reviewFields.ts",
"retrieved_chunk": " req.payload\n );\n try {\n const collectionConfig = await translationsApi.getCollectionConfig(global ? articleDirectory.name : articleDirectory.crowdinCollectionDirectory.collectionSlug, global)\n const response = {\n fields: collectionConfig.fields,\n localizedFields: getLocalizedFields({ fields: collectionConfig.fields })\n }\n res.status(200).send(response);\n } catch (error) {",
"score": 0.8357718586921692
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " console.error(error, options);\n }\n }\n async getArticleDirectory(documentId: string) {\n const result = await getArticleDirectory(documentId, this.payload);\n return result;\n }\n async deleteFilesAndDirectory(documentId: string) {\n const files = await this.getFilesByDocumentID(documentId);\n for (const file of files) {",
"score": 0.83514803647995
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " }\n async getFilesByDocumentID(documentId: string) {\n const result = await getFilesByDocumentID(documentId, this.payload);\n return result;\n }\n}",
"score": 0.8173831701278687
},
{
"filename": "src/endpoints/globals/reviewTranslation.ts",
"retrieved_chunk": " pluginOptions,\n req.payload\n );\n try {\n const translations = await translationsApi.updateTranslation({\n documentId: !global && articleDirectory.name,\n collection: global\n ? articleDirectory.name\n : articleDirectory.crowdinCollectionDirectory.collectionSlug,\n global,",
"score": 0.8069806098937988
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": " }\n const filteredFields = topLevel\n ? getLocalizedFields({\n fields,\n type: !crowdinHtmlObject ? \"json\" : undefined,\n })\n : fields;\n filteredFields.forEach((field) => {\n if (!crowdinJsonObject[field.name]) {\n return;",
"score": 0.8017348051071167
}
] | typescript | const files = await this.filesApi.getFilesByDocumentID(documentId); |
import { oraPromise } from 'ora'
import { ChatGptHelper, GeneratorHelperInterface } from './lib/post-helpers'
import {
PostPrompt,
Post
} from './types'
import { replaceAllPrompts } from './lib/template'
/**
* Class for generating a post. It need a helper class to generate the post
* Each helper class must implement the GeneratorHelperInterface
*/
export class PostGenerator {
private helper : GeneratorHelperInterface
public constructor (helper : GeneratorHelperInterface) {
this.helper = helper
}
public async generate () : Promise<Post> {
return this.helper.isCustom() ? await this.customGenerate() : await this.autoGenerate()
}
/**
* Generate a post using the custom prompt based on a template
*/
private async customGenerate () : Promise<Post> {
const promptContents = []
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
// We remove the first prompt because it is the system prompt
const prompts = this.helper.getPrompt().prompts.slice(1)
// for each prompt, we generate the content
const templatePrompts = prompts.entries()
for (const [index, prompt] of templatePrompts) {
const content = await oraPromise(
this.helper.generateCustomPrompt(prompt),
{
text: `Generating the prompt num. ${index + 1} ...`
}
)
promptContents.push(content)
}
// We replace the prompts by the AI answer in the template content
const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)
const seoInfo = await oraPromise(
this.helper.generateSeoInfo(),
{
text: 'Generating SEO info ...'
}
)
return {
title: seoInfo.h1,
slug: seoInfo.slug,
seoTitle: seoInfo.seoTitle,
seoDescription: seoInfo.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
}
}
/**
* Generate a post using the auto mode
*/
private async autoGenerate () : Promise<Post> {
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
const tableOfContent = await oraPromise(
this.helper.generateContentOutline(),
{
text: 'Generating post outline ...'
}
)
let content = await oraPromise(
this.helper.generateIntroduction(),
{
text: 'Generating introduction...'
}
)
content += await oraPromise(
| this.helper.generateHeadingContents(tableOfContent),
{ |
text: 'Generating content ...'
}
)
if (this.helper.getPrompt().withConclusion) {
content += await oraPromise(
this.helper.generateConclusion(),
{
text: 'Generating conclusion...'
}
)
}
return {
title: tableOfContent.title,
slug: tableOfContent.slug,
seoTitle: tableOfContent.seoTitle,
seoDescription: tableOfContent.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
}
}
}
/**
* Class for generating a post using the OpenAI API
*/
export class OpenAIPostGenerator extends PostGenerator {
public constructor (postPrompt : PostPrompt) {
super(new ChatGptHelper(postPrompt))
}
}
| src/post.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " async generateConclusion () {\n const response = await this.sendRequest(getPromptForConclusion(), this.completionParams)\n return extractCodeBlock(response.text)\n }\n async generateHeadingContents (postOutline : PostOutline) {\n const headingLevel = 2\n return await this.buildContent(postOutline.headings, headingLevel)\n }\n private async buildContent (headings: Heading[], headingLevel : number, previousContent: string = ''): Promise<string> {\n if (headings.length === 0) {",
"score": 0.8271711468696594
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " return previousContent\n }\n const [currentHeading, ...remainingHeadings] = headings\n const mdHeading = Array(headingLevel).fill('#').join('')\n let content = previousContent + '\\n' + mdHeading + ' ' + currentHeading.title\n if (currentHeading.headings && currentHeading.headings.length > 0) {\n content = await this.buildContent(currentHeading.headings, headingLevel + 1, content)\n } else {\n content += '\\n' + await this.getContent(currentHeading)\n }",
"score": 0.8143612146377563
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " if (this.postPrompt.debug) {\n console.log('---------- AUDIENCE INTENT ----------')\n console.log(response.text)\n }\n return extractAudienceIntentInfo(response.text)\n }\n async generateIntroduction () {\n const response = await this.sendRequest(getPromptForIntroduction(this.postPrompt), this.completionParams)\n return extractCodeBlock(response.text)\n }",
"score": 0.8045034408569336
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " return this.buildContent(remainingHeadings, headingLevel, content)\n }\n private async getContent (heading: Heading): Promise<string> {\n if (this.postPrompt.debug) {\n console.log(`\\nHeading : ${heading.title} ...'\\n`)\n }\n const response = await this.sendRequest(getPromptForHeading(this.postPrompt.tone, heading.title, heading.keywords), this.completionParams)\n return `${extractCodeBlock(response.text)}\\n`\n }\n // -----------------------------------------------",
"score": 0.7891775369644165
},
{
"filename": "src/lib/extractor.ts",
"retrieved_chunk": " 'title'\n ],\n additionalProperties: false\n }\n }\n}\nexport function extractCodeBlock (text: string): string {\n // Extract code blocks with specified tags\n const codeBlockTags = ['markdown', 'html', 'json']\n for (const tag of codeBlockTags) {",
"score": 0.7787350416183472
}
] | typescript | this.helper.generateHeadingContents(tableOfContent),
{ |
import fs from 'fs'
import util from 'util'
import { Command } from 'commander'
import {
getAllWordpress,
getWordpress,
addWordpress,
removeWordpress,
exportWordpressList,
importWordpressList
} from '../../lib/store/store'
import { getCategories, createPost, updatePost } from '../../lib/wp/wp-api'
import { Post } from '../../types'
const readFile = util.promisify(fs.readFile)
type UpdateOptions = {
date : string
}
export function buildWpCommands (program: Command) {
const wpCommand = program
.command('wp')
.description('Wordpress related commands. The wp list is stored in the local store : ~/.julius/wordpress.json')
.action(() => {
console.log('Please provide a sub-command: "add" or "ls" or "rm" , ... ')
})
wpCommand
.command('ls')
.description('List all Wordpress sites')
.action(async () => {
await getAllWp()
})
wpCommand
.command('info <domain|index>')
.description('Info on a Wordpress site')
.action(async (domain) => {
const domainFound = await getWordpress(domain)
if (domainFound) {
console.log('\nWordpress site found :\n')
console.log(`\ndomain : ${domainFound.domain}`)
console.log(`username : ${ | domainFound.username}`)
console.log(`password : ${domainFound.password}\n`)
} else { |
console.log(`\nWordpress site ${domain} not found\n`)
}
})
wpCommand
.command('add <domain:username:password>')
.description('Add a new Wordpress site')
.action(async (site) => {
await addWpSite(site)
})
wpCommand
.command('rm <domain|index>')
.description('Remove Wordpress site')
.action(async (domain) => {
const deleted = await removeWordpress(domain)
console.log(deleted ? `\nWordpress site ${domain} removed successfully\n` : `Wordpress site ${domain} not found\n`)
})
wpCommand
.command('export <file>')
.description('Export the list of wordpress sites (with credentials) the console')
.action(async (file) => {
await exportWordpressList(file)
})
wpCommand
.command('import <file>')
.description('Import the list of wordpress sites (with credentials) from a file')
.action(async (file) => {
await importWordpressList(file)
})
wpCommand
.command('categories <domain|index>')
.description('Fetch the categories for one Wordpress site')
.action(async (domain) => {
const domainFound = await getWordpress(domain)
if (domainFound) {
const categories = await getCategories(domainFound)
console.log(categories)
} else {
console.log(`\nWordpress site ${domain} not found\n`)
}
})
wpCommand
.command('post <domain> <categoryId> <jsonfile>')
.description('Create a new post to a Wordpress site. The file has to be a json file containing : { content, categories, seoTitle, seoDescription }')
.action(async (domain, categoryId, jsonFile) => {
const domainFound = await getWordpress(domain)
if (!domainFound) {
console.log(`\nWordpress site ${domain} not found\n`)
return
}
const jsonContent = await readFile(jsonFile, 'utf8')
const post: Post = JSON.parse(jsonContent)
post.categories = [categoryId]
post.status = 'draft'
await createPost(domainFound, post)
console.log(`\nContent has been published on https://${domainFound.domain}/${post.slug}\n`)
})
wpCommand
.command('update <domain> <slug> <jsonfile>')
.option('-d, --date <date>', 'Update the publish date of the post. Use the format YYYY-MM-DD:HH:MM:SS')
.description('Update a new post to a Wordpress site. The file has to be a json file containing : { content, seoTitle, seoDescription }')
.action(async (domain, slug, jsonFile, options : UpdateOptions) => {
const domainFound = await getWordpress(domain)
if (!domainFound) {
console.log(`\nWordpress site ${domain} not found\n`)
return
}
const jsonContent = await readFile(jsonFile, 'utf8')
const newContent: Post = JSON.parse(jsonContent)
await updatePost(domainFound, slug, newContent, options.date)
console.log(`\nContent has been updated on https://${domainFound.domain}${slug}\n\n`)
})
}
async function getAllWp () {
const wpSites = await getAllWordpress()
if (wpSites.length === 0) {
console.log('\nNo Wordpress site found\n')
return
}
console.log('\nWordpress sites :\n')
console.log(wpSites.map((wp, index) => `${index + 1}. ${wp.domain} (${wp.username})`).join('\n') + '\n')
}
async function addWpSite (site) {
const [domain, username, password] = site.split(':')
if (!domain || !username || !password) {
console.error('Invalid format for adding a new wp site. Expected : domain:username:password')
return
}
await addWordpress({ domain, username, password })
console.log(`\nWordpress site ${domain} added successfully\n`)
}
| src/bin/command/wp.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " const writeDocPromise = fs.promises.writeFile(contentFile, buildContent(options, post), 'utf8')\n await Promise.all([writeJSONPromise, writeDocPromise])\n console.log(`🔥 Content is successfully generated in the file : ${contentFile}. Use the file ${jsonFile} to publish the content on Wordpress.`)\n console.log(`- Slug : ${post.slug}`)\n console.log(`- H1 : ${post.title}`)\n console.log(`- SEO Title : ${post.seoTitle}`)\n console.log(`- SEO Description : ${post.seoDescription}`)\n console.log(`- Total prompts tokens : ${post.totalTokens.promptTokens}`)\n console.log(`- Total completion tokens : ${post.totalTokens.completionTokens}`)\n console.log(`- Estimated cost : ${estimatedCost(postPrompt.model, post)}$`)",
"score": 0.7673766613006592
},
{
"filename": "src/lib/wp/wp-api.ts",
"retrieved_chunk": " };\n date?: string;\n date_gmt?: string;\n}\nexport async function getCategories (wp : Wordpress) {\n const { domain, username, password } = wp\n const response = await axios.get(`${getApiUrl(domain)}/categories`, authenticate(username, password))\n return response.data.map((category) => {\n return {\n id: category.id,",
"score": 0.7611443996429443
},
{
"filename": "src/lib/store/store.ts",
"retrieved_chunk": "}\nexport async function removeWordpress (domain: string): Promise<Boolean> {\n const wpSites = await getAllWordpress()\n const index = !isNaN(Number(domain)) ? Number(domain) - 1 : wpSites.findIndex((wp) => wp.domain === domain)\n if (index < 0) {\n return false\n }\n wpSites.splice(index, 1)\n await fs.promises.writeFile(WORDPRESS_FILE, JSON.stringify(wpSites), 'utf8')\n return true",
"score": 0.759006142616272
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " console.log('---------- PROMPT MAIN KEYWORD ----------')\n console.log(prompt)\n }\n const response = await this.sendRequest(prompt)\n if (this.postPrompt.debug) {\n console.log('---------- MAIN KEYWORD ----------')\n console.log(response.text)\n }\n return extractJsonArray(response.text)\n }",
"score": 0.757174015045166
},
{
"filename": "src/lib/store/store.ts",
"retrieved_chunk": " return JSON.parse(data)\n}\nexport async function addWordpress (wp: Wordpress): Promise<void> {\n const wpSites = [...await getAllWordpress(), wp].sort((a, b) => a.domain.localeCompare(b.domain))\n await fs.promises.writeFile(WORDPRESS_FILE, JSON.stringify(wpSites), 'utf8')\n}\nexport async function getWordpress (domain: string): Promise<Wordpress | undefined> {\n const wpSites = await getAllWordpress()\n const index = !isNaN(Number(domain)) ? Number(domain) - 1 : wpSites.findIndex((wp) => wp.domain === domain)\n return wpSites[index]",
"score": 0.7549667358398438
}
] | typescript | domainFound.username}`)
console.log(`password : ${domainFound.password}\n`)
} else { |
import crowdin, {
Credentials,
SourceFiles,
UploadStorage,
} from "@crowdin/crowdin-api-client";
import { mockCrowdinClient } from "../mock/crowdin-client";
import { Payload } from "payload";
import { PluginOptions } from "../../types";
import { toWords } from "payload/dist/utilities/formatLabels";
import {
getArticleDirectory,
getFile,
getFiles,
getFileByDocumentID,
getFilesByDocumentID,
} from "../helpers";
import { isEmpty } from "lodash";
export interface IcrowdinFile {
id: string;
originalId: number;
fileData: {
json?: Object;
html?: string;
};
}
interface IfindOrCreateCollectionDirectory {
collectionSlug: string;
}
interface IfindOrCreateArticleDirectory
extends IfindOrCreateCollectionDirectory {
document: any;
global?: boolean;
}
interface IupdateOrCreateFile {
name: string;
value: string | object;
fileType: "html" | "json";
articleDirectory: any;
}
interface IcreateOrUpdateFile {
name: string;
fileData: string | object;
fileType: "html" | "json";
}
interface IcreateFile extends IcreateOrUpdateFile {
directoryId: number;
}
interface IupdateFile extends IcreateOrUpdateFile {
crowdinFile: IcrowdinFile;
}
interface IupdateCrowdinFile extends IcreateOrUpdateFile {
fileId: number;
}
interface IgetTranslation {
documentId: string;
fieldName: string;
locale: string;
global?: boolean;
}
export class payloadCrowdinSyncFilesApi {
sourceFilesApi: SourceFiles;
uploadStorageApi: UploadStorage;
projectId: number;
directoryId?: number;
payload: Payload;
constructor(pluginOptions: PluginOptions, payload: Payload) {
// credentials
const credentials: Credentials = {
token: pluginOptions.token,
};
const { sourceFilesApi, uploadStorageApi } = new crowdin(credentials);
this.projectId = pluginOptions.projectId;
this.directoryId = pluginOptions.directoryId;
this.sourceFilesApi =
process.env.NODE_ENV === "test"
? (mockCrowdinClient(pluginOptions) as any)
: sourceFilesApi;
this.uploadStorageApi =
process.env.NODE_ENV === "test"
? (mockCrowdinClient(pluginOptions) as any)
: uploadStorageApi;
this.payload = payload;
}
async findOrCreateArticleDirectory({
document,
collectionSlug,
global = false,
}: IfindOrCreateArticleDirectory) {
let crowdinPayloadArticleDirectory;
if (document.crowdinArticleDirectory) {
// Update not possible. Article name needs to be updated manually on Crowdin.
// The name of the directory is Crowdin specific helper text to give
// context to translators.
// See https://developer.crowdin.com/api/v2/#operation/api.projects.directories.getMany
crowdinPayloadArticleDirectory = await this.payload.findByID({
collection: "crowdin-article-directories",
id:
document.crowdinArticleDirectory.id ||
document.crowdinArticleDirectory,
});
} else {
const crowdinPayloadCollectionDirectory =
await this.findOrCreateCollectionDirectory({
collectionSlug: global ? "globals" : collectionSlug,
});
// Create article directory on Crowdin
const crowdinDirectory = await this.sourceFilesApi.createDirectory(
this.projectId,
{
directoryId: crowdinPayloadCollectionDirectory.originalId,
name: global ? collectionSlug : document.id,
title: global
? toWords(collectionSlug)
: document.title || document.name, // no tests for this Crowdin metadata, but makes it easier for translators
}
);
// Store result in Payload CMS
crowdinPayloadArticleDirectory = await this.payload.create({
collection: "crowdin-article-directories",
data: {
crowdinCollectionDirectory: crowdinPayloadCollectionDirectory.id,
originalId: crowdinDirectory.data.id,
projectId: this.projectId,
directoryId: crowdinDirectory.data.directoryId,
name: crowdinDirectory.data.name,
createdAt: crowdinDirectory.data.createdAt,
updatedAt: crowdinDirectory.data.updatedAt,
},
});
// Associate result with document
if (global) {
const update = await this.payload.updateGlobal({
slug: collectionSlug,
data: {
crowdinArticleDirectory: crowdinPayloadArticleDirectory.id,
},
});
} else {
const update = await this.payload.update({
collection: collectionSlug,
id: document.id,
data: {
crowdinArticleDirectory: crowdinPayloadArticleDirectory.id,
},
});
}
}
return crowdinPayloadArticleDirectory;
}
private async findOrCreateCollectionDirectory({
collectionSlug,
}: IfindOrCreateCollectionDirectory) {
let crowdinPayloadCollectionDirectory;
// Check whether collection directory exists on Crowdin
const query = await this.payload.find({
collection: "crowdin-collection-directories",
where: {
collectionSlug: {
equals: collectionSlug,
},
},
});
if (query.totalDocs === 0) {
// Create collection directory on Crowdin
const crowdinDirectory = await this.sourceFilesApi.createDirectory(
this.projectId,
{
directoryId: this.directoryId,
name: collectionSlug,
title: toWords(collectionSlug), // is this transformed value available on the collection object?
}
);
// Store result in Payload CMS
crowdinPayloadCollectionDirectory = await this.payload.create({
collection: "crowdin-collection-directories",
data: {
collectionSlug: collectionSlug,
originalId: crowdinDirectory.data.id,
projectId: this.projectId,
directoryId: crowdinDirectory.data.directoryId,
name: crowdinDirectory.data.name,
title: crowdinDirectory.data.title,
createdAt: crowdinDirectory.data.createdAt,
updatedAt: crowdinDirectory.data.updatedAt,
},
});
} else {
crowdinPayloadCollectionDirectory = query.docs[0];
}
return crowdinPayloadCollectionDirectory;
}
async getFile(name: string, crowdinArticleDirectoryId: string): Promise<any> {
return getFile(name, crowdinArticleDirectoryId, this.payload);
}
async getFiles(crowdinArticleDirectoryId: string): Promise<any> {
return getFiles(crowdinArticleDirectoryId, this.payload);
}
/**
* Create/Update/Delete a file on Crowdin
*
* Records the file in Payload CMS under the `crowdin-files` collection.
*
* - Create a file if it doesn't exist on Crowdin and the supplied content is not empty
* - Update a file if it exists on Crowdin and the supplied content is not empty
* - Delete a file if it exists on Crowdin and the supplied file content is empty
*/
async createOrUpdateFile({
name,
value,
fileType,
articleDirectory,
}: IupdateOrCreateFile) {
const empty = isEmpty(value);
// Check whether file exists on Crowdin
let crowdinFile = await this.getFile(name, articleDirectory.id);
let updatedCrowdinFile;
if (!empty) {
if (!crowdinFile) {
updatedCrowdinFile = await this.createFile({
name,
value,
fileType,
articleDirectory,
});
} else {
updatedCrowdinFile = await this.updateFile({
crowdinFile,
name: name,
fileData: value,
fileType: fileType,
});
}
} else {
if (crowdinFile) {
updatedCrowdinFile = await this.deleteFile(crowdinFile);
}
}
return updatedCrowdinFile;
}
private async updateFile({
crowdinFile,
name,
fileData,
fileType,
}: IupdateFile) {
// Update file on Crowdin
const updatedCrowdinFile = await this.crowdinUpdateFile({
fileId: crowdinFile.originalId,
name,
fileData,
fileType,
});
const payloadCrowdinFile = await this.payload.update({
collection: "crowdin-files", // required
id: crowdinFile.id,
data: {
// required
updatedAt: updatedCrowdinFile.data.updatedAt,
revisionId: updatedCrowdinFile.data.revisionId,
...(fileType === "json" && { fileData: { json: fileData } }),
...(fileType === "html" && { fileData: { html: fileData } }),
},
});
}
private async createFile({
name,
value,
fileType,
articleDirectory,
}: IupdateOrCreateFile) {
// Create file on Crowdin
const crowdinFile = await this.crowdinCreateFile({
directoryId: articleDirectory.originalId,
name: name,
fileData: value,
fileType: fileType,
});
// createFile has been intermittent in not being available
// perhaps logic goes wrong somewhere and express middleware
// is hard to debug?
/*const crowdinFile = {data: {
revisionId: 5,
status: 'active',
priority: 'normal',
importOptions: { contentSegmentation: true, customSegmentation: false },
exportOptions: null,
excludedTargetLanguages: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
id: 1079,
projectId: 323731,
branchId: null,
directoryId: 1077,
name: name,
title: null,
type: fileType,
path: `/policies/security-and-privacy/${name}.${fileType}`
}}*/
// Store result on Payload CMS
if (crowdinFile) {
const payloadCrowdinFile = await this.payload.create({
collection: "crowdin-files", // required
data: {
// required
title: crowdinFile.data.name,
field: name,
crowdinArticleDirectory: articleDirectory.id,
createdAt: crowdinFile.data.createdAt,
updatedAt: crowdinFile.data.updatedAt,
originalId: crowdinFile.data.id,
projectId: crowdinFile.data.projectId,
directoryId: crowdinFile.data.directoryId,
revisionId: crowdinFile.data.revisionId,
name: crowdinFile.data.name,
type: crowdinFile.data.type,
path: crowdinFile.data.path,
...(fileType === "json" && { fileData: { json: value } }),
...(fileType === "html" && { fileData: { html: value } }),
},
});
return payloadCrowdinFile;
}
}
async deleteFile(crowdinFile: IcrowdinFile) {
const file = await this.sourceFilesApi.deleteFile(
this.projectId,
crowdinFile.originalId
);
const payloadFile = await this.payload.delete({
collection: "crowdin-files", // required
id: crowdinFile.id, // required
});
return payloadFile;
}
private async crowdinUpdateFile({
fileId,
name,
fileData,
fileType,
}: IupdateCrowdinFile) {
const storage = await this.uploadStorageApi.addStorage(
name,
fileData,
fileType
);
//const file = await sourceFilesApi.deleteFile(projectId, 1161)
const file = await this.sourceFilesApi.updateOrRestoreFile(
this.projectId,
fileId,
{
storageId: storage.data.id,
}
);
return file;
}
private async crowdinCreateFile({
name,
fileData,
fileType,
directoryId,
}: IcreateFile) {
const storage = await this.uploadStorageApi.addStorage(
name,
fileData,
fileType
);
const options = {
name: `${name}.${fileType}`,
title: name,
storageId: storage.data.id,
directoryId,
type: fileType,
};
try {
const file = await this.sourceFilesApi.createFile(
this.projectId,
options
);
return file;
} catch (error) {
console.error(error, options);
}
}
async getArticleDirectory(documentId: string) {
const result = await getArticleDirectory(documentId, this.payload);
return result;
}
async deleteFilesAndDirectory(documentId: string) {
const files = await this.getFilesByDocumentID(documentId);
for (const file of files) {
| await this.deleteFile(file); |
}
await this.deleteArticleDirectory(documentId);
}
async deleteArticleDirectory(documentId: string) {
const crowdinPayloadArticleDirectory = await this.getArticleDirectory(
documentId
);
await this.sourceFilesApi.deleteDirectory(
this.projectId,
crowdinPayloadArticleDirectory.originalId
);
await this.payload.delete({
collection: "crowdin-article-directories",
id: crowdinPayloadArticleDirectory.id,
});
}
async getFileByDocumentID(name: string, documentId: string) {
const result = await getFileByDocumentID(name, documentId, this.payload);
return result;
}
async getFilesByDocumentID(documentId: string) {
const result = await getFilesByDocumentID(documentId, this.payload);
return result;
}
}
| src/api/payload-crowdin-sync/files.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/helpers.ts",
"retrieved_chunk": " return getFile(name, articleDirectory.id, payload);\n}\nexport async function getFilesByDocumentID(\n documentId: string,\n payload: Payload\n): Promise<IcrowdinFile[]> {\n const articleDirectory = await getArticleDirectory(documentId, payload);\n if (!articleDirectory) {\n // tests call this function to make sure files are deleted\n return [];",
"score": 0.9096229672431946
},
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " async getTranslation({ documentId, fieldName, locale }: IgetTranslation) {\n const articleDirectory = await this.filesApi.getArticleDirectory(\n documentId\n );\n const file = await this.filesApi.getFile(fieldName, articleDirectory.id);\n // it is possible a file doesn't exist yet - e.g. an article with localized text fields that contains an empty html field.\n if (!file) {\n return;\n }\n try {",
"score": 0.8852414488792419
},
{
"filename": "src/api/helpers.ts",
"retrieved_chunk": " },\n });\n return result.docs;\n}\nexport async function getFileByDocumentID(\n name: string,\n documentId: string,\n payload: Payload\n): Promise<IcrowdinFile> {\n const articleDirectory = await getArticleDirectory(documentId, payload);",
"score": 0.8662928938865662
},
{
"filename": "src/hooks/collections/afterChange.ts",
"retrieved_chunk": " */\n const filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, req.payload);\n /**\n * Retrieve the Crowdin Article Directory article\n *\n * Records of Crowdin directories are stored in Payload.\n */\n const articleDirectory = await filesApi.findOrCreateArticleDirectory({\n document: doc,\n collectionSlug: collection.slug,",
"score": 0.8405975103378296
},
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " requiredFieldSlugs.forEach((slug) => {\n if (!docTranslations.hasOwnProperty(slug)) {\n docTranslations[slug] = currentTranslations[slug];\n }\n });\n }\n return docTranslations;\n }\n async getHtmlFieldSlugs(documentId: string) {\n const files = await this.filesApi.getFilesByDocumentID(documentId);",
"score": 0.834632158279419
}
] | typescript | await this.deleteFile(file); |
import {
CollectionAfterChangeHook,
CollectionConfig,
Field,
GlobalConfig,
GlobalAfterChangeHook,
PayloadRequest,
} from "payload/types";
import { Descendant } from "slate";
import { PluginOptions } from "../../types";
import {
buildCrowdinHtmlObject,
buildCrowdinJsonObject,
convertSlateToHtml,
fieldChanged,
} from "../../utilities";
import deepEqual from "deep-equal";
import { getLocalizedFields } from "../../utilities";
import { payloadCrowdinSyncFilesApi } from "../../api/payload-crowdin-sync/files";
/**
* Update Crowdin collections and make updates in Crowdin
*
* This functionality used to be split into field hooks.
* However, it is more reliable to loop through localized
* fields and perform opeerations in one place. The
* asynchronous nature of operations means that
* we need to be careful updates are not made sooner than
* expected.
*/
interface CommonArgs {
pluginOptions: PluginOptions;
}
interface Args extends CommonArgs {
collection: CollectionConfig;
}
interface GlobalArgs extends CommonArgs {
global: GlobalConfig;
}
export const getGlobalAfterChangeHook =
({ global, pluginOptions }: GlobalArgs): GlobalAfterChangeHook =>
async ({
doc, // full document data
previousDoc, // document data before updating the collection
req, // full express request
}) => {
const operation = previousDoc ? "update" : "create";
return performAfterChange({
doc,
req,
previousDoc,
operation,
collection: global,
global: true,
pluginOptions,
});
};
export const getAfterChangeHook =
({ collection, pluginOptions }: Args): CollectionAfterChangeHook =>
async ({
doc, // full document data
req, // full express request
previousDoc, // document data before updating the collection
operation, // name of the operation ie. 'create', 'update'
}) => {
return performAfterChange({
doc,
req,
previousDoc,
operation,
collection,
pluginOptions,
});
};
interface IPerformChange {
doc: any;
req: PayloadRequest;
previousDoc: any;
operation: string;
collection: CollectionConfig | GlobalConfig;
global?: boolean;
pluginOptions: PluginOptions;
}
const performAfterChange = async ({
doc, // full document data
req, // full express request
previousDoc,
operation,
collection,
global = false,
pluginOptions,
}: IPerformChange) => {
/**
* Abort if token not set and not in test mode
*/
if (!pluginOptions.token && process.env.NODE_ENV !== "test") {
return doc;
}
const | localizedFields: Field[] = getLocalizedFields({ |
fields: collection.fields,
});
/**
* Abort if there are no fields to localize
*/
if (localizedFields.length === 0) {
return doc;
}
/**
* Abort if locale is unavailable or this
* is an update from the API to the source
* locale.
*/
if (!req.locale || req.locale !== pluginOptions.sourceLocale) {
return doc;
}
/**
* Prepare JSON objects
*
* `text` fields are compiled into a single JSON file
* on Crowdin. Prepare previous and current objects.
*/
const currentCrowdinJsonData = buildCrowdinJsonObject({
doc,
fields: localizedFields,
});
const prevCrowdinJsonData = buildCrowdinJsonObject({
doc: previousDoc,
fields: localizedFields,
});
/**
* Initialize Crowdin client sourceFilesApi
*/
const filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, req.payload);
/**
* Retrieve the Crowdin Article Directory article
*
* Records of Crowdin directories are stored in Payload.
*/
const articleDirectory = await filesApi.findOrCreateArticleDirectory({
document: doc,
collectionSlug: collection.slug,
global,
});
// START: function definitions
const createOrUpdateJsonFile = async () => {
await filesApi.createOrUpdateFile({
name: "fields",
value: currentCrowdinJsonData,
fileType: "json",
articleDirectory,
});
};
const createOrUpdateHtmlFile = async ({
name,
value,
}: {
name: string;
value: Descendant[];
}) => {
await filesApi.createOrUpdateFile({
name: name,
value: convertSlateToHtml(value),
fileType: "html",
articleDirectory,
});
};
const createOrUpdateJsonSource = async () => {
if (
(!deepEqual(currentCrowdinJsonData, prevCrowdinJsonData) &&
Object.keys(currentCrowdinJsonData).length !== 0) ||
process.env.PAYLOAD_CROWDIN_SYNC_ALWAYS_UPDATE === "true"
) {
await createOrUpdateJsonFile();
}
};
/**
* Recursively send rich text fields to Crowdin as HTML
*
* Name these HTML files with dot notation. Examples:
*
* * `localizedRichTextField`
* * `groupField.localizedRichTextField`
* * `arrayField[0].localizedRichTextField`
* * `arrayField[1].localizedRichTextField`
*/
const createOrUpdateHtmlSource = async () => {
const currentCrowdinHtmlData = buildCrowdinHtmlObject({
doc,
fields: localizedFields,
});
const prevCrowdinHtmlData = buildCrowdinHtmlObject({
doc: previousDoc,
fields: localizedFields,
});
Object.keys(currentCrowdinHtmlData).forEach(async (name) => {
const currentValue = currentCrowdinHtmlData[name];
const prevValue = prevCrowdinHtmlData[name];
if (
!fieldChanged(prevValue, currentValue, "richText") &&
process.env.PAYLOAD_CROWDIN_SYNC_ALWAYS_UPDATE !== "true"
) {
return;
}
const file = await createOrUpdateHtmlFile({
name,
value: currentValue as Descendant[],
});
});
};
// END: function definitions
await createOrUpdateJsonSource();
await createOrUpdateHtmlSource();
return doc;
};
| src/hooks/collections/afterChange.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/hooks/collections/afterDelete.ts",
"retrieved_chunk": " req, // full express request\n id, // id of document to delete\n doc, // deleted document\n }) => {\n /**\n * Abort if token not set and not in test mode\n */\n if (!pluginOptions.token && process.env.NODE_ENV !== \"test\") {\n return doc;\n }",
"score": 0.942046046257019
},
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " });\n return docTranslations;\n } catch (error) {\n console.log(error);\n throw new Error(`${error}`);\n }\n }\n /**\n * Retrieve translations from Crowdin for a document in a given locale\n */",
"score": 0.8586313724517822
},
{
"filename": "src/utilities/getLocalizedFields.spec.ts",
"retrieved_chunk": " type: \"array\",\n fields: [...localizedFieldCollection],\n },\n ];\n expect(getLocalizedFields({ fields })).toEqual(expected);\n });\n /**\n * * help ensure no errors during version 0 development\n * * mitigate against errors if a new field type is introduced by Payload CMS\n */",
"score": 0.8515310883522034
},
{
"filename": "src/utilities/containsLocalizedFields.spec.ts",
"retrieved_chunk": " ];\n expect(containsLocalizedFields({ fields })).toEqual(true);\n });\n /**\n * * help ensure no errors during version 0 development\n * * mitigate against errors if a new field type is introduced by Payload CMS\n */\n it(\"does not include unrecognized field types\", () => {\n const fields: any[] = [\n {",
"score": 0.8456941246986389
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": " doc,\n fields,\n topLevel = true,\n}: {\n doc: { [key: string]: any };\n /** Use getLocalizedFields to pass localized fields only */\n fields: Field[];\n /** Flag used internally to filter json fields before recursion. */\n topLevel?: boolean;\n}) => {",
"score": 0.8434010744094849
}
] | typescript | localizedFields: Field[] = getLocalizedFields({ |
import { oraPromise } from 'ora'
import { ChatGptHelper, GeneratorHelperInterface } from './lib/post-helpers'
import {
PostPrompt,
Post
} from './types'
import { replaceAllPrompts } from './lib/template'
/**
* Class for generating a post. It need a helper class to generate the post
* Each helper class must implement the GeneratorHelperInterface
*/
export class PostGenerator {
private helper : GeneratorHelperInterface
public constructor (helper : GeneratorHelperInterface) {
this.helper = helper
}
public async generate () : Promise<Post> {
return this.helper.isCustom() ? await this.customGenerate() : await this.autoGenerate()
}
/**
* Generate a post using the custom prompt based on a template
*/
private async customGenerate () : Promise<Post> {
const promptContents = []
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
// We remove the first prompt because it is the system prompt
const prompts = this.helper.getPrompt().prompts.slice(1)
// for each prompt, we generate the content
const templatePrompts = prompts.entries()
for (const [index, prompt] of templatePrompts) {
const content = await oraPromise(
this.helper.generateCustomPrompt(prompt),
{
text: `Generating the prompt num. ${index + 1} ...`
}
)
promptContents.push(content)
}
// We replace the prompts by the AI answer in the template content
const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)
const seoInfo = await oraPromise(
this.helper.generateSeoInfo(),
{
text: 'Generating SEO info ...'
}
)
return {
title: seoInfo.h1,
slug: seoInfo.slug,
seoTitle: seoInfo.seoTitle,
| seoDescription: seoInfo.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
} |
}
/**
* Generate a post using the auto mode
*/
private async autoGenerate () : Promise<Post> {
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
const tableOfContent = await oraPromise(
this.helper.generateContentOutline(),
{
text: 'Generating post outline ...'
}
)
let content = await oraPromise(
this.helper.generateIntroduction(),
{
text: 'Generating introduction...'
}
)
content += await oraPromise(
this.helper.generateHeadingContents(tableOfContent),
{
text: 'Generating content ...'
}
)
if (this.helper.getPrompt().withConclusion) {
content += await oraPromise(
this.helper.generateConclusion(),
{
text: 'Generating conclusion...'
}
)
}
return {
title: tableOfContent.title,
slug: tableOfContent.slug,
seoTitle: tableOfContent.seoTitle,
seoDescription: tableOfContent.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
}
}
}
/**
* Class for generating a post using the OpenAI API
*/
export class OpenAIPostGenerator extends PostGenerator {
public constructor (postPrompt : PostPrompt) {
super(new ChatGptHelper(postPrompt))
}
}
| src/post.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/wp/wp-api.ts",
"retrieved_chunk": " if (response.data.length === 0) {\n throw new Error(`Post with ${slug} not found`)\n }\n const postId: number = response.data[0].id\n const updatedPost : UpdatePost = {\n content: newContent.content,\n title: newContent.title,\n meta: {\n yoast_wpseo_title: newContent.seoTitle,\n yoast_wpseo_metadesc: newContent.seoDescription",
"score": 0.768079936504364
},
{
"filename": "src/types.ts",
"retrieved_chunk": "}\nexport type SeoInfo = {\n h1 : string\n slug : string\n seoTitle : string\n seoDescription : string\n}\nexport type AudienceIntentInfo = {\n audience : string\n intent : string",
"score": 0.7679843306541443
},
{
"filename": "src/types.ts",
"retrieved_chunk": "}\nexport type Post = {\n title : string\n content : string\n seoTitle : string\n seoDescription : string\n slug : string,\n categories? : number[],\n status? : string,\n totalTokens : TotalTokens",
"score": 0.7451578378677368
},
{
"filename": "src/types.ts",
"retrieved_chunk": " title: string\n keywords?: string[]\n headings?: Heading[]\n}\nexport type PostOutline = {\n title: string\n headings : Heading[],\n slug : string,\n seoTitle : string,\n seoDescription : string",
"score": 0.7360419034957886
},
{
"filename": "src/lib/extractor.ts",
"retrieved_chunk": " },\n slug: {\n type: 'string'\n },\n seoTitle: {\n type: 'string'\n },\n seoDescription: {\n type: 'string'\n }",
"score": 0.73397296667099
}
] | typescript | seoDescription: seoInfo.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
} |
import crowdin, {
Credentials,
Translations,
} from "@crowdin/crowdin-api-client";
import { payloadCrowdinSyncFilesApi } from "./files";
import { mockCrowdinClient } from "../mock/crowdin-client";
import { Payload } from "payload";
import { PluginOptions } from "../../types";
import deepEqual from "deep-equal";
import {
CollectionConfig,
GlobalConfig,
SanitizedCollectionConfig,
SanitizedGlobalConfig,
} from "payload/types";
import { htmlToSlate, payloadHtmlToSlateConfig } from "slate-serializers";
import {
getLocalizedFields,
getFieldSlugs,
buildCrowdinJsonObject,
buildCrowdinHtmlObject,
buildPayloadUpdateObject,
getLocalizedRequiredFields,
} from "../../utilities";
interface IgetLatestDocumentTranslation {
collection: string;
doc: any;
locale: string;
global?: boolean;
}
interface IgetCurrentDocumentTranslation {
doc: any;
collection: string;
locale: string;
global?: boolean;
}
interface IgetTranslation {
documentId: string;
fieldName: string;
locale: string;
global?: boolean;
}
interface IupdateTranslation {
documentId: string;
collection: string;
dryRun?: boolean;
global?: boolean;
excludeLocales?: string[];
}
export class payloadCrowdinSyncTranslationsApi {
translationsApi: Translations;
filesApi: payloadCrowdinSyncFilesApi; // our wrapper for file operations
projectId: number;
directoryId?: number;
payload: Payload;
localeMap: PluginOptions["localeMap"];
sourceLocale: PluginOptions["sourceLocale"];
constructor(pluginOptions: PluginOptions, payload: Payload) {
// credentials
const credentials: Credentials = {
token: pluginOptions.token,
};
const { translationsApi } = new crowdin(credentials);
this.projectId = pluginOptions.projectId;
this.directoryId = pluginOptions.directoryId;
this.translationsApi =
process.env.NODE_ENV === "test"
? | (mockCrowdinClient(pluginOptions) as any)
: translationsApi; |
this.filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, payload);
this.payload = payload;
this.localeMap = pluginOptions.localeMap;
this.sourceLocale = pluginOptions.sourceLocale;
}
async updateTranslation({
documentId,
collection,
dryRun = true,
global = false,
excludeLocales = [],
}: IupdateTranslation) {
/**
* Get existing document
*
* * check document exists
* * check for `meta` field (which can be added by @payloadcms/seo)
*
*/
let doc: { crowdinArticleDirectory: { id: any } };
if (global) {
doc = await this.payload.findGlobal({
slug: collection,
locale: this.sourceLocale,
});
} else {
doc = await this.payload.findByID({
collection: collection,
id: documentId,
locale: this.sourceLocale,
});
}
const report: { [key: string]: any } = {};
for (const locale of Object.keys(this.localeMap)) {
if (excludeLocales.includes(locale)) {
continue;
}
report[locale] = {};
report[locale].currentTranslations =
await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
report[locale].latestTranslations =
await this.getLatestDocumentTranslation({
collection: collection,
doc: doc,
locale: locale,
global,
});
report[locale].changed = !deepEqual(
report[locale].currentTranslations,
report[locale].latestTranslations
);
if (report[locale].changed && !dryRun) {
if (global) {
try {
await this.payload.updateGlobal({
slug: collection,
locale: locale,
data: {
...report[locale].latestTranslations,
// error on update without the following line.
// see https://github.com/thompsonsj/payload-crowdin-sync/pull/13/files#r1209271660
crowdinArticleDirectory: doc.crowdinArticleDirectory.id,
},
});
} catch (error) {
console.log(error);
}
} else {
try {
await this.payload.update({
collection: collection,
locale: locale,
id: documentId,
data: report[locale].latestTranslations,
});
} catch (error) {
console.log(error);
}
}
}
}
return {
source: doc,
translations: { ...report },
};
}
getCollectionConfig(
collection: string,
global: boolean
): CollectionConfig | GlobalConfig {
let collectionConfig:
| SanitizedGlobalConfig
| SanitizedCollectionConfig
| undefined;
if (global) {
collectionConfig = this.payload.config.globals.find(
(col: GlobalConfig) => col.slug === collection
);
} else {
collectionConfig = this.payload.config.collections.find(
(col: CollectionConfig) => col.slug === collection
);
}
if (!collectionConfig)
throw new Error(`Collection ${collection} not found in payload config`);
return collectionConfig;
}
async getCurrentDocumentTranslation({
doc,
collection,
locale,
global = false,
}: IgetCurrentDocumentTranslation) {
// get document
let document: any;
if (global) {
document = await this.payload.findGlobal({
slug: collection,
locale: locale,
});
} else {
document = await this.payload.findByID({
collection: collection,
id: doc.id,
locale: locale,
});
}
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
// build crowdin json object
const crowdinJsonObject = buildCrowdinJsonObject({
doc: document,
fields: localizedFields,
});
const crowdinHtmlObject = buildCrowdinHtmlObject({
doc: document,
fields: localizedFields,
});
try {
const docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document,
});
return docTranslations;
} catch (error) {
console.log(error);
throw new Error(`${error}`);
}
}
/**
* Retrieve translations from Crowdin for a document in a given locale
*/
async getLatestDocumentTranslation({
collection,
doc,
locale,
global = false,
}: IgetLatestDocumentTranslation) {
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
if (!localizedFields) {
return { message: "no localized fields" };
}
let docTranslations: { [key: string]: any } = {};
// add json fields
const crowdinJsonObject =
(await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: "fields",
locale: locale,
})) || {};
// add html fields
const localizedHtmlFields = await this.getHtmlFieldSlugs(
global ? collectionConfig.slug : doc.id
);
let crowdinHtmlObject: { [key: string]: any } = {};
for (const field of localizedHtmlFields) {
crowdinHtmlObject[field] = await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: field,
locale: locale,
});
}
docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document: doc,
});
// Add required fields if not present
const requiredFieldSlugs = getFieldSlugs(
getLocalizedRequiredFields(collectionConfig)
);
if (requiredFieldSlugs.length > 0) {
const currentTranslations = await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
requiredFieldSlugs.forEach((slug) => {
if (!docTranslations.hasOwnProperty(slug)) {
docTranslations[slug] = currentTranslations[slug];
}
});
}
return docTranslations;
}
async getHtmlFieldSlugs(documentId: string) {
const files = await this.filesApi.getFilesByDocumentID(documentId);
return files
.filter((file: any) => file.type === "html")
.map((file: any) => file.field);
}
/**
* Retrieve translations for a document field name
*
* * returns Slate object for html fields
* * returns all json fields if fieldName is 'fields'
*/
async getTranslation({ documentId, fieldName, locale }: IgetTranslation) {
const articleDirectory = await this.filesApi.getArticleDirectory(
documentId
);
const file = await this.filesApi.getFile(fieldName, articleDirectory.id);
// it is possible a file doesn't exist yet - e.g. an article with localized text fields that contains an empty html field.
if (!file) {
return;
}
try {
const response = await this.translationsApi.buildProjectFileTranslation(
this.projectId,
file.originalId,
{
targetLanguageId: this.localeMap[locale].crowdinId,
}
);
const data = await this.getFileDataFromUrl(response.data.url);
return file.type === "html"
? htmlToSlate(data, payloadHtmlToSlateConfig)
: JSON.parse(data);
} catch (error) {
console.log(error);
}
}
private async getFileDataFromUrl(url: string) {
const response = await fetch(url);
const body = await response.text();
return body;
}
/**
* Restore id and blockType to translations
*
* In order to update a document, we need to know the id and blockType of each block.
*
* Ideally, id and blockType are not sent to Crowdin - hence
* we need to restore them from the original document.
*
* This currently only works for a top-level `layout` blocks field.
*
* TODO: make this work for nested blocks.
*/
restoreIdAndBlockType = (
document: any,
translations: any,
key: string = "layout"
) => {
if (translations.hasOwnProperty(key)) {
translations[key] = translations[key].map(
(block: any, index: number) => ({
...block,
id: document[key][index].id,
blockType: document[key][index].blockType,
})
);
}
return translations;
};
}
| src/api/payload-crowdin-sync/translations.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " const { sourceFilesApi, uploadStorageApi } = new crowdin(credentials);\n this.projectId = pluginOptions.projectId;\n this.directoryId = pluginOptions.directoryId;\n this.sourceFilesApi =\n process.env.NODE_ENV === \"test\"\n ? (mockCrowdinClient(pluginOptions) as any)\n : sourceFilesApi;\n this.uploadStorageApi =\n process.env.NODE_ENV === \"test\"\n ? (mockCrowdinClient(pluginOptions) as any)",
"score": 0.9301525354385376
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " sourceFilesApi: SourceFiles;\n uploadStorageApi: UploadStorage;\n projectId: number;\n directoryId?: number;\n payload: Payload;\n constructor(pluginOptions: PluginOptions, payload: Payload) {\n // credentials\n const credentials: Credentials = {\n token: pluginOptions.token,\n };",
"score": 0.8156653642654419
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " },\n });\n if (query.totalDocs === 0) {\n // Create collection directory on Crowdin\n const crowdinDirectory = await this.sourceFilesApi.createDirectory(\n this.projectId,\n {\n directoryId: this.directoryId,\n name: collectionSlug,\n title: toWords(collectionSlug), // is this transformed value available on the collection object?",
"score": 0.8109180927276611
},
{
"filename": "src/api/mock/crowdin-client.ts",
"retrieved_chunk": " directoryId?: number;\n branchId: number;\n constructor(pluginOptions: PluginOptions) {\n this.projectId = pluginOptions.projectId;\n this.directoryId = pluginOptions.directoryId;\n this.branchId = 4;\n }\n async listFileRevisions(projectId: number, fileId: number) {\n return await Promise.resolve(1).then(() => undefined);\n }",
"score": 0.8052509427070618
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " } else {\n const crowdinPayloadCollectionDirectory =\n await this.findOrCreateCollectionDirectory({\n collectionSlug: global ? \"globals\" : collectionSlug,\n });\n // Create article directory on Crowdin\n const crowdinDirectory = await this.sourceFilesApi.createDirectory(\n this.projectId,\n {\n directoryId: crowdinPayloadCollectionDirectory.originalId,",
"score": 0.8051137328147888
}
] | typescript | (mockCrowdinClient(pluginOptions) as any)
: translationsApi; |
import crowdin, {
Credentials,
Translations,
} from "@crowdin/crowdin-api-client";
import { payloadCrowdinSyncFilesApi } from "./files";
import { mockCrowdinClient } from "../mock/crowdin-client";
import { Payload } from "payload";
import { PluginOptions } from "../../types";
import deepEqual from "deep-equal";
import {
CollectionConfig,
GlobalConfig,
SanitizedCollectionConfig,
SanitizedGlobalConfig,
} from "payload/types";
import { htmlToSlate, payloadHtmlToSlateConfig } from "slate-serializers";
import {
getLocalizedFields,
getFieldSlugs,
buildCrowdinJsonObject,
buildCrowdinHtmlObject,
buildPayloadUpdateObject,
getLocalizedRequiredFields,
} from "../../utilities";
interface IgetLatestDocumentTranslation {
collection: string;
doc: any;
locale: string;
global?: boolean;
}
interface IgetCurrentDocumentTranslation {
doc: any;
collection: string;
locale: string;
global?: boolean;
}
interface IgetTranslation {
documentId: string;
fieldName: string;
locale: string;
global?: boolean;
}
interface IupdateTranslation {
documentId: string;
collection: string;
dryRun?: boolean;
global?: boolean;
excludeLocales?: string[];
}
export class payloadCrowdinSyncTranslationsApi {
translationsApi: Translations;
filesApi: payloadCrowdinSyncFilesApi; // our wrapper for file operations
projectId: number;
directoryId?: number;
payload: Payload;
localeMap: PluginOptions["localeMap"];
sourceLocale: PluginOptions["sourceLocale"];
constructor(pluginOptions: PluginOptions, payload: Payload) {
// credentials
const credentials: Credentials = {
token: pluginOptions.token,
};
const { translationsApi } = new crowdin(credentials);
this.projectId = pluginOptions.projectId;
this.directoryId = pluginOptions.directoryId;
this.translationsApi =
process.env.NODE_ENV === "test"
? (mockCrowdinClient(pluginOptions) as any)
: translationsApi;
this.filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, payload);
this.payload = payload;
this.localeMap = pluginOptions.localeMap;
this.sourceLocale = pluginOptions.sourceLocale;
}
async updateTranslation({
documentId,
collection,
dryRun = true,
global = false,
excludeLocales = [],
}: IupdateTranslation) {
/**
* Get existing document
*
* * check document exists
* * check for `meta` field (which can be added by @payloadcms/seo)
*
*/
let doc: { crowdinArticleDirectory: { id: any } };
if (global) {
doc = await this.payload.findGlobal({
slug: collection,
locale: this.sourceLocale,
});
} else {
doc = await this.payload.findByID({
collection: collection,
id: documentId,
locale: this.sourceLocale,
});
}
const report: { [key: string]: any } = {};
for (const locale of Object.keys(this.localeMap)) {
if (excludeLocales.includes(locale)) {
continue;
}
report[locale] = {};
report[locale].currentTranslations =
await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
report[locale].latestTranslations =
await this.getLatestDocumentTranslation({
collection: collection,
doc: doc,
locale: locale,
global,
});
report[locale].changed = !deepEqual(
report[locale].currentTranslations,
report[locale].latestTranslations
);
if (report[locale].changed && !dryRun) {
if (global) {
try {
await this.payload.updateGlobal({
slug: collection,
locale: locale,
data: {
...report[locale].latestTranslations,
// error on update without the following line.
// see https://github.com/thompsonsj/payload-crowdin-sync/pull/13/files#r1209271660
crowdinArticleDirectory: doc.crowdinArticleDirectory.id,
},
});
} catch (error) {
console.log(error);
}
} else {
try {
await this.payload.update({
collection: collection,
locale: locale,
id: documentId,
data: report[locale].latestTranslations,
});
} catch (error) {
console.log(error);
}
}
}
}
return {
source: doc,
translations: { ...report },
};
}
getCollectionConfig(
collection: string,
global: boolean
): CollectionConfig | GlobalConfig {
let collectionConfig:
| SanitizedGlobalConfig
| SanitizedCollectionConfig
| undefined;
if (global) {
collectionConfig = this.payload.config.globals.find(
(col: GlobalConfig) => col.slug === collection
);
} else {
collectionConfig = this.payload.config.collections.find(
(col: CollectionConfig) => col.slug === collection
);
}
if (!collectionConfig)
throw new Error(`Collection ${collection} not found in payload config`);
return collectionConfig;
}
async getCurrentDocumentTranslation({
doc,
collection,
locale,
global = false,
}: IgetCurrentDocumentTranslation) {
// get document
let document: any;
if (global) {
document = await this.payload.findGlobal({
slug: collection,
locale: locale,
});
} else {
document = await this.payload.findByID({
collection: collection,
id: doc.id,
locale: locale,
});
}
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
// build crowdin json object
const crowdinJsonObject = buildCrowdinJsonObject({
doc: document,
fields: localizedFields,
});
const crowdinHtmlObject = buildCrowdinHtmlObject({
doc: document,
fields: localizedFields,
});
try {
const docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document,
});
return docTranslations;
} catch (error) {
console.log(error);
throw new Error(`${error}`);
}
}
/**
* Retrieve translations from Crowdin for a document in a given locale
*/
async getLatestDocumentTranslation({
collection,
doc,
locale,
global = false,
}: IgetLatestDocumentTranslation) {
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
if (!localizedFields) {
return { message: "no localized fields" };
}
let docTranslations: { [key: string]: any } = {};
// add json fields
const crowdinJsonObject =
(await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: "fields",
locale: locale,
})) || {};
// add html fields
const localizedHtmlFields = await this.getHtmlFieldSlugs(
global ? collectionConfig.slug : doc.id
);
let crowdinHtmlObject: { [key: string]: any } = {};
for (const field of localizedHtmlFields) {
crowdinHtmlObject[field] = await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: field,
locale: locale,
});
}
docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document: doc,
});
// Add required fields if not present
const requiredFieldSlugs = getFieldSlugs(
getLocalizedRequiredFields(collectionConfig)
);
if (requiredFieldSlugs.length > 0) {
const currentTranslations = await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
requiredFieldSlugs.forEach((slug) => {
if (!docTranslations.hasOwnProperty(slug)) {
docTranslations[slug] = currentTranslations[slug];
}
});
}
return docTranslations;
}
async getHtmlFieldSlugs(documentId: string) {
const files = await this.filesApi.getFilesByDocumentID(documentId);
return files
.filter((file: any) => file.type === "html")
.map((file: any) => file.field);
}
/**
* Retrieve translations for a document field name
*
* * returns Slate object for html fields
* * returns all json fields if fieldName is 'fields'
*/
async getTranslation({ documentId, fieldName, locale }: IgetTranslation) {
const articleDirectory | = await this.filesApi.getArticleDirectory(
documentId
); |
const file = await this.filesApi.getFile(fieldName, articleDirectory.id);
// it is possible a file doesn't exist yet - e.g. an article with localized text fields that contains an empty html field.
if (!file) {
return;
}
try {
const response = await this.translationsApi.buildProjectFileTranslation(
this.projectId,
file.originalId,
{
targetLanguageId: this.localeMap[locale].crowdinId,
}
);
const data = await this.getFileDataFromUrl(response.data.url);
return file.type === "html"
? htmlToSlate(data, payloadHtmlToSlateConfig)
: JSON.parse(data);
} catch (error) {
console.log(error);
}
}
private async getFileDataFromUrl(url: string) {
const response = await fetch(url);
const body = await response.text();
return body;
}
/**
* Restore id and blockType to translations
*
* In order to update a document, we need to know the id and blockType of each block.
*
* Ideally, id and blockType are not sent to Crowdin - hence
* we need to restore them from the original document.
*
* This currently only works for a top-level `layout` blocks field.
*
* TODO: make this work for nested blocks.
*/
restoreIdAndBlockType = (
document: any,
translations: any,
key: string = "layout"
) => {
if (translations.hasOwnProperty(key)) {
translations[key] = translations[key].map(
(block: any, index: number) => ({
...block,
id: document[key][index].id,
blockType: document[key][index].blockType,
})
);
}
return translations;
};
}
| src/api/payload-crowdin-sync/translations.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/helpers.ts",
"retrieved_chunk": " return getFile(name, articleDirectory.id, payload);\n}\nexport async function getFilesByDocumentID(\n documentId: string,\n payload: Payload\n): Promise<IcrowdinFile[]> {\n const articleDirectory = await getArticleDirectory(documentId, payload);\n if (!articleDirectory) {\n // tests call this function to make sure files are deleted\n return [];",
"score": 0.8818296194076538
},
{
"filename": "src/hooks/collections/afterChange.ts",
"retrieved_chunk": " */\n if (!req.locale || req.locale !== pluginOptions.sourceLocale) {\n return doc;\n }\n /**\n * Prepare JSON objects\n *\n * `text` fields are compiled into a single JSON file\n * on Crowdin. Prepare previous and current objects.\n */",
"score": 0.8777556419372559
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": "): any[] => {\n const fields = getLocalizedFields({ fields: collection.fields, type });\n return fields.filter((field) => field.required);\n};\n/**\n * Not yet compatible with nested fields - this means nested HTML\n * field translations cannot be synced from Crowdin.\n */\nexport const getFieldSlugs = (fields: FieldWithName[]): string[] =>\n fields",
"score": 0.8747223019599915
},
{
"filename": "src/hooks/collections/afterChange.ts",
"retrieved_chunk": " */\n const filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, req.payload);\n /**\n * Retrieve the Crowdin Article Directory article\n *\n * Records of Crowdin directories are stored in Payload.\n */\n const articleDirectory = await filesApi.findOrCreateArticleDirectory({\n document: doc,\n collectionSlug: collection.slug,",
"score": 0.873211145401001
},
{
"filename": "src/hooks/collections/afterChange.ts",
"retrieved_chunk": " ) {\n await createOrUpdateJsonFile();\n }\n };\n /**\n * Recursively send rich text fields to Crowdin as HTML\n *\n * Name these HTML files with dot notation. Examples:\n *\n * * `localizedRichTextField`",
"score": 0.8664525747299194
}
] | typescript | = await this.filesApi.getArticleDirectory(
documentId
); |
import crowdin, {
Credentials,
Translations,
} from "@crowdin/crowdin-api-client";
import { payloadCrowdinSyncFilesApi } from "./files";
import { mockCrowdinClient } from "../mock/crowdin-client";
import { Payload } from "payload";
import { PluginOptions } from "../../types";
import deepEqual from "deep-equal";
import {
CollectionConfig,
GlobalConfig,
SanitizedCollectionConfig,
SanitizedGlobalConfig,
} from "payload/types";
import { htmlToSlate, payloadHtmlToSlateConfig } from "slate-serializers";
import {
getLocalizedFields,
getFieldSlugs,
buildCrowdinJsonObject,
buildCrowdinHtmlObject,
buildPayloadUpdateObject,
getLocalizedRequiredFields,
} from "../../utilities";
interface IgetLatestDocumentTranslation {
collection: string;
doc: any;
locale: string;
global?: boolean;
}
interface IgetCurrentDocumentTranslation {
doc: any;
collection: string;
locale: string;
global?: boolean;
}
interface IgetTranslation {
documentId: string;
fieldName: string;
locale: string;
global?: boolean;
}
interface IupdateTranslation {
documentId: string;
collection: string;
dryRun?: boolean;
global?: boolean;
excludeLocales?: string[];
}
export class payloadCrowdinSyncTranslationsApi {
translationsApi: Translations;
filesApi: payloadCrowdinSyncFilesApi; // our wrapper for file operations
projectId: number;
directoryId?: number;
payload: Payload;
localeMap: PluginOptions["localeMap"];
| sourceLocale: PluginOptions["sourceLocale"]; |
constructor(pluginOptions: PluginOptions, payload: Payload) {
// credentials
const credentials: Credentials = {
token: pluginOptions.token,
};
const { translationsApi } = new crowdin(credentials);
this.projectId = pluginOptions.projectId;
this.directoryId = pluginOptions.directoryId;
this.translationsApi =
process.env.NODE_ENV === "test"
? (mockCrowdinClient(pluginOptions) as any)
: translationsApi;
this.filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, payload);
this.payload = payload;
this.localeMap = pluginOptions.localeMap;
this.sourceLocale = pluginOptions.sourceLocale;
}
async updateTranslation({
documentId,
collection,
dryRun = true,
global = false,
excludeLocales = [],
}: IupdateTranslation) {
/**
* Get existing document
*
* * check document exists
* * check for `meta` field (which can be added by @payloadcms/seo)
*
*/
let doc: { crowdinArticleDirectory: { id: any } };
if (global) {
doc = await this.payload.findGlobal({
slug: collection,
locale: this.sourceLocale,
});
} else {
doc = await this.payload.findByID({
collection: collection,
id: documentId,
locale: this.sourceLocale,
});
}
const report: { [key: string]: any } = {};
for (const locale of Object.keys(this.localeMap)) {
if (excludeLocales.includes(locale)) {
continue;
}
report[locale] = {};
report[locale].currentTranslations =
await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
report[locale].latestTranslations =
await this.getLatestDocumentTranslation({
collection: collection,
doc: doc,
locale: locale,
global,
});
report[locale].changed = !deepEqual(
report[locale].currentTranslations,
report[locale].latestTranslations
);
if (report[locale].changed && !dryRun) {
if (global) {
try {
await this.payload.updateGlobal({
slug: collection,
locale: locale,
data: {
...report[locale].latestTranslations,
// error on update without the following line.
// see https://github.com/thompsonsj/payload-crowdin-sync/pull/13/files#r1209271660
crowdinArticleDirectory: doc.crowdinArticleDirectory.id,
},
});
} catch (error) {
console.log(error);
}
} else {
try {
await this.payload.update({
collection: collection,
locale: locale,
id: documentId,
data: report[locale].latestTranslations,
});
} catch (error) {
console.log(error);
}
}
}
}
return {
source: doc,
translations: { ...report },
};
}
getCollectionConfig(
collection: string,
global: boolean
): CollectionConfig | GlobalConfig {
let collectionConfig:
| SanitizedGlobalConfig
| SanitizedCollectionConfig
| undefined;
if (global) {
collectionConfig = this.payload.config.globals.find(
(col: GlobalConfig) => col.slug === collection
);
} else {
collectionConfig = this.payload.config.collections.find(
(col: CollectionConfig) => col.slug === collection
);
}
if (!collectionConfig)
throw new Error(`Collection ${collection} not found in payload config`);
return collectionConfig;
}
async getCurrentDocumentTranslation({
doc,
collection,
locale,
global = false,
}: IgetCurrentDocumentTranslation) {
// get document
let document: any;
if (global) {
document = await this.payload.findGlobal({
slug: collection,
locale: locale,
});
} else {
document = await this.payload.findByID({
collection: collection,
id: doc.id,
locale: locale,
});
}
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
// build crowdin json object
const crowdinJsonObject = buildCrowdinJsonObject({
doc: document,
fields: localizedFields,
});
const crowdinHtmlObject = buildCrowdinHtmlObject({
doc: document,
fields: localizedFields,
});
try {
const docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document,
});
return docTranslations;
} catch (error) {
console.log(error);
throw new Error(`${error}`);
}
}
/**
* Retrieve translations from Crowdin for a document in a given locale
*/
async getLatestDocumentTranslation({
collection,
doc,
locale,
global = false,
}: IgetLatestDocumentTranslation) {
const collectionConfig = this.getCollectionConfig(collection, global);
const localizedFields = getLocalizedFields({
fields: collectionConfig.fields,
});
if (!localizedFields) {
return { message: "no localized fields" };
}
let docTranslations: { [key: string]: any } = {};
// add json fields
const crowdinJsonObject =
(await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: "fields",
locale: locale,
})) || {};
// add html fields
const localizedHtmlFields = await this.getHtmlFieldSlugs(
global ? collectionConfig.slug : doc.id
);
let crowdinHtmlObject: { [key: string]: any } = {};
for (const field of localizedHtmlFields) {
crowdinHtmlObject[field] = await this.getTranslation({
documentId: global ? collectionConfig.slug : doc.id,
fieldName: field,
locale: locale,
});
}
docTranslations = buildPayloadUpdateObject({
crowdinJsonObject,
crowdinHtmlObject,
fields: localizedFields,
document: doc,
});
// Add required fields if not present
const requiredFieldSlugs = getFieldSlugs(
getLocalizedRequiredFields(collectionConfig)
);
if (requiredFieldSlugs.length > 0) {
const currentTranslations = await this.getCurrentDocumentTranslation({
doc: doc,
collection: collection,
locale: locale,
global,
});
requiredFieldSlugs.forEach((slug) => {
if (!docTranslations.hasOwnProperty(slug)) {
docTranslations[slug] = currentTranslations[slug];
}
});
}
return docTranslations;
}
async getHtmlFieldSlugs(documentId: string) {
const files = await this.filesApi.getFilesByDocumentID(documentId);
return files
.filter((file: any) => file.type === "html")
.map((file: any) => file.field);
}
/**
* Retrieve translations for a document field name
*
* * returns Slate object for html fields
* * returns all json fields if fieldName is 'fields'
*/
async getTranslation({ documentId, fieldName, locale }: IgetTranslation) {
const articleDirectory = await this.filesApi.getArticleDirectory(
documentId
);
const file = await this.filesApi.getFile(fieldName, articleDirectory.id);
// it is possible a file doesn't exist yet - e.g. an article with localized text fields that contains an empty html field.
if (!file) {
return;
}
try {
const response = await this.translationsApi.buildProjectFileTranslation(
this.projectId,
file.originalId,
{
targetLanguageId: this.localeMap[locale].crowdinId,
}
);
const data = await this.getFileDataFromUrl(response.data.url);
return file.type === "html"
? htmlToSlate(data, payloadHtmlToSlateConfig)
: JSON.parse(data);
} catch (error) {
console.log(error);
}
}
private async getFileDataFromUrl(url: string) {
const response = await fetch(url);
const body = await response.text();
return body;
}
/**
* Restore id and blockType to translations
*
* In order to update a document, we need to know the id and blockType of each block.
*
* Ideally, id and blockType are not sent to Crowdin - hence
* we need to restore them from the original document.
*
* This currently only works for a top-level `layout` blocks field.
*
* TODO: make this work for nested blocks.
*/
restoreIdAndBlockType = (
document: any,
translations: any,
key: string = "layout"
) => {
if (translations.hasOwnProperty(key)) {
translations[key] = translations[key].map(
(block: any, index: number) => ({
...block,
id: document[key][index].id,
blockType: document[key][index].blockType,
})
);
}
return translations;
};
}
| src/api/payload-crowdin-sync/translations.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": "interface IupdateCrowdinFile extends IcreateOrUpdateFile {\n fileId: number;\n}\ninterface IgetTranslation {\n documentId: string;\n fieldName: string;\n locale: string;\n global?: boolean;\n}\nexport class payloadCrowdinSyncFilesApi {",
"score": 0.8731741309165955
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { Field } from \"payload/types\";\nexport interface CollectionOptions {\n directory?: string;\n}\nexport interface PluginOptions {\n projectId: number;\n /** This should be optional? */\n directoryId?: number;\n token: string;\n //client: crowdinAPIService,",
"score": 0.8582146167755127
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " sourceFilesApi: SourceFiles;\n uploadStorageApi: UploadStorage;\n projectId: number;\n directoryId?: number;\n payload: Payload;\n constructor(pluginOptions: PluginOptions, payload: Payload) {\n // credentials\n const credentials: Credentials = {\n token: pluginOptions.token,\n };",
"score": 0.8266818523406982
},
{
"filename": "src/fields/getFields.ts",
"retrieved_chunk": "import type { CollectionConfig, Field, GlobalConfig } from \"payload/types\";\ninterface Args {\n collection: CollectionConfig | GlobalConfig;\n}\nexport const getFields = ({ collection }: Args): Field[] => {\n const fields = [...collection.fields];\n const crowdinArticleDirectoryField: Field = {\n name: \"crowdinArticleDirectory\",\n type: \"relationship\",\n relationTo: \"crowdin-article-directories\",",
"score": 0.8058179616928101
},
{
"filename": "src/api/mock/crowdin-client.ts",
"retrieved_chunk": " });\n return file;\n }\n async buildProjectFileTranslation(\n projectId: number,\n fileId: number,\n { targetLanguageId }: TranslationsModel.BuildProjectFileTranslationRequest\n ): Promise<\n ResponseObject<TranslationsModel.BuildProjectFileTranslationResponse>\n > {",
"score": 0.7991292476654053
}
] | typescript | sourceLocale: PluginOptions["sourceLocale"]; |
import { oraPromise } from 'ora'
import { ChatGptHelper, GeneratorHelperInterface } from './lib/post-helpers'
import {
PostPrompt,
Post
} from './types'
import { replaceAllPrompts } from './lib/template'
/**
* Class for generating a post. It need a helper class to generate the post
* Each helper class must implement the GeneratorHelperInterface
*/
export class PostGenerator {
private helper : GeneratorHelperInterface
public constructor (helper : GeneratorHelperInterface) {
this.helper = helper
}
public async generate () : Promise<Post> {
return this.helper.isCustom() ? await this.customGenerate() : await this.autoGenerate()
}
/**
* Generate a post using the custom prompt based on a template
*/
private async customGenerate () : Promise<Post> {
const promptContents = []
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
// We remove the first prompt because it is the system prompt
const prompts = this.helper.getPrompt().prompts.slice(1)
// for each prompt, we generate the content
const templatePrompts = prompts.entries()
for (const [index, prompt] of templatePrompts) {
const content = await oraPromise(
this.helper.generateCustomPrompt(prompt),
{
text: `Generating the prompt num. ${index + 1} ...`
}
)
promptContents.push(content)
}
// We replace the prompts by the AI answer in the template content
const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)
const seoInfo = await oraPromise(
this.helper.generateSeoInfo(),
{
text: 'Generating SEO info ...'
}
)
return {
title: seoInfo.h1,
slug: seoInfo.slug,
seoTitle: seoInfo | .seoTitle,
seoDescription: seoInfo.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
} |
}
/**
* Generate a post using the auto mode
*/
private async autoGenerate () : Promise<Post> {
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
const tableOfContent = await oraPromise(
this.helper.generateContentOutline(),
{
text: 'Generating post outline ...'
}
)
let content = await oraPromise(
this.helper.generateIntroduction(),
{
text: 'Generating introduction...'
}
)
content += await oraPromise(
this.helper.generateHeadingContents(tableOfContent),
{
text: 'Generating content ...'
}
)
if (this.helper.getPrompt().withConclusion) {
content += await oraPromise(
this.helper.generateConclusion(),
{
text: 'Generating conclusion...'
}
)
}
return {
title: tableOfContent.title,
slug: tableOfContent.slug,
seoTitle: tableOfContent.seoTitle,
seoDescription: tableOfContent.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
}
}
}
/**
* Class for generating a post using the OpenAI API
*/
export class OpenAIPostGenerator extends PostGenerator {
public constructor (postPrompt : PostPrompt) {
super(new ChatGptHelper(postPrompt))
}
}
| src/post.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/wp/wp-api.ts",
"retrieved_chunk": " if (response.data.length === 0) {\n throw new Error(`Post with ${slug} not found`)\n }\n const postId: number = response.data[0].id\n const updatedPost : UpdatePost = {\n content: newContent.content,\n title: newContent.title,\n meta: {\n yoast_wpseo_title: newContent.seoTitle,\n yoast_wpseo_metadesc: newContent.seoDescription",
"score": 0.7769627571105957
},
{
"filename": "src/types.ts",
"retrieved_chunk": "}\nexport type SeoInfo = {\n h1 : string\n slug : string\n seoTitle : string\n seoDescription : string\n}\nexport type AudienceIntentInfo = {\n audience : string\n intent : string",
"score": 0.7427002191543579
},
{
"filename": "src/types.ts",
"retrieved_chunk": "}\nexport type Post = {\n title : string\n content : string\n seoTitle : string\n seoDescription : string\n slug : string,\n categories? : number[],\n status? : string,\n totalTokens : TotalTokens",
"score": 0.7191040515899658
},
{
"filename": "src/lib/extractor.ts",
"retrieved_chunk": " },\n slug: {\n type: 'string'\n },\n seoTitle: {\n type: 'string'\n },\n seoDescription: {\n type: 'string'\n }",
"score": 0.7104098200798035
},
{
"filename": "src/types.ts",
"retrieved_chunk": " title: string\n keywords?: string[]\n headings?: Heading[]\n}\nexport type PostOutline = {\n title: string\n headings : Heading[],\n slug : string,\n seoTitle : string,\n seoDescription : string",
"score": 0.7097113132476807
}
] | typescript | .seoTitle,
seoDescription: seoInfo.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
} |
import { oraPromise } from 'ora'
import { ChatGptHelper, GeneratorHelperInterface } from './lib/post-helpers'
import {
PostPrompt,
Post
} from './types'
import { replaceAllPrompts } from './lib/template'
/**
* Class for generating a post. It need a helper class to generate the post
* Each helper class must implement the GeneratorHelperInterface
*/
export class PostGenerator {
private helper : GeneratorHelperInterface
public constructor (helper : GeneratorHelperInterface) {
this.helper = helper
}
public async generate () : Promise<Post> {
return this.helper.isCustom() ? await this.customGenerate() : await this.autoGenerate()
}
/**
* Generate a post using the custom prompt based on a template
*/
private async customGenerate () : Promise<Post> {
const promptContents = []
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
// We remove the first prompt because it is the system prompt
const prompts = this.helper.getPrompt().prompts.slice(1)
// for each prompt, we generate the content
const templatePrompts = prompts.entries()
for (const [index, prompt] of templatePrompts) {
const content = await oraPromise(
| this.helper.generateCustomPrompt(prompt),
{ |
text: `Generating the prompt num. ${index + 1} ...`
}
)
promptContents.push(content)
}
// We replace the prompts by the AI answer in the template content
const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)
const seoInfo = await oraPromise(
this.helper.generateSeoInfo(),
{
text: 'Generating SEO info ...'
}
)
return {
title: seoInfo.h1,
slug: seoInfo.slug,
seoTitle: seoInfo.seoTitle,
seoDescription: seoInfo.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
}
}
/**
* Generate a post using the auto mode
*/
private async autoGenerate () : Promise<Post> {
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
const tableOfContent = await oraPromise(
this.helper.generateContentOutline(),
{
text: 'Generating post outline ...'
}
)
let content = await oraPromise(
this.helper.generateIntroduction(),
{
text: 'Generating introduction...'
}
)
content += await oraPromise(
this.helper.generateHeadingContents(tableOfContent),
{
text: 'Generating content ...'
}
)
if (this.helper.getPrompt().withConclusion) {
content += await oraPromise(
this.helper.generateConclusion(),
{
text: 'Generating conclusion...'
}
)
}
return {
title: tableOfContent.title,
slug: tableOfContent.slug,
seoTitle: tableOfContent.seoTitle,
seoDescription: tableOfContent.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
}
}
}
/**
* Class for generating a post using the OpenAI API
*/
export class OpenAIPostGenerator extends PostGenerator {
public constructor (postPrompt : PostPrompt) {
super(new ChatGptHelper(postPrompt))
}
}
| src/post.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " // METHODS FOR THE CUSTOM MODE base on a template\n // -----------------------------------------------\n /**\n * Generate a content based on one of prompt defined in the template\n * @param customPrompt : the prompt defined in the template\n * @returns the AI answer\n */\n async generateCustomPrompt (customPrompt : string) {\n this.chatParentMessage = await this.sendRequest(customPrompt, this.completionParams)\n return extractCodeBlock(this.chatParentMessage.text)",
"score": 0.8534557819366455
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " })\n}\nasync function generatePost (options: Options) {\n let answers : any = {}\n if (isInteractive(options)) {\n answers = isCustom(options) ? await askCustomQuestions() : await askQuestions()\n }\n const defaultPostPrompt = buildDefaultPostPrompt()\n const postPrompt : PostPrompt = {\n ...defaultPostPrompt,",
"score": 0.8405506610870361
},
{
"filename": "src/lib/template.ts",
"retrieved_chunk": " let tmpTemplate = replacePrompt(template, 0, '')\n contents.forEach((content, index) => {\n tmpTemplate = replacePrompt(tmpTemplate, index + 1, content)\n })\n return tmpTemplate.trim()\n}",
"score": 0.8331162333488464
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " console.log('---------- PROMPT OUTLINE ----------')\n console.log(prompt)\n }\n // the parent message is the outline for the upcoming content\n // By this way, we can decrease the cost of the API call by minimizing the number of prompt tokens\n // TODO : add an option to disable this feature\n this.chatParentMessage = await this.sendRequest(prompt)\n if (this.postPrompt.debug) {\n console.log('---------- OUTLINE ----------')\n console.log(this.chatParentMessage.text)",
"score": 0.823677122592926
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " async generateConclusion () {\n const response = await this.sendRequest(getPromptForConclusion(), this.completionParams)\n return extractCodeBlock(response.text)\n }\n async generateHeadingContents (postOutline : PostOutline) {\n const headingLevel = 2\n return await this.buildContent(postOutline.headings, headingLevel)\n }\n private async buildContent (headings: Heading[], headingLevel : number, previousContent: string = ''): Promise<string> {\n if (headings.length === 0) {",
"score": 0.818202793598175
}
] | typescript | this.helper.generateCustomPrompt(prompt),
{ |
import { ok } from "assert";
import * as core from "@actions/core";
import { exec } from "@actions/exec";
import { RequestError } from "@octokit/request-error";
import { mkdirP } from "@actions/io";
import { Config } from "./config";
import { getOctokit } from "./octokit";
export async function cloneRepository(config: Config): Promise<void> {
const { syncAuth, syncPath, syncRepository, syncTree } = config;
const tempDirectory = await mkdirP(syncPath);
await exec(
`git clone https://${syncAuth}@${syncRepository} ${syncPath}`,
[],
{
silent: !core.isDebug(),
},
);
await exec(`git fetch`, [], {
cwd: syncPath,
silent: !core.isDebug(),
});
await exec(`git checkout --progress --force ${syncTree}`, [], {
cwd: syncPath,
silent: !core.isDebug(),
});
}
export async function configureRepository(config: Config): Promise<void> {
await exec("git", ["config", "user.email", config.commitUserEmail], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
await exec("git", ["config", "user.name", config.commitUserName], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
await exec("git", ["checkout", "-f", "-b", config.commitBranch], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
}
export async function commitChanges(config: Config): Promise<boolean> {
await exec("git", ["add", "-A"], {
cwd: config.fullPath,
failOnStdErr: false,
ignoreReturnCode: true,
silent: !core.isDebug(),
});
const exitCode = await exec("git", ["commit", "-m", config.commitMessage], {
cwd: config.fullPath,
failOnStdErr: false,
ignoreReturnCode: true,
silent: !core.isDebug(),
});
return exitCode === 0;
}
export async function createPr(config: Config): Promise<void> {
await exec("git", ["push", "-f", "-u", "origin", config.commitBranch], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
ok(process.env.GITHUB_REPOSITORY, "Expected GITHUB_REPOSITORY to be defined");
ok | (config.prToken, "Expected PR_TOKEN to be defined"); |
const [owner, repo] = process.env.GITHUB_REPOSITORY.split("/");
const octokit = getOctokit(config.prToken);
const { data: repository } = await octokit.rest.repos.get({ owner, repo });
for (const name of config.prLabels) {
core.debug(`Creating issue label ${name}`);
try {
await octokit.rest.issues.createLabel({ owner, repo, name });
} catch (err) {
if (err instanceof RequestError && err.status === 422) {
core.debug(`Issue label ${name} already exists`);
} else {
throw err;
}
}
}
try {
const res = await octokit.rest.pulls.create({
owner,
repo,
base: repository.default_branch,
body: config.prBody,
head: config.commitBranch,
maintainer_can_modify: true,
title: config.prTitle,
});
await octokit.rest.issues.addLabels({
owner,
repo,
issue_number: res.data.number,
labels: config.prLabels,
});
await octokit.rest.pulls.requestReviewers({
owner,
repo,
pull_number: res.data.number,
reviewers: config.prReviewUsers,
});
core.setOutput("pr-url", res.data.html_url);
} catch (err) {
if (err instanceof RequestError && err.status === 422) {
core.debug("PR already exists");
} else {
throw err;
}
}
}
| src/git.ts | stordco-actions-sync-ca5bdce | [
{
"filename": "src/config.ts",
"retrieved_chunk": " syncRepository: string;\n syncTree: string;\n templateVariables: Record<string, string>;\n};\nexport function getConfig(): Config {\n const path = core.getInput(\"path\", { required: false });\n const workspace = process.env.GITHUB_WORKSPACE;\n ok(workspace, \"Expected GITHUB_WORKSPACE to be defined\");\n return {\n commitBranch: core.getInput(\"commit-branch\", { required: true }),",
"score": 0.8422271013259888
},
{
"filename": "src/templates.test.ts",
"retrieved_chunk": "describe.concurrent(\"templates\", () => {\n beforeEach<LocalTestContext>(async (ctx) => {\n const fullPath = await mkdtemp(join(tmpdir(), \"actions-sync\"));\n ctx.config = {\n commitBranch: \"main\",\n commitMessage: \"commit message\",\n commitUserEmail: \"[email protected]\",\n commitUserName: \"testing\",\n fullPath,\n path: \"\",",
"score": 0.7639439105987549
},
{
"filename": "src/scripts.ts",
"retrieved_chunk": " ...config.templateVariables,\n SYNC_BRANCH: config.syncTree,\n SYNC_PATH: config.syncPath,\n SYNC_REPOSITORY: config.syncRepository,\n SYNC_TREE: config.syncTree,\n TEMPLATE_ENV: outputFilePath,\n },\n silent: false,\n failOnStdErr: false,\n ignoreReturnCode: true,",
"score": 0.7411713600158691
},
{
"filename": "src/index.ts",
"retrieved_chunk": "export async function run() {\n const config = getConfig();\n await configureRepository(config);\n await cloneRepository(config);\n await runScripts(config);\n await templateFiles(config);\n if (config.prEnabled) {\n const hasChanges = await commitChanges(config);\n if (hasChanges === false) {\n core.info(\"No changes to commit.\");",
"score": 0.7286918759346008
},
{
"filename": "src/scripts.ts",
"retrieved_chunk": " scriptPath: string,\n config: Config,\n): Promise<Record<string, string>> {\n const outputFilePath = createTempPath();\n const io = await open(outputFilePath, \"a\");\n await io.close();\n await exec(scriptPath, [], {\n cwd: config.fullPath,\n env: {\n ...process.env,",
"score": 0.7273099422454834
}
] | typescript | (config.prToken, "Expected PR_TOKEN to be defined"); |
import { PostPrompt } from '../types'
const STRUCTURE_OUTLINE = 'Generate the blog post outline with the following JSON format: ' +
'{"title": "", // Add the post title here ' +
'"headings" : [ { "title": "", // Add the heading title here ' +
'"keywords": ["...", "...", "...", "..."], // Add a list of keywords here. They will help to generate the final content of this heading.' +
'"headings": [ // If necessary, add subheadings here. This is optional.' +
'{ "title": "", ' + '"keywords": ["...", "..."] },' +
'{ "title": "", "keywords": ["...", "..."] }, ... ] } ... ],' +
'"slug" : "", // Use the main keywords for the slug based on the topic of the post. Do not mention the country. Max 3 or 4 keywords, without stop words and with text normalization and accent stripping.' +
'"seoTitle" : "", // Not the same as the post title, max 60 characters, do not mention the country.' +
'"seoDescription : "" // Max 155 characters }'
const INFORMATIVE_INTRO_PROMPT = 'Compose the introduction for this blog post topic, without using phrases such as, "In this article,..." to introduce the subject.' +
'Instead, explain the context and/or explain the main problem. If necessary, mention facts to help the user better understand the context or the problem. Do not describe or introduce the content of the different headings of the outline.' +
'Do not add a heading. Your responses should be in the markdown format. Do not add the title in the beginning of the introduction.'
const CAPTIVATING_INTO_PROMPT = 'Compose a captivating introduction for this blog post topic, without using phrases such as, "In this article,..." to introduce the subject.' +
'Instead, focus on creating a hook to capture the reader\'s attention, setting the tone and style, and seamlessly leading the reader into the main content of the article.' +
'Your introduction should entice readers to continue reading the article and learn more about the subject presented.' +
' Do not add a heading. Your responses should be in the markdown format. Do not add the title in the beginning of the introduction.'
// ------------------------------------------------------
// PROMPTS FOR THE INTERACTIVE / AUTO MODE
// ------------------------------------------------------
export function getAutoSystemPrompt (postPrompt : PostPrompt) {
return 'You are a copywriter with a strong expertise in SEO. I need a detailed blog post in ' + postPrompt.language + ' about the topic: "' + postPrompt.topic + '".' +
'Do not add a paragraph summarizing your response/explanation at the end of your answers.'
}
export function getPromptForIntentAudience (postPrompt : PostPrompt) {
return 'For a post based on the topic : ' + postPrompt.topic + ', describe the ideal audience and intent for this topic.' +
'Write maximum 3 statements for the audience and also 3 statements for the intent.' +
'Your response should be only the following object in json format : ' +
'{"audience" : "", "intent": ""}'
}
export function getPromptForOutline (postPrompt : PostPrompt) {
const { country, intent, audience } = postPrompt
const prompt = STRUCTURE_OUTLINE +
'For the title and headings, do not capitalize words unless the first one.' +
'Please make sure your title is clear, concise, and accurately represents the topic of the post.' +
'Do not add a heading for an introduction, conclusion, or to summarize the article.' +
(country ? 'Market/country/region:' + country + '.' : '') +
(audience ? 'Audience: ' + audience + '.' : '') +
(intent ? 'Content intent: ' + intent + '.' : '')
return prompt
}
export function getPromptForMainKeyword () {
const prompt = 'Give me the most important SEO keyword in a JSON array in which each item matches a word without the stop words.'
return prompt
}
export function getPromptForIntroduction (postPrompt : PostPrompt) {
return (!postPrompt.tone) || postPrompt.tone === 'informative' ? INFORMATIVE_INTRO_PROMPT : CAPTIVATING_INTO_PROMPT
}
export function getPromptForHeading (tone : string, title : string, keywords : string[] | null) {
return tone === 'informative' ? getPromptForInformativeHeading(title, keywords) : getPromptForCaptivatingHeading(title, keywords)
}
export function getPromptForConclusion () {
return 'Write a compelling conclusion for this blog post topic without using transitional phrases such as, "In conclusion", "In summary", "In short", "So", "Thus", or any other transitional expressions.' +
'Focus on summarizing the main points of the post, emphasizing the significance of the topic, and leaving the reader with a lasting impression or a thought-provoking final remark.' +
'Ensure that your conclusion effectively wraps up the article and reinforces the central message or insights presented in the blog post.' +
'Do not add a heading. Your responses should be in the markdown format.'
}
function getPromptForInformativeHeading (title : string, keywords : string[] | null) {
const promptAboutKeywords = keywords ? ' based on the following list of keywords: ' + keywords.join(', ') + '.' : ''
return 'Write some informative content for the heading (without the heading) "' + title + '"' + promptAboutKeywords +
'Make sure to provide in-depth information and valuable insights. Use clear and concise language, along with relevant examples or anecdotes if needed.' +
'Do not start the first sentence with the heading. Instead, start with a sentence that introduces and provides context for the heading.' +
'I do not want a conclusion or summary at the end of the generated text. Just the information requested. ' +
'This rule applies to all languages. ' +
'So do not add a paragraph at the end of your text beginning with one of the following words or variants: in conclusion, in sum, to conclude, in summary, ... ' +
'Your response should be in the markdown format.'
}
function getPromptForCaptivatingHeading (title : string, keywords : string[] | null) {
const promptAboutKeywords = keywords ? ' based on the following list of keywords: ' + keywords.join(', ') + '.' : ''
return 'Write some captivating content for the heading (without the heading): "' + title + '"' + promptAboutKeywords +
'Make sure to provide in-depth information and valuable insights. Use clear and concise language, along with relevant examples or anecdotes, to engage the reader and enhance their understanding.' +
'Do not start the first sentence with the heading. Instead, start with a sentence that introduces and provides context for the heading.' +
'I do not want a conclusion or summary at the end of the generated text. Just the information requested. ' +
'This rule applies to all languages. ' +
'So do not add a paragraph at the end of your text beginning with one of the following words or variants: in conclusion, in sum, to conclude, in summary, ... ' +
'Your response should be in the markdown format.'
}
// ------------------------------------------------------
// PROMPTS FOR THE CUSTOM MODE (based on a template)
// ------------------------------------------------------
export function getCustomSystemPrompt (postPrompt : PostPrompt) {
// The prompt with the index 0 in the template is the system prompt
| return postPrompt.prompts[0] + '\n' + ' Language: ' + postPrompt.language + '. '
} |
export function getSeoSystemPrompt (postPrompt : PostPrompt) {
return 'You are a SEO expert and you need to optimize a web page based on the following info in ' + postPrompt.language + ': ' +
'\n' + postPrompt.prompts[0]
}
export function getPromptForSeoInfo (postPrompt : PostPrompt) {
return 'For content based on the topic of this conversation, Use the H1 provided in the system prompt. If not, write a new H1. ' +
'Use the slug provided in the system prompt. If not, write a new slug.' +
'Write an SEO title and an SEO description for this blog post.' +
'The SEO title should be no more than 60 characters long.' +
'The H1 and the title should be different.' +
'The SEO description should be no more than 155 characters long.' +
'Use the main keywords for the slug based on the topic of the post. Do not mention the country. Max 3 or 4 keywords, without stop words, and with text normalization and accent stripping.' +
'Your response should be in the JSON format based on the following structure: ' +
'{"h1" : "", "seoTitle": "", "": "seoDescription": "", "slug": ""}'
}
| src/lib/prompts.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " // METHODS FOR THE CUSTOM MODE base on a template\n // -----------------------------------------------\n /**\n * Generate a content based on one of prompt defined in the template\n * @param customPrompt : the prompt defined in the template\n * @returns the AI answer\n */\n async generateCustomPrompt (customPrompt : string) {\n this.chatParentMessage = await this.sendRequest(customPrompt, this.completionParams)\n return extractCodeBlock(this.chatParentMessage.text)",
"score": 0.8598071932792664
},
{
"filename": "src/post.ts",
"retrieved_chunk": " * Generate a post using the custom prompt based on a template\n */\n private async customGenerate () : Promise<Post> {\n const promptContents = []\n await oraPromise(\n this.helper.init(),\n {\n text: ' Init the completion parameters ...'\n }\n )",
"score": 0.8583331108093262
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " console.log('---------- PROMPT OUTLINE ----------')\n console.log(prompt)\n }\n // the parent message is the outline for the upcoming content\n // By this way, we can decrease the cost of the API call by minimizing the number of prompt tokens\n // TODO : add an option to disable this feature\n this.chatParentMessage = await this.sendRequest(prompt)\n if (this.postPrompt.debug) {\n console.log('---------- OUTLINE ----------')\n console.log(this.chatParentMessage.text)",
"score": 0.8401201963424683
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": "/**\n * Helper implementation for generating a post using the ChatGPT API\n * @class\n */\nexport class ChatGptHelper implements GeneratorHelperInterface {\n private postPrompt : PostPrompt\n private api : ChatGPTAPI\n // The parent message is either the previous one in the conversation (if a template is used)\n // or the generated outline (if we are in auto mode)\n private chatParentMessage : ChatMessage",
"score": 0.8357690572738647
},
{
"filename": "src/post.ts",
"retrieved_chunk": " // We remove the first prompt because it is the system prompt\n const prompts = this.helper.getPrompt().prompts.slice(1)\n // for each prompt, we generate the content\n const templatePrompts = prompts.entries()\n for (const [index, prompt] of templatePrompts) {\n const content = await oraPromise(\n this.helper.generateCustomPrompt(prompt),\n {\n text: `Generating the prompt num. ${index + 1} ...`\n }",
"score": 0.8354704976081848
}
] | typescript | return postPrompt.prompts[0] + '\n' + ' Language: ' + postPrompt.language + '. '
} |
import { ok } from "assert";
import * as core from "@actions/core";
import { exec } from "@actions/exec";
import { RequestError } from "@octokit/request-error";
import { mkdirP } from "@actions/io";
import { Config } from "./config";
import { getOctokit } from "./octokit";
export async function cloneRepository(config: Config): Promise<void> {
const { syncAuth, syncPath, syncRepository, syncTree } = config;
const tempDirectory = await mkdirP(syncPath);
await exec(
`git clone https://${syncAuth}@${syncRepository} ${syncPath}`,
[],
{
silent: !core.isDebug(),
},
);
await exec(`git fetch`, [], {
cwd: syncPath,
silent: !core.isDebug(),
});
await exec(`git checkout --progress --force ${syncTree}`, [], {
cwd: syncPath,
silent: !core.isDebug(),
});
}
export async function configureRepository(config: Config): Promise<void> {
await exec("git", ["config", "user.email", config.commitUserEmail], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
await exec("git", ["config", "user.name", config.commitUserName], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
await exec("git", ["checkout", "-f", "-b", config.commitBranch], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
}
export async function commitChanges(config: Config): Promise<boolean> {
await exec("git", ["add", "-A"], {
cwd: config.fullPath,
failOnStdErr: false,
ignoreReturnCode: true,
silent: !core.isDebug(),
});
const exitCode = await exec("git", ["commit", "-m", config.commitMessage], {
cwd: config.fullPath,
failOnStdErr: false,
ignoreReturnCode: true,
silent: !core.isDebug(),
});
return exitCode === 0;
}
export async function createPr(config: Config): Promise<void> {
await exec("git", ["push", "-f", "-u", "origin", config.commitBranch], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
ok(process.env.GITHUB_REPOSITORY, "Expected GITHUB_REPOSITORY to be defined");
ok(config.prToken, "Expected PR_TOKEN to be defined");
const [owner, repo] = process.env.GITHUB_REPOSITORY.split("/");
const octokit = getOctokit(config.prToken);
const { data: repository } = await octokit.rest.repos.get({ owner, repo });
for (const name of config.prLabels) {
core.debug(`Creating issue label ${name}`);
try {
await octokit.rest.issues.createLabel({ owner, repo, name });
} catch (err) {
if (err instanceof RequestError && err.status === 422) {
core.debug(`Issue label ${name} already exists`);
} else {
throw err;
}
}
}
try {
const res = await octokit.rest.pulls.create({
owner,
repo,
base: repository.default_branch,
| body: config.prBody,
head: config.commitBranch,
maintainer_can_modify: true,
title: config.prTitle,
}); |
await octokit.rest.issues.addLabels({
owner,
repo,
issue_number: res.data.number,
labels: config.prLabels,
});
await octokit.rest.pulls.requestReviewers({
owner,
repo,
pull_number: res.data.number,
reviewers: config.prReviewUsers,
});
core.setOutput("pr-url", res.data.html_url);
} catch (err) {
if (err instanceof RequestError && err.status === 422) {
core.debug("PR already exists");
} else {
throw err;
}
}
}
| src/git.ts | stordco-actions-sync-ca5bdce | [
{
"filename": "src/config.ts",
"retrieved_chunk": " commitMessage: core.getInput(\"commit-message\", { required: true }),\n commitUserEmail: core.getInput(\"commit-user-email\", { required: true }),\n commitUserName: core.getInput(\"commit-user-name\", { required: true }),\n fullPath: join(workspace, path),\n path: path,\n prBody: core.getInput(\"pr-body\", { required: false }),\n prEnabled: core.getBooleanInput(\"pr-enabled\", { required: true }),\n prLabels: core.getMultilineInput(\"pr-labels\", { required: false }),\n prReviewUsers: core.getMultilineInput(\"pr-review-users\", {\n required: false,",
"score": 0.721599817276001
},
{
"filename": "src/templates.test.ts",
"retrieved_chunk": "describe.concurrent(\"templates\", () => {\n beforeEach<LocalTestContext>(async (ctx) => {\n const fullPath = await mkdtemp(join(tmpdir(), \"actions-sync\"));\n ctx.config = {\n commitBranch: \"main\",\n commitMessage: \"commit message\",\n commitUserEmail: \"[email protected]\",\n commitUserName: \"testing\",\n fullPath,\n path: \"\",",
"score": 0.714604377746582
},
{
"filename": "src/templates.test.ts",
"retrieved_chunk": " prAssignee: \"\",\n prBody: \"testing\",\n prEnabled: false,\n prLabels: [],\n prReviewUsers: [],\n prTitle: \"testing\",\n syncAuth: \"\",\n syncBranch: \"main\",\n syncPath: resolve(__dirname, \"../test/fixtures\"),\n syncRepository: \"test/test\",",
"score": 0.7107183933258057
},
{
"filename": "src/config.ts",
"retrieved_chunk": " }),\n prTitle: core.getInput(\"pr-title\", { required: true }),\n prToken: core.getInput(\"pr-token\", { required: false }),\n syncAuth: core.getInput(\"sync-auth\", { required: false }),\n syncPath: createTempPath(),\n syncRepository: core.getInput(\"sync-repository\", { required: true }),\n syncTree:\n core.getInput(\"sync-branch\", { required: false }) ||\n core.getInput(\"sync-tree\", { required: true }),\n templateVariables: {},",
"score": 0.6929792165756226
},
{
"filename": "src/octokit.ts",
"retrieved_chunk": " octokit.log.info(`Retrying after ${retryAfter} seconds`);\n return true;\n}\nexport function getOctokit(token: string) {\n return upstreamOctokit(\n token,\n {\n retry: {\n enabled: true,\n },",
"score": 0.6754122972488403
}
] | typescript | body: config.prBody,
head: config.commitBranch,
maintainer_can_modify: true,
title: config.prTitle,
}); |
import * as dotenv from 'dotenv'
import { readFile as rd } from 'fs'
import { promisify } from 'util'
import { ChatGPTAPI, ChatGPTError, ChatMessage, SendMessageOptions } from 'chatgpt'
import pRetry, { AbortError, FailedAttemptError } from 'p-retry'
import { extractJsonArray, extractCodeBlock, extractPostOutlineFromCodeBlock, extractSeoInfo, extractAudienceIntentInfo } from './extractor'
import {
getPromptForMainKeyword,
getPromptForOutline,
getPromptForIntroduction,
getPromptForHeading,
getPromptForConclusion,
getAutoSystemPrompt,
getPromptForSeoInfo,
getCustomSystemPrompt,
getSeoSystemPrompt,
getPromptForIntentAudience as getPromptForAudienceIntent
} from './prompts'
import {
Heading,
PostOutline,
PostPrompt,
TotalTokens,
SeoInfo
} from '../types'
import { encode } from './tokenizer'
import { extractPrompts } from './template'
import { log } from 'console'
import { NoApiKeyError } from './errors'
dotenv.config()
const readFile = promisify(rd)
/**
* Specific Open AI API parameters for the completion
*/
export type CompletionParams = {
temperature?: number | null,
top_p?: number | null,
max_tokens?: number,
presence_penalty?: number | null,
frequency_penalty?: number | null,
logit_bias?: object | null,
}
/**
* Interface for the helper class for generating a post. it defines how to generate a post
* Each helper class must implement this interface
* @interface
*/
export interface GeneratorHelperInterface {
init () : Promise<void>
isCustom() : boolean
generateContentOutline () : Promise<PostOutline>
generateMainKeyword () : Promise<string[]>
generateIntroduction () : Promise<string>
generateConclusion () : Promise<string>
generateHeadingContents (tableOfContent : PostOutline) : Promise<string>
generateCustomPrompt(prompt : string) : Promise<string>
generateSeoInfo () : Promise<SeoInfo>
getTotalTokens() : TotalTokens
getPrompt() : PostPrompt
}
/**
* Helper implementation for generating a post using the ChatGPT API
* @class
*/
export class ChatGptHelper implements GeneratorHelperInterface {
private postPrompt : PostPrompt
private api : ChatGPTAPI
// The parent message is either the previous one in the conversation (if a template is used)
// or the generated outline (if we are in auto mode)
private chatParentMessage : ChatMessage
private completionParams : CompletionParams
private totalTokens : TotalTokens = {
promptTokens: 0,
completionTokens: 0,
total: 0
}
// -----------------------------------------------
// CONSTRUCTOR AND INITIALIZATION
// -----------------------------------------------
public constructor (postPrompt : PostPrompt) {
this.postPrompt = postPrompt
}
isCustom () : boolean {
return this.postPrompt?.templateFile !== undefined
}
getPrompt (): PostPrompt {
return this.postPrompt
}
getTotalTokens (): TotalTokens {
return this.totalTokens
}
async init () {
if (this.isCustom()) {
if (this.postPrompt.debug) {
console.log(`Use template : ${this.postPrompt.templateFile}`)
}
this.postPrompt.templateContent = await this.readTemplate()
this.postPrompt.prompts = extractPrompts(this.postPrompt.templateContent)
}
const systemMessage = this.isCustom() ? getCustomSystemPrompt(this.postPrompt) : getAutoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemMessage)
}
private async buildChatGPTAPI (systemMessage : string) {
try {
this.api = new ChatGPTAPI({
apiKey: this.postPrompt?.apiKey || process.env.OPENAI_API_KEY,
completionParams: {
model: this.postPrompt.model
},
systemMessage,
debug: this.postPrompt.debugapi
})
} catch (error) {
throw new NoApiKeyError()
}
if (this.postPrompt.debug) {
console.log(`OpenAI API initialized with model : ${this.postPrompt.model}`)
}
this.completionParams = {
temperature: this.postPrompt.temperature ?? 0.8,
frequency_penalty: this.postPrompt.frequencyPenalty ?? 0,
presence_penalty: this.postPrompt.presencePenalty ?? 1
}
if (this.postPrompt.logitBias) {
const mainKwWords = await this.generateMainKeyword()
// set the logit bias in order to force the model to minimize the usage of the main keyword
const logitBiais: Record<number, number> = {}
mainKwWords.forEach((kw) => {
const encoded = encode(kw)
encoded.forEach((element) => {
logitBiais[element] = Number(this.postPrompt.logitBias) || -1
})
})
this.completionParams.logit_bias = logitBiais
}
if (this.postPrompt.debug) {
console.log('---------- COMPLETION PARAMETERS ----------')
console.log('Max Tokens : ' + this.completionParams.max_tokens)
console.log('Temperature : ' + this.completionParams.temperature)
console.log('Frequency Penalty : ' + this.completionParams.frequency_penalty)
console.log('Presence Penalty : ' + this.completionParams.presence_penalty)
console.log('Logit Biais : ' + this.completionParams.logit_bias)
}
}
// -----------------------------------------------
// METHODS FOR THE AUTOMATIC MODE
// -----------------------------------------------
async generateMainKeyword () {
const prompt = getPromptForMainKeyword()
if (this.postPrompt.debug) {
console.log('---------- PROMPT MAIN KEYWORD ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- MAIN KEYWORD ----------')
console.log(response.text)
}
return extractJsonArray(response.text)
}
async generateContentOutline () {
if (this.postPrompt.generate) {
const audienceIntent = await this.generateAudienceIntent()
this.postPrompt = {
...audienceIntent,
...this.postPrompt
}
}
const prompt = getPromptForOutline(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT OUTLINE ----------')
console.log(prompt)
}
// the parent message is the outline for the upcoming content
// By this way, we can decrease the cost of the API call by minimizing the number of prompt tokens
// TODO : add an option to disable this feature
this.chatParentMessage = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- OUTLINE ----------')
console.log(this.chatParentMessage.text)
}
return extractPostOutlineFromCodeBlock(this.chatParentMessage.text)
}
async generateAudienceIntent () {
const prompt = getPromptForAudienceIntent(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT AUDIENCE INTENT ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- AUDIENCE INTENT ----------')
console.log(response.text)
}
return extractAudienceIntentInfo(response.text)
}
async generateIntroduction () {
const response = await this.sendRequest(getPromptForIntroduction(this.postPrompt), this.completionParams)
return | extractCodeBlock(response.text)
} |
async generateConclusion () {
const response = await this.sendRequest(getPromptForConclusion(), this.completionParams)
return extractCodeBlock(response.text)
}
async generateHeadingContents (postOutline : PostOutline) {
const headingLevel = 2
return await this.buildContent(postOutline.headings, headingLevel)
}
private async buildContent (headings: Heading[], headingLevel : number, previousContent: string = ''): Promise<string> {
if (headings.length === 0) {
return previousContent
}
const [currentHeading, ...remainingHeadings] = headings
const mdHeading = Array(headingLevel).fill('#').join('')
let content = previousContent + '\n' + mdHeading + ' ' + currentHeading.title
if (currentHeading.headings && currentHeading.headings.length > 0) {
content = await this.buildContent(currentHeading.headings, headingLevel + 1, content)
} else {
content += '\n' + await this.getContent(currentHeading)
}
return this.buildContent(remainingHeadings, headingLevel, content)
}
private async getContent (heading: Heading): Promise<string> {
if (this.postPrompt.debug) {
console.log(`\nHeading : ${heading.title} ...'\n`)
}
const response = await this.sendRequest(getPromptForHeading(this.postPrompt.tone, heading.title, heading.keywords), this.completionParams)
return `${extractCodeBlock(response.text)}\n`
}
// -----------------------------------------------
// METHODS FOR THE CUSTOM MODE base on a template
// -----------------------------------------------
/**
* Generate a content based on one of prompt defined in the template
* @param customPrompt : the prompt defined in the template
* @returns the AI answer
*/
async generateCustomPrompt (customPrompt : string) {
this.chatParentMessage = await this.sendRequest(customPrompt, this.completionParams)
return extractCodeBlock(this.chatParentMessage.text)
}
/**
* Generate the SEO info for the post based on the template
* @returns the SEO info
*/
async generateSeoInfo (): Promise<SeoInfo> {
const systemPrompt = getSeoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemPrompt)
this.chatParentMessage = await this.sendRequest(getPromptForSeoInfo(this.postPrompt), this.completionParams)
if (this.postPrompt.debug) {
log('---------- SEO INFO ----------')
console.log(this.chatParentMessage.text)
}
return extractSeoInfo(this.chatParentMessage.text)
}
private async readTemplate () : Promise<string> {
const templatePath = this.postPrompt.templateFile
return await readFile(templatePath, 'utf-8')
}
// -----------------------------------------------
// SEND REQUEST TO OPENAI API
// -----------------------------------------------
private async sendRequest (prompt : string, completionParams? : CompletionParams) {
return await pRetry(async () => {
const options : SendMessageOptions = { parentMessageId: this.chatParentMessage?.id }
if (completionParams) {
options.completionParams = completionParams
}
const response = await this.api.sendMessage(prompt, options)
this.totalTokens.promptTokens += response.detail.usage.prompt_tokens
this.totalTokens.completionTokens += response.detail.usage.completion_tokens
this.totalTokens.total += response.detail.usage.total_tokens
return response
}, {
retries: 10,
onFailedAttempt: async (error) => {
this.manageError(error)
}
})
}
private manageError (error: FailedAttemptError) {
if (this.postPrompt.debug) {
console.log('---------- OPENAI REQUEST ERROR ----------')
console.log(error)
}
if (error instanceof ChatGPTError) {
const chatGPTError = error as ChatGPTError
if (chatGPTError.statusCode === 401) {
console.log('OpenAI API Error : Invalid API key: please check your API key in the option -k or in the OPENAI_API_KEY env var.')
process.exit(1)
}
if (chatGPTError.statusCode === 404) {
console.log(`OpenAI API Error : Invalid model for your OpenAI subscription. Check if you can use : ${this.postPrompt.model}.`)
console.log(this.postPrompt.model === 'gpt-4' || this.postPrompt.model === 'gpt-4-32k' ? 'You need to join the waiting list to use the GPT-4 API : https://openai.com/waitlist/gpt-4-api' : '')
process.exit(1)
}
}
if (error instanceof AbortError) {
console.log(`OpenAI API - Request aborted. ${error.message}`)
} else {
console.log(`OpenAI API - Request failed - Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left. ${error.message}`)
}
}
}
| src/lib/post-helpers.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/post.ts",
"retrieved_chunk": " )\n promptContents.push(content)\n }\n // We replace the prompts by the AI answer in the template content\n const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)\n const seoInfo = await oraPromise(\n this.helper.generateSeoInfo(),\n {\n text: 'Generating SEO info ...'\n }",
"score": 0.8068490028381348
},
{
"filename": "src/post.ts",
"retrieved_chunk": " const tableOfContent = await oraPromise(\n this.helper.generateContentOutline(),\n {\n text: 'Generating post outline ...'\n }\n )\n let content = await oraPromise(\n this.helper.generateIntroduction(),\n {\n text: 'Generating introduction...'",
"score": 0.8066839575767517
},
{
"filename": "src/post.ts",
"retrieved_chunk": " }\n )\n content += await oraPromise(\n this.helper.generateHeadingContents(tableOfContent),\n {\n text: 'Generating content ...'\n }\n )\n if (this.helper.getPrompt().withConclusion) {\n content += await oraPromise(",
"score": 0.7930988669395447
},
{
"filename": "src/post.ts",
"retrieved_chunk": " * Generate a post using the custom prompt based on a template\n */\n private async customGenerate () : Promise<Post> {\n const promptContents = []\n await oraPromise(\n this.helper.init(),\n {\n text: ' Init the completion parameters ...'\n }\n )",
"score": 0.7929819822311401
},
{
"filename": "src/lib/prompts.ts",
"retrieved_chunk": " return prompt\n}\nexport function getPromptForMainKeyword () {\n const prompt = 'Give me the most important SEO keyword in a JSON array in which each item matches a word without the stop words.'\n return prompt\n}\nexport function getPromptForIntroduction (postPrompt : PostPrompt) {\n return (!postPrompt.tone) || postPrompt.tone === 'informative' ? INFORMATIVE_INTRO_PROMPT : CAPTIVATING_INTO_PROMPT\n}\nexport function getPromptForHeading (tone : string, title : string, keywords : string[] | null) {",
"score": 0.7902151346206665
}
] | typescript | extractCodeBlock(response.text)
} |
import { oraPromise } from 'ora'
import { ChatGptHelper, GeneratorHelperInterface } from './lib/post-helpers'
import {
PostPrompt,
Post
} from './types'
import { replaceAllPrompts } from './lib/template'
/**
* Class for generating a post. It need a helper class to generate the post
* Each helper class must implement the GeneratorHelperInterface
*/
export class PostGenerator {
private helper : GeneratorHelperInterface
public constructor (helper : GeneratorHelperInterface) {
this.helper = helper
}
public async generate () : Promise<Post> {
return this.helper.isCustom() ? await this.customGenerate() : await this.autoGenerate()
}
/**
* Generate a post using the custom prompt based on a template
*/
private async customGenerate () : Promise<Post> {
const promptContents = []
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
// We remove the first prompt because it is the system prompt
const prompts = this.helper.getPrompt().prompts.slice(1)
// for each prompt, we generate the content
const templatePrompts = prompts.entries()
for (const [index, prompt] of templatePrompts) {
const content = await oraPromise(
this.helper.generateCustomPrompt(prompt),
{
text: `Generating the prompt num. ${index + 1} ...`
}
)
promptContents.push(content)
}
// We replace the prompts by the AI answer in the template content
const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)
const seoInfo = await oraPromise(
this.helper.generateSeoInfo(),
{
text: 'Generating SEO info ...'
}
)
return {
title: seoInfo.h1,
slug: seoInfo.slug,
seoTitle: seoInfo.seoTitle,
seoDescription: seoInfo.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
}
}
/**
* Generate a post using the auto mode
*/
private async autoGenerate () : Promise<Post> {
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
const tableOfContent = await oraPromise(
this.helper.generateContentOutline(),
{
text: 'Generating post outline ...'
}
)
let content = await oraPromise(
this.helper.generateIntroduction(),
{
text: 'Generating introduction...'
}
)
content += await oraPromise(
this.helper.generateHeadingContents(tableOfContent),
{
text: 'Generating content ...'
}
)
if (this.helper.getPrompt().withConclusion) {
content += await oraPromise(
this.helper.generateConclusion(),
{
text: 'Generating conclusion...'
}
)
}
return {
title: tableOfContent.title,
slug: tableOfContent.slug,
seoTitle: tableOfContent.seoTitle,
seoDescription: tableOfContent.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
}
}
}
/**
* Class for generating a post using the OpenAI API
*/
export class OpenAIPostGenerator extends PostGenerator {
public constructor (postPrompt : PostPrompt) {
super | (new ChatGptHelper(postPrompt))
} |
}
| src/post.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": "/**\n * Helper implementation for generating a post using the ChatGPT API\n * @class\n */\nexport class ChatGptHelper implements GeneratorHelperInterface {\n private postPrompt : PostPrompt\n private api : ChatGPTAPI\n // The parent message is either the previous one in the conversation (if a template is used)\n // or the generated outline (if we are in auto mode)\n private chatParentMessage : ChatMessage",
"score": 0.8523451089859009
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " logit_bias?: object | null,\n}\n/**\n * Interface for the helper class for generating a post. it defines how to generate a post\n * Each helper class must implement this interface\n * @interface\n */\nexport interface GeneratorHelperInterface {\n init () : Promise<void>\n isCustom() : boolean",
"score": 0.8418594598770142
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " // METHODS FOR THE CUSTOM MODE base on a template\n // -----------------------------------------------\n /**\n * Generate a content based on one of prompt defined in the template\n * @param customPrompt : the prompt defined in the template\n * @returns the AI answer\n */\n async generateCustomPrompt (customPrompt : string) {\n this.chatParentMessage = await this.sendRequest(customPrompt, this.completionParams)\n return extractCodeBlock(this.chatParentMessage.text)",
"score": 0.8018609285354614
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " this.postPrompt = postPrompt\n }\n isCustom () : boolean {\n return this.postPrompt?.templateFile !== undefined\n }\n getPrompt (): PostPrompt {\n return this.postPrompt\n }\n getTotalTokens (): TotalTokens {\n return this.totalTokens",
"score": 0.7812701463699341
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " ...options,\n ...answers,\n maxModelTokens: answers.model === 'gpt-4' ? 8000 : 4000\n }\n if (!postPrompt.topic) {\n throw new Error('The topic is mandatory, use the option -tp or --topic')\n }\n const postGenerator = new OpenAIPostGenerator(postPrompt)\n const post = await postGenerator.generate()\n const jsonData = {",
"score": 0.7803663611412048
}
] | typescript | (new ChatGptHelper(postPrompt))
} |
import { oraPromise } from 'ora'
import { ChatGptHelper, GeneratorHelperInterface } from './lib/post-helpers'
import {
PostPrompt,
Post
} from './types'
import { replaceAllPrompts } from './lib/template'
/**
* Class for generating a post. It need a helper class to generate the post
* Each helper class must implement the GeneratorHelperInterface
*/
export class PostGenerator {
private helper : GeneratorHelperInterface
public constructor (helper : GeneratorHelperInterface) {
this.helper = helper
}
public async generate () : Promise<Post> {
return this.helper.isCustom() ? await this.customGenerate() : await this.autoGenerate()
}
/**
* Generate a post using the custom prompt based on a template
*/
private async customGenerate () : Promise<Post> {
const promptContents = []
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
// We remove the first prompt because it is the system prompt
const prompts = this.helper.getPrompt().prompts.slice(1)
// for each prompt, we generate the content
const templatePrompts = prompts.entries()
for (const [index, prompt] of templatePrompts) {
const content = await oraPromise(
this.helper.generateCustomPrompt(prompt),
{
text: `Generating the prompt num. ${index + 1} ...`
}
)
promptContents.push(content)
}
// We replace the prompts by the AI answer in the template content
const content = | replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)
const seoInfo = await oraPromise(
this.helper.generateSeoInfo(),
{ |
text: 'Generating SEO info ...'
}
)
return {
title: seoInfo.h1,
slug: seoInfo.slug,
seoTitle: seoInfo.seoTitle,
seoDescription: seoInfo.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
}
}
/**
* Generate a post using the auto mode
*/
private async autoGenerate () : Promise<Post> {
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
const tableOfContent = await oraPromise(
this.helper.generateContentOutline(),
{
text: 'Generating post outline ...'
}
)
let content = await oraPromise(
this.helper.generateIntroduction(),
{
text: 'Generating introduction...'
}
)
content += await oraPromise(
this.helper.generateHeadingContents(tableOfContent),
{
text: 'Generating content ...'
}
)
if (this.helper.getPrompt().withConclusion) {
content += await oraPromise(
this.helper.generateConclusion(),
{
text: 'Generating conclusion...'
}
)
}
return {
title: tableOfContent.title,
slug: tableOfContent.slug,
seoTitle: tableOfContent.seoTitle,
seoDescription: tableOfContent.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
}
}
}
/**
* Class for generating a post using the OpenAI API
*/
export class OpenAIPostGenerator extends PostGenerator {
public constructor (postPrompt : PostPrompt) {
super(new ChatGptHelper(postPrompt))
}
}
| src/post.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " }\n /**\n * Generate the SEO info for the post based on the template\n * @returns the SEO info\n */\n async generateSeoInfo (): Promise<SeoInfo> {\n const systemPrompt = getSeoSystemPrompt(this.postPrompt)\n await this.buildChatGPTAPI(systemPrompt)\n this.chatParentMessage = await this.sendRequest(getPromptForSeoInfo(this.postPrompt), this.completionParams)\n if (this.postPrompt.debug) {",
"score": 0.8586474657058716
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " log('---------- SEO INFO ----------')\n console.log(this.chatParentMessage.text)\n }\n return extractSeoInfo(this.chatParentMessage.text)\n }\n private async readTemplate () : Promise<string> {\n const templatePath = this.postPrompt.templateFile\n return await readFile(templatePath, 'utf-8')\n }\n // -----------------------------------------------",
"score": 0.8426812887191772
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " // METHODS FOR THE CUSTOM MODE base on a template\n // -----------------------------------------------\n /**\n * Generate a content based on one of prompt defined in the template\n * @param customPrompt : the prompt defined in the template\n * @returns the AI answer\n */\n async generateCustomPrompt (customPrompt : string) {\n this.chatParentMessage = await this.sendRequest(customPrompt, this.completionParams)\n return extractCodeBlock(this.chatParentMessage.text)",
"score": 0.83096843957901
},
{
"filename": "src/lib/prompts.ts",
"retrieved_chunk": "// ------------------------------------------------------\nexport function getCustomSystemPrompt (postPrompt : PostPrompt) {\n // The prompt with the index 0 in the template is the system prompt\n return postPrompt.prompts[0] + '\\n' + ' Language: ' + postPrompt.language + '. '\n}\nexport function getSeoSystemPrompt (postPrompt : PostPrompt) {\n return 'You are a SEO expert and you need to optimize a web page based on the following info in ' + postPrompt.language + ': ' +\n '\\n' + postPrompt.prompts[0]\n}\nexport function getPromptForSeoInfo (postPrompt : PostPrompt) {",
"score": 0.8176279067993164
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " })\n}\nasync function generatePost (options: Options) {\n let answers : any = {}\n if (isInteractive(options)) {\n answers = isCustom(options) ? await askCustomQuestions() : await askQuestions()\n }\n const defaultPostPrompt = buildDefaultPostPrompt()\n const postPrompt : PostPrompt = {\n ...defaultPostPrompt,",
"score": 0.8124606609344482
}
] | typescript | replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)
const seoInfo = await oraPromise(
this.helper.generateSeoInfo(),
{ |
import fs from 'fs'
import util from 'util'
import { Command } from 'commander'
import {
getAllWordpress,
getWordpress,
addWordpress,
removeWordpress,
exportWordpressList,
importWordpressList
} from '../../lib/store/store'
import { getCategories, createPost, updatePost } from '../../lib/wp/wp-api'
import { Post } from '../../types'
const readFile = util.promisify(fs.readFile)
type UpdateOptions = {
date : string
}
export function buildWpCommands (program: Command) {
const wpCommand = program
.command('wp')
.description('Wordpress related commands. The wp list is stored in the local store : ~/.julius/wordpress.json')
.action(() => {
console.log('Please provide a sub-command: "add" or "ls" or "rm" , ... ')
})
wpCommand
.command('ls')
.description('List all Wordpress sites')
.action(async () => {
await getAllWp()
})
wpCommand
.command('info <domain|index>')
.description('Info on a Wordpress site')
.action(async (domain) => {
const domainFound = await getWordpress(domain)
if (domainFound) {
console.log('\nWordpress site found :\n')
console.log(`\ndomain : ${domainFound.domain}`)
console.log(`username : ${domainFound.username}`)
console.log(` | password : ${domainFound.password}\n`)
} else { |
console.log(`\nWordpress site ${domain} not found\n`)
}
})
wpCommand
.command('add <domain:username:password>')
.description('Add a new Wordpress site')
.action(async (site) => {
await addWpSite(site)
})
wpCommand
.command('rm <domain|index>')
.description('Remove Wordpress site')
.action(async (domain) => {
const deleted = await removeWordpress(domain)
console.log(deleted ? `\nWordpress site ${domain} removed successfully\n` : `Wordpress site ${domain} not found\n`)
})
wpCommand
.command('export <file>')
.description('Export the list of wordpress sites (with credentials) the console')
.action(async (file) => {
await exportWordpressList(file)
})
wpCommand
.command('import <file>')
.description('Import the list of wordpress sites (with credentials) from a file')
.action(async (file) => {
await importWordpressList(file)
})
wpCommand
.command('categories <domain|index>')
.description('Fetch the categories for one Wordpress site')
.action(async (domain) => {
const domainFound = await getWordpress(domain)
if (domainFound) {
const categories = await getCategories(domainFound)
console.log(categories)
} else {
console.log(`\nWordpress site ${domain} not found\n`)
}
})
wpCommand
.command('post <domain> <categoryId> <jsonfile>')
.description('Create a new post to a Wordpress site. The file has to be a json file containing : { content, categories, seoTitle, seoDescription }')
.action(async (domain, categoryId, jsonFile) => {
const domainFound = await getWordpress(domain)
if (!domainFound) {
console.log(`\nWordpress site ${domain} not found\n`)
return
}
const jsonContent = await readFile(jsonFile, 'utf8')
const post: Post = JSON.parse(jsonContent)
post.categories = [categoryId]
post.status = 'draft'
await createPost(domainFound, post)
console.log(`\nContent has been published on https://${domainFound.domain}/${post.slug}\n`)
})
wpCommand
.command('update <domain> <slug> <jsonfile>')
.option('-d, --date <date>', 'Update the publish date of the post. Use the format YYYY-MM-DD:HH:MM:SS')
.description('Update a new post to a Wordpress site. The file has to be a json file containing : { content, seoTitle, seoDescription }')
.action(async (domain, slug, jsonFile, options : UpdateOptions) => {
const domainFound = await getWordpress(domain)
if (!domainFound) {
console.log(`\nWordpress site ${domain} not found\n`)
return
}
const jsonContent = await readFile(jsonFile, 'utf8')
const newContent: Post = JSON.parse(jsonContent)
await updatePost(domainFound, slug, newContent, options.date)
console.log(`\nContent has been updated on https://${domainFound.domain}${slug}\n\n`)
})
}
async function getAllWp () {
const wpSites = await getAllWordpress()
if (wpSites.length === 0) {
console.log('\nNo Wordpress site found\n')
return
}
console.log('\nWordpress sites :\n')
console.log(wpSites.map((wp, index) => `${index + 1}. ${wp.domain} (${wp.username})`).join('\n') + '\n')
}
async function addWpSite (site) {
const [domain, username, password] = site.split(':')
if (!domain || !username || !password) {
console.error('Invalid format for adding a new wp site. Expected : domain:username:password')
return
}
await addWordpress({ domain, username, password })
console.log(`\nWordpress site ${domain} added successfully\n`)
}
| src/bin/command/wp.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " const writeDocPromise = fs.promises.writeFile(contentFile, buildContent(options, post), 'utf8')\n await Promise.all([writeJSONPromise, writeDocPromise])\n console.log(`🔥 Content is successfully generated in the file : ${contentFile}. Use the file ${jsonFile} to publish the content on Wordpress.`)\n console.log(`- Slug : ${post.slug}`)\n console.log(`- H1 : ${post.title}`)\n console.log(`- SEO Title : ${post.seoTitle}`)\n console.log(`- SEO Description : ${post.seoDescription}`)\n console.log(`- Total prompts tokens : ${post.totalTokens.promptTokens}`)\n console.log(`- Total completion tokens : ${post.totalTokens.completionTokens}`)\n console.log(`- Estimated cost : ${estimatedCost(postPrompt.model, post)}$`)",
"score": 0.769851565361023
},
{
"filename": "src/lib/wp/wp-api.ts",
"retrieved_chunk": " };\n date?: string;\n date_gmt?: string;\n}\nexport async function getCategories (wp : Wordpress) {\n const { domain, username, password } = wp\n const response = await axios.get(`${getApiUrl(domain)}/categories`, authenticate(username, password))\n return response.data.map((category) => {\n return {\n id: category.id,",
"score": 0.7574292421340942
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " console.log('---------- PROMPT MAIN KEYWORD ----------')\n console.log(prompt)\n }\n const response = await this.sendRequest(prompt)\n if (this.postPrompt.debug) {\n console.log('---------- MAIN KEYWORD ----------')\n console.log(response.text)\n }\n return extractJsonArray(response.text)\n }",
"score": 0.7557083964347839
},
{
"filename": "src/lib/store/store.ts",
"retrieved_chunk": "}\nexport async function removeWordpress (domain: string): Promise<Boolean> {\n const wpSites = await getAllWordpress()\n const index = !isNaN(Number(domain)) ? Number(domain) - 1 : wpSites.findIndex((wp) => wp.domain === domain)\n if (index < 0) {\n return false\n }\n wpSites.splice(index, 1)\n await fs.promises.writeFile(WORDPRESS_FILE, JSON.stringify(wpSites), 'utf8')\n return true",
"score": 0.7551441788673401
},
{
"filename": "src/lib/store/store.ts",
"retrieved_chunk": " return JSON.parse(data)\n}\nexport async function addWordpress (wp: Wordpress): Promise<void> {\n const wpSites = [...await getAllWordpress(), wp].sort((a, b) => a.domain.localeCompare(b.domain))\n await fs.promises.writeFile(WORDPRESS_FILE, JSON.stringify(wpSites), 'utf8')\n}\nexport async function getWordpress (domain: string): Promise<Wordpress | undefined> {\n const wpSites = await getAllWordpress()\n const index = !isNaN(Number(domain)) ? Number(domain) - 1 : wpSites.findIndex((wp) => wp.domain === domain)\n return wpSites[index]",
"score": 0.7518801689147949
}
] | typescript | password : ${domainFound.password}\n`)
} else { |
import {
CollectionAfterChangeHook,
CollectionConfig,
Field,
GlobalConfig,
GlobalAfterChangeHook,
PayloadRequest,
} from "payload/types";
import { Descendant } from "slate";
import { PluginOptions } from "../../types";
import {
buildCrowdinHtmlObject,
buildCrowdinJsonObject,
convertSlateToHtml,
fieldChanged,
} from "../../utilities";
import deepEqual from "deep-equal";
import { getLocalizedFields } from "../../utilities";
import { payloadCrowdinSyncFilesApi } from "../../api/payload-crowdin-sync/files";
/**
* Update Crowdin collections and make updates in Crowdin
*
* This functionality used to be split into field hooks.
* However, it is more reliable to loop through localized
* fields and perform opeerations in one place. The
* asynchronous nature of operations means that
* we need to be careful updates are not made sooner than
* expected.
*/
interface CommonArgs {
pluginOptions: PluginOptions;
}
interface Args extends CommonArgs {
collection: CollectionConfig;
}
interface GlobalArgs extends CommonArgs {
global: GlobalConfig;
}
export const getGlobalAfterChangeHook =
({ global, pluginOptions }: GlobalArgs): GlobalAfterChangeHook =>
async ({
doc, // full document data
previousDoc, // document data before updating the collection
req, // full express request
}) => {
const operation = previousDoc ? "update" : "create";
return performAfterChange({
doc,
req,
previousDoc,
operation,
collection: global,
global: true,
pluginOptions,
});
};
export const getAfterChangeHook =
({ collection, pluginOptions }: Args): CollectionAfterChangeHook =>
async ({
doc, // full document data
req, // full express request
previousDoc, // document data before updating the collection
operation, // name of the operation ie. 'create', 'update'
}) => {
return performAfterChange({
doc,
req,
previousDoc,
operation,
collection,
pluginOptions,
});
};
interface IPerformChange {
doc: any;
req: PayloadRequest;
previousDoc: any;
operation: string;
collection: CollectionConfig | GlobalConfig;
global?: boolean;
pluginOptions: PluginOptions;
}
const performAfterChange = async ({
doc, // full document data
req, // full express request
previousDoc,
operation,
collection,
global = false,
pluginOptions,
}: IPerformChange) => {
/**
* Abort if token not set and not in test mode
*/
if (!pluginOptions.token && process.env.NODE_ENV !== "test") {
return doc;
}
const localizedFields: Field[] = getLocalizedFields({
fields: collection.fields,
});
/**
* Abort if there are no fields to localize
*/
if (localizedFields.length === 0) {
return doc;
}
/**
* Abort if locale is unavailable or this
* is an update from the API to the source
* locale.
*/
if | (!req.locale || req.locale !== pluginOptions.sourceLocale) { |
return doc;
}
/**
* Prepare JSON objects
*
* `text` fields are compiled into a single JSON file
* on Crowdin. Prepare previous and current objects.
*/
const currentCrowdinJsonData = buildCrowdinJsonObject({
doc,
fields: localizedFields,
});
const prevCrowdinJsonData = buildCrowdinJsonObject({
doc: previousDoc,
fields: localizedFields,
});
/**
* Initialize Crowdin client sourceFilesApi
*/
const filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, req.payload);
/**
* Retrieve the Crowdin Article Directory article
*
* Records of Crowdin directories are stored in Payload.
*/
const articleDirectory = await filesApi.findOrCreateArticleDirectory({
document: doc,
collectionSlug: collection.slug,
global,
});
// START: function definitions
const createOrUpdateJsonFile = async () => {
await filesApi.createOrUpdateFile({
name: "fields",
value: currentCrowdinJsonData,
fileType: "json",
articleDirectory,
});
};
const createOrUpdateHtmlFile = async ({
name,
value,
}: {
name: string;
value: Descendant[];
}) => {
await filesApi.createOrUpdateFile({
name: name,
value: convertSlateToHtml(value),
fileType: "html",
articleDirectory,
});
};
const createOrUpdateJsonSource = async () => {
if (
(!deepEqual(currentCrowdinJsonData, prevCrowdinJsonData) &&
Object.keys(currentCrowdinJsonData).length !== 0) ||
process.env.PAYLOAD_CROWDIN_SYNC_ALWAYS_UPDATE === "true"
) {
await createOrUpdateJsonFile();
}
};
/**
* Recursively send rich text fields to Crowdin as HTML
*
* Name these HTML files with dot notation. Examples:
*
* * `localizedRichTextField`
* * `groupField.localizedRichTextField`
* * `arrayField[0].localizedRichTextField`
* * `arrayField[1].localizedRichTextField`
*/
const createOrUpdateHtmlSource = async () => {
const currentCrowdinHtmlData = buildCrowdinHtmlObject({
doc,
fields: localizedFields,
});
const prevCrowdinHtmlData = buildCrowdinHtmlObject({
doc: previousDoc,
fields: localizedFields,
});
Object.keys(currentCrowdinHtmlData).forEach(async (name) => {
const currentValue = currentCrowdinHtmlData[name];
const prevValue = prevCrowdinHtmlData[name];
if (
!fieldChanged(prevValue, currentValue, "richText") &&
process.env.PAYLOAD_CROWDIN_SYNC_ALWAYS_UPDATE !== "true"
) {
return;
}
const file = await createOrUpdateHtmlFile({
name,
value: currentValue as Descendant[],
});
});
};
// END: function definitions
await createOrUpdateJsonSource();
await createOrUpdateHtmlSource();
return doc;
};
| src/hooks/collections/afterChange.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/hooks/collections/afterDelete.ts",
"retrieved_chunk": " req, // full express request\n id, // id of document to delete\n doc, // deleted document\n }) => {\n /**\n * Abort if token not set and not in test mode\n */\n if (!pluginOptions.token && process.env.NODE_ENV !== \"test\") {\n return doc;\n }",
"score": 0.897014319896698
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/combined-field-types.spec.ts",
"retrieved_chunk": " }),\n })\n ).toEqual(expected);\n });\n /**\n * afterChange builds a JSON object for the previous version of\n * a document to compare with the current version. Ensure this\n * function works in that scenario. Also important for dealing\n * with non-required empty fields.\n */",
"score": 0.8884645700454712
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": " if (containsNestedFields(field)) {\n return true;\n }\n return type\n ? fieldCrowdinFileType(field as FieldWithName) === type\n : true;\n })\n // exclude group, array and block fields with no localized fields\n // TODO: find a better way to do this - block, array and group logic is duplicated, and this filter needs to be compatible with field extraction logic later in this function\n .filter((field) => {",
"score": 0.8695594668388367
},
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " });\n return docTranslations;\n } catch (error) {\n console.log(error);\n throw new Error(`${error}`);\n }\n }\n /**\n * Retrieve translations from Crowdin for a document in a given locale\n */",
"score": 0.8664750456809998
},
{
"filename": "src/utilities/containsLocalizedFields.spec.ts",
"retrieved_chunk": " ];\n expect(containsLocalizedFields({ fields })).toEqual(true);\n });\n /**\n * * help ensure no errors during version 0 development\n * * mitigate against errors if a new field type is introduced by Payload CMS\n */\n it(\"does not include unrecognized field types\", () => {\n const fields: any[] = [\n {",
"score": 0.8594827651977539
}
] | typescript | (!req.locale || req.locale !== pluginOptions.sourceLocale) { |
import { ok } from "assert";
import * as core from "@actions/core";
import { exec } from "@actions/exec";
import { RequestError } from "@octokit/request-error";
import { mkdirP } from "@actions/io";
import { Config } from "./config";
import { getOctokit } from "./octokit";
export async function cloneRepository(config: Config): Promise<void> {
const { syncAuth, syncPath, syncRepository, syncTree } = config;
const tempDirectory = await mkdirP(syncPath);
await exec(
`git clone https://${syncAuth}@${syncRepository} ${syncPath}`,
[],
{
silent: !core.isDebug(),
},
);
await exec(`git fetch`, [], {
cwd: syncPath,
silent: !core.isDebug(),
});
await exec(`git checkout --progress --force ${syncTree}`, [], {
cwd: syncPath,
silent: !core.isDebug(),
});
}
export async function configureRepository(config: Config): Promise<void> {
await exec("git", ["config", "user.email", config.commitUserEmail], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
await exec("git", ["config", "user.name", config.commitUserName], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
await exec("git", ["checkout", "-f", "-b", config.commitBranch], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
}
export async function commitChanges(config: Config): Promise<boolean> {
await exec("git", ["add", "-A"], {
cwd: config.fullPath,
failOnStdErr: false,
ignoreReturnCode: true,
silent: !core.isDebug(),
});
| const exitCode = await exec("git", ["commit", "-m", config.commitMessage], { |
cwd: config.fullPath,
failOnStdErr: false,
ignoreReturnCode: true,
silent: !core.isDebug(),
});
return exitCode === 0;
}
export async function createPr(config: Config): Promise<void> {
await exec("git", ["push", "-f", "-u", "origin", config.commitBranch], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
ok(process.env.GITHUB_REPOSITORY, "Expected GITHUB_REPOSITORY to be defined");
ok(config.prToken, "Expected PR_TOKEN to be defined");
const [owner, repo] = process.env.GITHUB_REPOSITORY.split("/");
const octokit = getOctokit(config.prToken);
const { data: repository } = await octokit.rest.repos.get({ owner, repo });
for (const name of config.prLabels) {
core.debug(`Creating issue label ${name}`);
try {
await octokit.rest.issues.createLabel({ owner, repo, name });
} catch (err) {
if (err instanceof RequestError && err.status === 422) {
core.debug(`Issue label ${name} already exists`);
} else {
throw err;
}
}
}
try {
const res = await octokit.rest.pulls.create({
owner,
repo,
base: repository.default_branch,
body: config.prBody,
head: config.commitBranch,
maintainer_can_modify: true,
title: config.prTitle,
});
await octokit.rest.issues.addLabels({
owner,
repo,
issue_number: res.data.number,
labels: config.prLabels,
});
await octokit.rest.pulls.requestReviewers({
owner,
repo,
pull_number: res.data.number,
reviewers: config.prReviewUsers,
});
core.setOutput("pr-url", res.data.html_url);
} catch (err) {
if (err instanceof RequestError && err.status === 422) {
core.debug("PR already exists");
} else {
throw err;
}
}
}
| src/git.ts | stordco-actions-sync-ca5bdce | [
{
"filename": "src/scripts.ts",
"retrieved_chunk": " scriptPath: string,\n config: Config,\n): Promise<Record<string, string>> {\n const outputFilePath = createTempPath();\n const io = await open(outputFilePath, \"a\");\n await io.close();\n await exec(scriptPath, [], {\n cwd: config.fullPath,\n env: {\n ...process.env,",
"score": 0.7928340435028076
},
{
"filename": "src/templates.test.ts",
"retrieved_chunk": "describe.concurrent(\"templates\", () => {\n beforeEach<LocalTestContext>(async (ctx) => {\n const fullPath = await mkdtemp(join(tmpdir(), \"actions-sync\"));\n ctx.config = {\n commitBranch: \"main\",\n commitMessage: \"commit message\",\n commitUserEmail: \"[email protected]\",\n commitUserName: \"testing\",\n fullPath,\n path: \"\",",
"score": 0.7809848189353943
},
{
"filename": "src/index.ts",
"retrieved_chunk": "export async function run() {\n const config = getConfig();\n await configureRepository(config);\n await cloneRepository(config);\n await runScripts(config);\n await templateFiles(config);\n if (config.prEnabled) {\n const hasChanges = await commitChanges(config);\n if (hasChanges === false) {\n core.info(\"No changes to commit.\");",
"score": 0.7640459537506104
},
{
"filename": "src/config.ts",
"retrieved_chunk": " syncRepository: string;\n syncTree: string;\n templateVariables: Record<string, string>;\n};\nexport function getConfig(): Config {\n const path = core.getInput(\"path\", { required: false });\n const workspace = process.env.GITHUB_WORKSPACE;\n ok(workspace, \"Expected GITHUB_WORKSPACE to be defined\");\n return {\n commitBranch: core.getInput(\"commit-branch\", { required: true }),",
"score": 0.7278238534927368
},
{
"filename": "src/scripts.ts",
"retrieved_chunk": "export async function runScripts(config: Config): Promise<void> {\n const scriptGlob = await glob.create(`${config.syncPath}/scripts/*`);\n const scriptPathsUnsorted = await scriptGlob.glob();\n const scriptPaths = scriptPathsUnsorted.sort();\n core.info(`Running ${scriptPaths.length} scripts...`);\n for (const scriptPath of scriptPaths) {\n core.startGroup(`Run ${relative(config.syncPath, scriptPath)}`);\n const newTemplateVariables = await runScript(scriptPath, config);\n core.debug(\n \"Adding new template variables\\n\" +",
"score": 0.7043022513389587
}
] | typescript | const exitCode = await exec("git", ["commit", "-m", config.commitMessage], { |
import { oraPromise } from 'ora'
import { ChatGptHelper, GeneratorHelperInterface } from './lib/post-helpers'
import {
PostPrompt,
Post
} from './types'
import { replaceAllPrompts } from './lib/template'
/**
* Class for generating a post. It need a helper class to generate the post
* Each helper class must implement the GeneratorHelperInterface
*/
export class PostGenerator {
private helper : GeneratorHelperInterface
public constructor (helper : GeneratorHelperInterface) {
this.helper = helper
}
public async generate () : Promise<Post> {
return this.helper.isCustom() ? await this.customGenerate() : await this.autoGenerate()
}
/**
* Generate a post using the custom prompt based on a template
*/
private async customGenerate () : Promise<Post> {
const promptContents = []
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
// We remove the first prompt because it is the system prompt
const prompts = this.helper.getPrompt().prompts.slice(1)
// for each prompt, we generate the content
const templatePrompts = prompts.entries()
for (const [index, prompt] of templatePrompts) {
const content = await oraPromise(
this.helper.generateCustomPrompt(prompt),
{
text: `Generating the prompt num. ${index + 1} ...`
}
)
promptContents.push(content)
}
// We replace the prompts by the AI answer in the template content
const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)
const seoInfo = await oraPromise(
this.helper.generateSeoInfo(),
{
text: 'Generating SEO info ...'
}
)
return {
title: seoInfo.h1,
slug: seoInfo.slug,
seoTitle: seoInfo.seoTitle,
seoDescription: seoInfo.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
}
}
/**
* Generate a post using the auto mode
*/
private async autoGenerate () : Promise<Post> {
await oraPromise(
this.helper.init(),
{
text: ' Init the completion parameters ...'
}
)
const tableOfContent = await oraPromise(
this.helper.generateContentOutline(),
{
text: 'Generating post outline ...'
}
)
let content = await oraPromise(
this.helper.generateIntroduction(),
{
text: 'Generating introduction...'
}
)
content += await oraPromise(
this.helper.generateHeadingContents(tableOfContent),
{
text: 'Generating content ...'
}
)
if (this.helper.getPrompt().withConclusion) {
content += await oraPromise(
this.helper.generateConclusion(),
{
text: 'Generating conclusion...'
}
)
}
return {
title: tableOfContent.title,
slug: tableOfContent.slug,
seoTitle: tableOfContent.seoTitle,
seoDescription: tableOfContent.seoDescription,
content,
totalTokens: this.helper.getTotalTokens()
}
}
}
/**
* Class for generating a post using the OpenAI API
*/
export class OpenAIPostGenerator extends PostGenerator {
public constructor (postPrompt : PostPrompt) {
| super(new ChatGptHelper(postPrompt))
} |
}
| src/post.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": "/**\n * Helper implementation for generating a post using the ChatGPT API\n * @class\n */\nexport class ChatGptHelper implements GeneratorHelperInterface {\n private postPrompt : PostPrompt\n private api : ChatGPTAPI\n // The parent message is either the previous one in the conversation (if a template is used)\n // or the generated outline (if we are in auto mode)\n private chatParentMessage : ChatMessage",
"score": 0.8642280697822571
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " logit_bias?: object | null,\n}\n/**\n * Interface for the helper class for generating a post. it defines how to generate a post\n * Each helper class must implement this interface\n * @interface\n */\nexport interface GeneratorHelperInterface {\n init () : Promise<void>\n isCustom() : boolean",
"score": 0.863215446472168
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " // METHODS FOR THE CUSTOM MODE base on a template\n // -----------------------------------------------\n /**\n * Generate a content based on one of prompt defined in the template\n * @param customPrompt : the prompt defined in the template\n * @returns the AI answer\n */\n async generateCustomPrompt (customPrompt : string) {\n this.chatParentMessage = await this.sendRequest(customPrompt, this.completionParams)\n return extractCodeBlock(this.chatParentMessage.text)",
"score": 0.8164967894554138
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " this.postPrompt = postPrompt\n }\n isCustom () : boolean {\n return this.postPrompt?.templateFile !== undefined\n }\n getPrompt (): PostPrompt {\n return this.postPrompt\n }\n getTotalTokens (): TotalTokens {\n return this.totalTokens",
"score": 0.7914614677429199
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " ...options,\n ...answers,\n maxModelTokens: answers.model === 'gpt-4' ? 8000 : 4000\n }\n if (!postPrompt.topic) {\n throw new Error('The topic is mandatory, use the option -tp or --topic')\n }\n const postGenerator = new OpenAIPostGenerator(postPrompt)\n const post = await postGenerator.generate()\n const jsonData = {",
"score": 0.7880046963691711
}
] | typescript | super(new ChatGptHelper(postPrompt))
} |
import { ok } from "assert";
import * as core from "@actions/core";
import { exec } from "@actions/exec";
import { RequestError } from "@octokit/request-error";
import { mkdirP } from "@actions/io";
import { Config } from "./config";
import { getOctokit } from "./octokit";
export async function cloneRepository(config: Config): Promise<void> {
const { syncAuth, syncPath, syncRepository, syncTree } = config;
const tempDirectory = await mkdirP(syncPath);
await exec(
`git clone https://${syncAuth}@${syncRepository} ${syncPath}`,
[],
{
silent: !core.isDebug(),
},
);
await exec(`git fetch`, [], {
cwd: syncPath,
silent: !core.isDebug(),
});
await exec(`git checkout --progress --force ${syncTree}`, [], {
cwd: syncPath,
silent: !core.isDebug(),
});
}
export async function configureRepository(config: Config): Promise<void> {
await exec("git", ["config", "user.email", config.commitUserEmail], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
await exec("git", ["config", "user.name", config.commitUserName], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
await exec("git", ["checkout", "-f", "-b", config.commitBranch], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
}
export async function commitChanges(config: Config): Promise<boolean> {
await exec("git", ["add", "-A"], {
cwd: config.fullPath,
failOnStdErr: false,
ignoreReturnCode: true,
silent: !core.isDebug(),
});
const exitCode = await exec("git", ["commit", "-m", config.commitMessage], {
cwd: config.fullPath,
failOnStdErr: false,
ignoreReturnCode: true,
silent: !core.isDebug(),
});
return exitCode === 0;
}
export async function createPr(config: Config): Promise<void> {
await exec("git", ["push", "-f", "-u", "origin", config.commitBranch], {
cwd: config.fullPath,
silent: !core.isDebug(),
});
ok(process.env.GITHUB_REPOSITORY, "Expected GITHUB_REPOSITORY to be defined");
ok(config.prToken, "Expected PR_TOKEN to be defined");
const [owner, repo] = process.env.GITHUB_REPOSITORY.split("/");
const octokit = getOctokit(config.prToken);
const { data: repository } = await octokit.rest.repos.get({ owner, repo });
for (const name of config.prLabels) {
core.debug(`Creating issue label ${name}`);
try {
await octokit.rest.issues.createLabel({ owner, repo, name });
} catch (err) {
if (err instanceof RequestError && err.status === 422) {
core.debug(`Issue label ${name} already exists`);
} else {
throw err;
}
}
}
try {
const res = await octokit.rest.pulls.create({
owner,
repo,
base: repository.default_branch,
body: config.prBody,
head: config.commitBranch,
maintainer_can_modify: true,
title: config.prTitle,
});
await octokit.rest.issues.addLabels({
owner,
repo,
issue_number: res.data.number,
labels: config.prLabels,
});
await octokit.rest.pulls.requestReviewers({
owner,
repo,
pull_number: res.data.number,
| reviewers: config.prReviewUsers,
}); |
core.setOutput("pr-url", res.data.html_url);
} catch (err) {
if (err instanceof RequestError && err.status === 422) {
core.debug("PR already exists");
} else {
throw err;
}
}
}
| src/git.ts | stordco-actions-sync-ca5bdce | [
{
"filename": "src/config.ts",
"retrieved_chunk": " commitMessage: core.getInput(\"commit-message\", { required: true }),\n commitUserEmail: core.getInput(\"commit-user-email\", { required: true }),\n commitUserName: core.getInput(\"commit-user-name\", { required: true }),\n fullPath: join(workspace, path),\n path: path,\n prBody: core.getInput(\"pr-body\", { required: false }),\n prEnabled: core.getBooleanInput(\"pr-enabled\", { required: true }),\n prLabels: core.getMultilineInput(\"pr-labels\", { required: false }),\n prReviewUsers: core.getMultilineInput(\"pr-review-users\", {\n required: false,",
"score": 0.6946748495101929
},
{
"filename": "src/templates.test.ts",
"retrieved_chunk": " prAssignee: \"\",\n prBody: \"testing\",\n prEnabled: false,\n prLabels: [],\n prReviewUsers: [],\n prTitle: \"testing\",\n syncAuth: \"\",\n syncBranch: \"main\",\n syncPath: resolve(__dirname, \"../test/fixtures\"),\n syncRepository: \"test/test\",",
"score": 0.6434301733970642
},
{
"filename": "src/config.ts",
"retrieved_chunk": " }),\n prTitle: core.getInput(\"pr-title\", { required: true }),\n prToken: core.getInput(\"pr-token\", { required: false }),\n syncAuth: core.getInput(\"sync-auth\", { required: false }),\n syncPath: createTempPath(),\n syncRepository: core.getInput(\"sync-repository\", { required: true }),\n syncTree:\n core.getInput(\"sync-branch\", { required: false }) ||\n core.getInput(\"sync-tree\", { required: true }),\n templateVariables: {},",
"score": 0.6113787889480591
},
{
"filename": "src/octokit.ts",
"retrieved_chunk": "import type { Octokit } from \"@octokit/core\";\nimport { getOctokit as upstreamOctokit } from \"@actions/github\";\nimport { retry } from \"@octokit/plugin-retry\";\nimport { throttling } from \"@octokit/plugin-throttling\";\nfunction onLimit(\n retryAfter: number,\n { method, url }: { method: string; url: string },\n octokit: Octokit,\n) {\n octokit.log.warn(`Request quota exhausted for request ${method} ${url}`);",
"score": 0.6034956574440002
},
{
"filename": "src/octokit.ts",
"retrieved_chunk": " octokit.log.info(`Retrying after ${retryAfter} seconds`);\n return true;\n}\nexport function getOctokit(token: string) {\n return upstreamOctokit(\n token,\n {\n retry: {\n enabled: true,\n },",
"score": 0.5985422134399414
}
] | typescript | reviewers: config.prReviewUsers,
}); |
import {
Body,
Controller,
Delete,
Get,
Logger,
Param,
Post,
Put,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { TodoListService } from './todolist.service';
import TodoList from '../models/todolist/todolist';
import Task from '../models/task/task';
@Controller('todolist')
export class TodoListController {
constructor(private readonly appService: TodoListService) {}
@Post()
@UsePipes(new ValidationPipe())
createTodoList(@Body() list: TodoList): TodoList {
try {
const id = this.appService.AddList(list);
return this.appService.GetList(id);
} catch (error) {
Logger.error(error);
}
}
@Get(':id')
getTodoList(@Param('id') listId: string): TodoList {
return this.appService.GetList(listId);
}
@Delete(':id')
@UsePipes(new ValidationPipe())
deleteList(@Param('id') listId: string): string {
this | .appService.RemoveList(listId); |
return 'done';
}
@Put(':id')
@UsePipes(new ValidationPipe())
updateList(
@Param('id') listId: string,
@Body('Name') newName: string,
): TodoList {
this.appService.UpdateListName(listId, newName);
return this.appService.GetList(listId);
}
@Post(':id/task')
@UsePipes(new ValidationPipe())
createTask(@Body() task: Task, @Param('id') listId: string): string {
const id = this.appService.AddTask(listId, task);
return id;
}
}
| src/todolist/todolist.controller.ts | nitzan8897-TodoListNestJS-72123e7 | [
{
"filename": "src/todolist/todolist.service.ts",
"retrieved_chunk": " delete this.RAMMemory[listId];\n }\n GetList(listId: string): TodoList | undefined {\n listIdValidation(this.RAMMemory, listId);\n return this.RAMMemory[listId];\n }\n UpdateListName(listId: string, listNewName: string): void {\n listIdValidation(this.RAMMemory, listId);\n this.RAMMemory[listId].Name = listNewName;\n }",
"score": 0.7456505298614502
},
{
"filename": "src/models/task/task.ts",
"retrieved_chunk": " doneStatus: boolean;\n @IsString()\n @IsNotEmpty()\n description: string;\n @ManyToOne(() => TodoList, (todoList) => todoList.Tasks)\n todoList: TodoList;\n}",
"score": 0.7161875367164612
},
{
"filename": "src/utils/index.ts",
"retrieved_chunk": "import { HttpException, HttpStatus } from '@nestjs/common';\nimport TodoList from '../models/todolist/todolist';\nimport { ListNotFound } from './messages';\nexport const listIdValidation = (\n RAMMemory: Record<string, TodoList>,\n listId: string,\n) => {\n if (!RAMMemory[listId]) {\n throw new HttpException(ListNotFound(listId), HttpStatus.NOT_FOUND);\n }",
"score": 0.7071604132652283
},
{
"filename": "src/models/todolist/todolist-actions.module.ts",
"retrieved_chunk": "import IList from \"./todolist.module\";\nexport default interface ITodoListActions {\n AddList(list: IList): string;\n RemoveList(listId: string): void;\n GetList(listId: string): IList | undefined;\n UpdateListName(listId: string, listNewName: string): void;\n}",
"score": 0.7059619426727295
},
{
"filename": "src/todolist/todolist.service.ts",
"retrieved_chunk": " AddList(list: IList): string {\n const listId = uuidv4();\n this.RAMMemory[listId] = { Name: list.Name, Id: listId, Tasks: [] };\n Logger.log(\n `Added new list, listName: ${this.RAMMemory[listId].Name}, listId: ${listId}`,\n );\n return listId;\n }\n RemoveList(listId: string): void {\n listIdValidation(this.RAMMemory, listId);",
"score": 0.681036651134491
}
] | typescript | .appService.RemoveList(listId); |
import * as dotenv from 'dotenv'
import { readFile as rd } from 'fs'
import { promisify } from 'util'
import { ChatGPTAPI, ChatGPTError, ChatMessage, SendMessageOptions } from 'chatgpt'
import pRetry, { AbortError, FailedAttemptError } from 'p-retry'
import { extractJsonArray, extractCodeBlock, extractPostOutlineFromCodeBlock, extractSeoInfo, extractAudienceIntentInfo } from './extractor'
import {
getPromptForMainKeyword,
getPromptForOutline,
getPromptForIntroduction,
getPromptForHeading,
getPromptForConclusion,
getAutoSystemPrompt,
getPromptForSeoInfo,
getCustomSystemPrompt,
getSeoSystemPrompt,
getPromptForIntentAudience as getPromptForAudienceIntent
} from './prompts'
import {
Heading,
PostOutline,
PostPrompt,
TotalTokens,
SeoInfo
} from '../types'
import { encode } from './tokenizer'
import { extractPrompts } from './template'
import { log } from 'console'
import { NoApiKeyError } from './errors'
dotenv.config()
const readFile = promisify(rd)
/**
* Specific Open AI API parameters for the completion
*/
export type CompletionParams = {
temperature?: number | null,
top_p?: number | null,
max_tokens?: number,
presence_penalty?: number | null,
frequency_penalty?: number | null,
logit_bias?: object | null,
}
/**
* Interface for the helper class for generating a post. it defines how to generate a post
* Each helper class must implement this interface
* @interface
*/
export interface GeneratorHelperInterface {
init () : Promise<void>
isCustom() : boolean
generateContentOutline () : Promise<PostOutline>
generateMainKeyword () : Promise<string[]>
generateIntroduction () : Promise<string>
generateConclusion () : Promise<string>
generateHeadingContents (tableOfContent : PostOutline) : Promise<string>
generateCustomPrompt(prompt : string) : Promise<string>
generateSeoInfo () : Promise<SeoInfo>
getTotalTokens() : TotalTokens
getPrompt() : PostPrompt
}
/**
* Helper implementation for generating a post using the ChatGPT API
* @class
*/
export class ChatGptHelper implements GeneratorHelperInterface {
private postPrompt : PostPrompt
private api : ChatGPTAPI
// The parent message is either the previous one in the conversation (if a template is used)
// or the generated outline (if we are in auto mode)
private chatParentMessage : ChatMessage
private completionParams : CompletionParams
private totalTokens : TotalTokens = {
promptTokens: 0,
completionTokens: 0,
total: 0
}
// -----------------------------------------------
// CONSTRUCTOR AND INITIALIZATION
// -----------------------------------------------
public constructor (postPrompt : PostPrompt) {
this.postPrompt = postPrompt
}
isCustom () : boolean {
return this.postPrompt?.templateFile !== undefined
}
getPrompt (): PostPrompt {
return this.postPrompt
}
getTotalTokens (): TotalTokens {
return this.totalTokens
}
async init () {
if (this.isCustom()) {
if (this.postPrompt.debug) {
console.log(`Use template : ${this.postPrompt.templateFile}`)
}
this.postPrompt.templateContent = await this.readTemplate()
| this.postPrompt.prompts = extractPrompts(this.postPrompt.templateContent)
} |
const systemMessage = this.isCustom() ? getCustomSystemPrompt(this.postPrompt) : getAutoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemMessage)
}
private async buildChatGPTAPI (systemMessage : string) {
try {
this.api = new ChatGPTAPI({
apiKey: this.postPrompt?.apiKey || process.env.OPENAI_API_KEY,
completionParams: {
model: this.postPrompt.model
},
systemMessage,
debug: this.postPrompt.debugapi
})
} catch (error) {
throw new NoApiKeyError()
}
if (this.postPrompt.debug) {
console.log(`OpenAI API initialized with model : ${this.postPrompt.model}`)
}
this.completionParams = {
temperature: this.postPrompt.temperature ?? 0.8,
frequency_penalty: this.postPrompt.frequencyPenalty ?? 0,
presence_penalty: this.postPrompt.presencePenalty ?? 1
}
if (this.postPrompt.logitBias) {
const mainKwWords = await this.generateMainKeyword()
// set the logit bias in order to force the model to minimize the usage of the main keyword
const logitBiais: Record<number, number> = {}
mainKwWords.forEach((kw) => {
const encoded = encode(kw)
encoded.forEach((element) => {
logitBiais[element] = Number(this.postPrompt.logitBias) || -1
})
})
this.completionParams.logit_bias = logitBiais
}
if (this.postPrompt.debug) {
console.log('---------- COMPLETION PARAMETERS ----------')
console.log('Max Tokens : ' + this.completionParams.max_tokens)
console.log('Temperature : ' + this.completionParams.temperature)
console.log('Frequency Penalty : ' + this.completionParams.frequency_penalty)
console.log('Presence Penalty : ' + this.completionParams.presence_penalty)
console.log('Logit Biais : ' + this.completionParams.logit_bias)
}
}
// -----------------------------------------------
// METHODS FOR THE AUTOMATIC MODE
// -----------------------------------------------
async generateMainKeyword () {
const prompt = getPromptForMainKeyword()
if (this.postPrompt.debug) {
console.log('---------- PROMPT MAIN KEYWORD ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- MAIN KEYWORD ----------')
console.log(response.text)
}
return extractJsonArray(response.text)
}
async generateContentOutline () {
if (this.postPrompt.generate) {
const audienceIntent = await this.generateAudienceIntent()
this.postPrompt = {
...audienceIntent,
...this.postPrompt
}
}
const prompt = getPromptForOutline(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT OUTLINE ----------')
console.log(prompt)
}
// the parent message is the outline for the upcoming content
// By this way, we can decrease the cost of the API call by minimizing the number of prompt tokens
// TODO : add an option to disable this feature
this.chatParentMessage = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- OUTLINE ----------')
console.log(this.chatParentMessage.text)
}
return extractPostOutlineFromCodeBlock(this.chatParentMessage.text)
}
async generateAudienceIntent () {
const prompt = getPromptForAudienceIntent(this.postPrompt)
if (this.postPrompt.debug) {
console.log('---------- PROMPT AUDIENCE INTENT ----------')
console.log(prompt)
}
const response = await this.sendRequest(prompt)
if (this.postPrompt.debug) {
console.log('---------- AUDIENCE INTENT ----------')
console.log(response.text)
}
return extractAudienceIntentInfo(response.text)
}
async generateIntroduction () {
const response = await this.sendRequest(getPromptForIntroduction(this.postPrompt), this.completionParams)
return extractCodeBlock(response.text)
}
async generateConclusion () {
const response = await this.sendRequest(getPromptForConclusion(), this.completionParams)
return extractCodeBlock(response.text)
}
async generateHeadingContents (postOutline : PostOutline) {
const headingLevel = 2
return await this.buildContent(postOutline.headings, headingLevel)
}
private async buildContent (headings: Heading[], headingLevel : number, previousContent: string = ''): Promise<string> {
if (headings.length === 0) {
return previousContent
}
const [currentHeading, ...remainingHeadings] = headings
const mdHeading = Array(headingLevel).fill('#').join('')
let content = previousContent + '\n' + mdHeading + ' ' + currentHeading.title
if (currentHeading.headings && currentHeading.headings.length > 0) {
content = await this.buildContent(currentHeading.headings, headingLevel + 1, content)
} else {
content += '\n' + await this.getContent(currentHeading)
}
return this.buildContent(remainingHeadings, headingLevel, content)
}
private async getContent (heading: Heading): Promise<string> {
if (this.postPrompt.debug) {
console.log(`\nHeading : ${heading.title} ...'\n`)
}
const response = await this.sendRequest(getPromptForHeading(this.postPrompt.tone, heading.title, heading.keywords), this.completionParams)
return `${extractCodeBlock(response.text)}\n`
}
// -----------------------------------------------
// METHODS FOR THE CUSTOM MODE base on a template
// -----------------------------------------------
/**
* Generate a content based on one of prompt defined in the template
* @param customPrompt : the prompt defined in the template
* @returns the AI answer
*/
async generateCustomPrompt (customPrompt : string) {
this.chatParentMessage = await this.sendRequest(customPrompt, this.completionParams)
return extractCodeBlock(this.chatParentMessage.text)
}
/**
* Generate the SEO info for the post based on the template
* @returns the SEO info
*/
async generateSeoInfo (): Promise<SeoInfo> {
const systemPrompt = getSeoSystemPrompt(this.postPrompt)
await this.buildChatGPTAPI(systemPrompt)
this.chatParentMessage = await this.sendRequest(getPromptForSeoInfo(this.postPrompt), this.completionParams)
if (this.postPrompt.debug) {
log('---------- SEO INFO ----------')
console.log(this.chatParentMessage.text)
}
return extractSeoInfo(this.chatParentMessage.text)
}
private async readTemplate () : Promise<string> {
const templatePath = this.postPrompt.templateFile
return await readFile(templatePath, 'utf-8')
}
// -----------------------------------------------
// SEND REQUEST TO OPENAI API
// -----------------------------------------------
private async sendRequest (prompt : string, completionParams? : CompletionParams) {
return await pRetry(async () => {
const options : SendMessageOptions = { parentMessageId: this.chatParentMessage?.id }
if (completionParams) {
options.completionParams = completionParams
}
const response = await this.api.sendMessage(prompt, options)
this.totalTokens.promptTokens += response.detail.usage.prompt_tokens
this.totalTokens.completionTokens += response.detail.usage.completion_tokens
this.totalTokens.total += response.detail.usage.total_tokens
return response
}, {
retries: 10,
onFailedAttempt: async (error) => {
this.manageError(error)
}
})
}
private manageError (error: FailedAttemptError) {
if (this.postPrompt.debug) {
console.log('---------- OPENAI REQUEST ERROR ----------')
console.log(error)
}
if (error instanceof ChatGPTError) {
const chatGPTError = error as ChatGPTError
if (chatGPTError.statusCode === 401) {
console.log('OpenAI API Error : Invalid API key: please check your API key in the option -k or in the OPENAI_API_KEY env var.')
process.exit(1)
}
if (chatGPTError.statusCode === 404) {
console.log(`OpenAI API Error : Invalid model for your OpenAI subscription. Check if you can use : ${this.postPrompt.model}.`)
console.log(this.postPrompt.model === 'gpt-4' || this.postPrompt.model === 'gpt-4-32k' ? 'You need to join the waiting list to use the GPT-4 API : https://openai.com/waitlist/gpt-4-api' : '')
process.exit(1)
}
}
if (error instanceof AbortError) {
console.log(`OpenAI API - Request aborted. ${error.message}`)
} else {
console.log(`OpenAI API - Request failed - Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left. ${error.message}`)
}
}
}
| src/lib/post-helpers.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/post.ts",
"retrieved_chunk": " )\n promptContents.push(content)\n }\n // We replace the prompts by the AI answer in the template content\n const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)\n const seoInfo = await oraPromise(\n this.helper.generateSeoInfo(),\n {\n text: 'Generating SEO info ...'\n }",
"score": 0.7903935313224792
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " })\n}\nasync function generatePost (options: Options) {\n let answers : any = {}\n if (isInteractive(options)) {\n answers = isCustom(options) ? await askCustomQuestions() : await askQuestions()\n }\n const defaultPostPrompt = buildDefaultPostPrompt()\n const postPrompt : PostPrompt = {\n ...defaultPostPrompt,",
"score": 0.7875884175300598
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": " ...options,\n ...answers,\n maxModelTokens: answers.model === 'gpt-4' ? 8000 : 4000\n }\n if (!postPrompt.topic) {\n throw new Error('The topic is mandatory, use the option -tp or --topic')\n }\n const postGenerator = new OpenAIPostGenerator(postPrompt)\n const post = await postGenerator.generate()\n const jsonData = {",
"score": 0.7721039056777954
},
{
"filename": "src/post.ts",
"retrieved_chunk": " // We remove the first prompt because it is the system prompt\n const prompts = this.helper.getPrompt().prompts.slice(1)\n // for each prompt, we generate the content\n const templatePrompts = prompts.entries()\n for (const [index, prompt] of templatePrompts) {\n const content = await oraPromise(\n this.helper.generateCustomPrompt(prompt),\n {\n text: `Generating the prompt num. ${index + 1} ...`\n }",
"score": 0.7683541774749756
},
{
"filename": "src/post.ts",
"retrieved_chunk": " }\n )\n content += await oraPromise(\n this.helper.generateHeadingContents(tableOfContent),\n {\n text: 'Generating content ...'\n }\n )\n if (this.helper.getPrompt().withConclusion) {\n content += await oraPromise(",
"score": 0.7675711512565613
}
] | typescript | this.postPrompt.prompts = extractPrompts(this.postPrompt.templateContent)
} |
import {
Body,
Controller,
Delete,
Get,
Logger,
Param,
Post,
Put,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { TodoListService } from './todolist.service';
import TodoList from '../models/todolist/todolist';
import Task from '../models/task/task';
@Controller('todolist')
export class TodoListController {
constructor(private readonly appService: TodoListService) {}
@Post()
@UsePipes(new ValidationPipe())
createTodoList(@Body() list: TodoList): TodoList {
try {
const id = this.appService.AddList(list);
return this.appService.GetList(id);
} catch (error) {
Logger.error(error);
}
}
@Get(':id')
getTodoList(@Param('id') listId: string): TodoList {
return this.appService.GetList(listId);
}
@Delete(':id')
@UsePipes(new ValidationPipe())
deleteList(@Param('id') listId: string): string {
this.appService.RemoveList(listId);
return 'done';
}
@Put(':id')
@UsePipes(new ValidationPipe())
updateList(
@Param('id') listId: string,
@Body('Name') newName: string,
): TodoList {
this.appService.UpdateListName(listId, newName);
return this.appService.GetList(listId);
}
@Post(':id/task')
@UsePipes(new ValidationPipe())
createTask(@Body() task: Task, @Param('id') listId: string): string {
const id = this.appService | .AddTask(listId, task); |
return id;
}
}
| src/todolist/todolist.controller.ts | nitzan8897-TodoListNestJS-72123e7 | [
{
"filename": "src/todolist/todolist.service.ts",
"retrieved_chunk": " AddTask(listId: string, task: Task): string {\n listIdValidation(this.RAMMemory, listId);\n const taskId = uuidv4();\n task.taskId = taskId;\n this.RAMMemory[listId].Tasks.push(task);\n Logger.log(`Added new Task, ${task.description} to the list: ${listId}`);\n return taskId;\n }\n}",
"score": 0.7795267701148987
},
{
"filename": "src/todolist/todolist.service.ts",
"retrieved_chunk": " delete this.RAMMemory[listId];\n }\n GetList(listId: string): TodoList | undefined {\n listIdValidation(this.RAMMemory, listId);\n return this.RAMMemory[listId];\n }\n UpdateListName(listId: string, listNewName: string): void {\n listIdValidation(this.RAMMemory, listId);\n this.RAMMemory[listId].Name = listNewName;\n }",
"score": 0.7791277170181274
},
{
"filename": "src/todolist/todolist.service.ts",
"retrieved_chunk": " AddList(list: IList): string {\n const listId = uuidv4();\n this.RAMMemory[listId] = { Name: list.Name, Id: listId, Tasks: [] };\n Logger.log(\n `Added new list, listName: ${this.RAMMemory[listId].Name}, listId: ${listId}`,\n );\n return listId;\n }\n RemoveList(listId: string): void {\n listIdValidation(this.RAMMemory, listId);",
"score": 0.7492704391479492
},
{
"filename": "src/models/todolist/todolist-actions.module.ts",
"retrieved_chunk": "import IList from \"./todolist.module\";\nexport default interface ITodoListActions {\n AddList(list: IList): string;\n RemoveList(listId: string): void;\n GetList(listId: string): IList | undefined;\n UpdateListName(listId: string, listNewName: string): void;\n}",
"score": 0.7419408559799194
},
{
"filename": "src/utils/index.ts",
"retrieved_chunk": "import { HttpException, HttpStatus } from '@nestjs/common';\nimport TodoList from '../models/todolist/todolist';\nimport { ListNotFound } from './messages';\nexport const listIdValidation = (\n RAMMemory: Record<string, TodoList>,\n listId: string,\n) => {\n if (!RAMMemory[listId]) {\n throw new HttpException(ListNotFound(listId), HttpStatus.NOT_FOUND);\n }",
"score": 0.7402350902557373
}
] | typescript | .AddTask(listId, task); |
import {
Body,
Controller,
Delete,
Get,
Logger,
Param,
Post,
Put,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { TodoListService } from './todolist.service';
import TodoList from '../models/todolist/todolist';
import Task from '../models/task/task';
@Controller('todolist')
export class TodoListController {
constructor(private readonly appService: TodoListService) {}
@Post()
@UsePipes(new ValidationPipe())
createTodoList(@Body() list: TodoList): TodoList {
try {
const id = this.appService.AddList(list);
return this.appService.GetList(id);
} catch (error) {
Logger.error(error);
}
}
@Get(':id')
getTodoList(@Param('id') listId: string): TodoList {
return this.appService.GetList(listId);
}
@Delete(':id')
@UsePipes(new ValidationPipe())
deleteList(@Param('id') listId: string): string {
this.appService.RemoveList(listId);
return 'done';
}
@Put(':id')
@UsePipes(new ValidationPipe())
updateList(
@Param('id') listId: string,
@Body('Name') newName: string,
): TodoList {
this. | appService.UpdateListName(listId, newName); |
return this.appService.GetList(listId);
}
@Post(':id/task')
@UsePipes(new ValidationPipe())
createTask(@Body() task: Task, @Param('id') listId: string): string {
const id = this.appService.AddTask(listId, task);
return id;
}
}
| src/todolist/todolist.controller.ts | nitzan8897-TodoListNestJS-72123e7 | [
{
"filename": "src/models/task/task.ts",
"retrieved_chunk": " doneStatus: boolean;\n @IsString()\n @IsNotEmpty()\n description: string;\n @ManyToOne(() => TodoList, (todoList) => todoList.Tasks)\n todoList: TodoList;\n}",
"score": 0.7547593116760254
},
{
"filename": "src/models/todolist/todolist-actions.module.ts",
"retrieved_chunk": "import IList from \"./todolist.module\";\nexport default interface ITodoListActions {\n AddList(list: IList): string;\n RemoveList(listId: string): void;\n GetList(listId: string): IList | undefined;\n UpdateListName(listId: string, listNewName: string): void;\n}",
"score": 0.7370561361312866
},
{
"filename": "src/todolist/todolist.service.ts",
"retrieved_chunk": " delete this.RAMMemory[listId];\n }\n GetList(listId: string): TodoList | undefined {\n listIdValidation(this.RAMMemory, listId);\n return this.RAMMemory[listId];\n }\n UpdateListName(listId: string, listNewName: string): void {\n listIdValidation(this.RAMMemory, listId);\n this.RAMMemory[listId].Name = listNewName;\n }",
"score": 0.7355082035064697
},
{
"filename": "src/utils/index.ts",
"retrieved_chunk": "import { HttpException, HttpStatus } from '@nestjs/common';\nimport TodoList from '../models/todolist/todolist';\nimport { ListNotFound } from './messages';\nexport const listIdValidation = (\n RAMMemory: Record<string, TodoList>,\n listId: string,\n) => {\n if (!RAMMemory[listId]) {\n throw new HttpException(ListNotFound(listId), HttpStatus.NOT_FOUND);\n }",
"score": 0.6989732980728149
},
{
"filename": "src/models/todolist/todolist.ts",
"retrieved_chunk": " Id: string;\n @OneToMany(() => Task, task => task.todoList)\n Tasks?: Task[];\n}",
"score": 0.6709451675415039
}
] | typescript | appService.UpdateListName(listId, newName); |
import JSON5 from 'json5'
import { validate } from 'jsonschema'
import { AudienceIntentInfo, PostOutline, SeoInfo } from '../types'
export class PostOutlineValidationError extends Error {
constructor (message: string, public readonly errors: any[]) {
super(message)
}
}
const schemaValidiation = {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
properties: {
title: {
type: 'string'
},
headings: {
type: 'array',
items: {
$ref: '#/definitions/Heading'
}
},
slug: {
type: 'string'
},
seoTitle: {
type: 'string'
},
seoDescription: {
type: 'string'
}
},
required: [
'title',
'headings',
'slug',
'seoTitle',
'seoDescription'
],
additionalProperties: false,
definitions: {
Heading: {
type: 'object',
properties: {
title: {
type: 'string'
},
keywords: {
type: 'array',
items: {
type: 'string'
}
},
headings: {
type: 'array',
items: {
$ref: '#/definitions/Heading'
}
}
},
required: [
'title'
],
additionalProperties: false
}
}
}
export function extractCodeBlock (text: string): string {
// Extract code blocks with specified tags
const codeBlockTags = ['markdown', 'html', 'json']
for (const tag of codeBlockTags) {
const regex = new RegExp(`\`\`\`${tag}((.|\\n|\\r)*?)\`\`\``, 'i')
const match = text.match(regex)
if (match) {
return match[1]
}
}
// Extract code blocks without specified tags
const genericRegex = /```\n?((.|\\n|\\r)*?)```/
const genericMatch = text.match(genericRegex)
if (genericMatch) {
return genericMatch[1]
}
// No code blocks found
return text
}
export function extractPostOutlineFromCodeBlock (text: | string) : PostOutline { |
// Use JSON5 because it supports trailing comma and comments in the json text
const jsonData = JSON5.parse(extractCodeBlock(text))
const v = validate(jsonData, schemaValidiation)
if (!v.valid) {
const errorList = v.errors.map((val) => val.toString())
throw new PostOutlineValidationError('Invalid json for the post outline', errorList)
}
return jsonData
}
export function extractJsonArray (text : string) : string[] {
return JSON5.parse(extractCodeBlock(text))
}
export function extractSeoInfo (text : string) : SeoInfo {
return JSON5.parse(extractCodeBlock(text))
}
export function extractAudienceIntentInfo (text : string) : AudienceIntentInfo {
return JSON5.parse(extractCodeBlock(text))
}
| src/lib/extractor.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/template.ts",
"retrieved_chunk": "export function extractPrompts (template: string): string[] {\n const regex = /{\\d+:((?:.|\\n)*?)}/g\n return Array.from(template.matchAll(regex)).map((match) => match[1].trim())\n}\nexport function replacePrompt (template: string, index: number, content: string): string {\n const regex = new RegExp(`{${index}:((?:.|\\n)*?)}`)\n return template.replace(regex, content)\n}\nexport function replaceAllPrompts (template: string, contents: string[]): string {\n // We are removing the first prompt because it is the system prompt",
"score": 0.8102149963378906
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " async generateConclusion () {\n const response = await this.sendRequest(getPromptForConclusion(), this.completionParams)\n return extractCodeBlock(response.text)\n }\n async generateHeadingContents (postOutline : PostOutline) {\n const headingLevel = 2\n return await this.buildContent(postOutline.headings, headingLevel)\n }\n private async buildContent (headings: Heading[], headingLevel : number, previousContent: string = ''): Promise<string> {\n if (headings.length === 0) {",
"score": 0.7818508148193359
},
{
"filename": "src/bin/command/post.ts",
"retrieved_chunk": "}\nfunction getFileExtension (options : Options) {\n // in custom mode, we use the template extension\n // in auto/default mode, we use the markdown extension in all cases\n return isCustom(options) ? options.templateFile.split('.').pop() : 'md'\n}\nfunction buildMDPage (post: Post) {\n return '# ' + post.title + '\\n' + post.content\n}\nfunction buildHTMLPage (post : Post) {",
"score": 0.7675656080245972
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " return this.buildContent(remainingHeadings, headingLevel, content)\n }\n private async getContent (heading: Heading): Promise<string> {\n if (this.postPrompt.debug) {\n console.log(`\\nHeading : ${heading.title} ...'\\n`)\n }\n const response = await this.sendRequest(getPromptForHeading(this.postPrompt.tone, heading.title, heading.keywords), this.completionParams)\n return `${extractCodeBlock(response.text)}\\n`\n }\n // -----------------------------------------------",
"score": 0.7578070759773254
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " log('---------- SEO INFO ----------')\n console.log(this.chatParentMessage.text)\n }\n return extractSeoInfo(this.chatParentMessage.text)\n }\n private async readTemplate () : Promise<string> {\n const templatePath = this.postPrompt.templateFile\n return await readFile(templatePath, 'utf-8')\n }\n // -----------------------------------------------",
"score": 0.7542358636856079
}
] | typescript | string) : PostOutline { |
import { PostPrompt } from '../types'
const STRUCTURE_OUTLINE = 'Generate the blog post outline with the following JSON format: ' +
'{"title": "", // Add the post title here ' +
'"headings" : [ { "title": "", // Add the heading title here ' +
'"keywords": ["...", "...", "...", "..."], // Add a list of keywords here. They will help to generate the final content of this heading.' +
'"headings": [ // If necessary, add subheadings here. This is optional.' +
'{ "title": "", ' + '"keywords": ["...", "..."] },' +
'{ "title": "", "keywords": ["...", "..."] }, ... ] } ... ],' +
'"slug" : "", // Use the main keywords for the slug based on the topic of the post. Do not mention the country. Max 3 or 4 keywords, without stop words and with text normalization and accent stripping.' +
'"seoTitle" : "", // Not the same as the post title, max 60 characters, do not mention the country.' +
'"seoDescription : "" // Max 155 characters }'
const INFORMATIVE_INTRO_PROMPT = 'Compose the introduction for this blog post topic, without using phrases such as, "In this article,..." to introduce the subject.' +
'Instead, explain the context and/or explain the main problem. If necessary, mention facts to help the user better understand the context or the problem. Do not describe or introduce the content of the different headings of the outline.' +
'Do not add a heading. Your responses should be in the markdown format. Do not add the title in the beginning of the introduction.'
const CAPTIVATING_INTO_PROMPT = 'Compose a captivating introduction for this blog post topic, without using phrases such as, "In this article,..." to introduce the subject.' +
'Instead, focus on creating a hook to capture the reader\'s attention, setting the tone and style, and seamlessly leading the reader into the main content of the article.' +
'Your introduction should entice readers to continue reading the article and learn more about the subject presented.' +
' Do not add a heading. Your responses should be in the markdown format. Do not add the title in the beginning of the introduction.'
// ------------------------------------------------------
// PROMPTS FOR THE INTERACTIVE / AUTO MODE
// ------------------------------------------------------
export function getAutoSystemPrompt (postPrompt : PostPrompt) {
return 'You are a copywriter with a strong expertise in SEO. I need a detailed blog post in ' + postPrompt.language + ' about the topic: "' + postPrompt.topic + '".' +
'Do not add a paragraph summarizing your response/explanation at the end of your answers.'
}
export function getPromptForIntentAudience (postPrompt : PostPrompt) {
return 'For a post based on the topic : ' + postPrompt.topic + ', describe the ideal audience and intent for this topic.' +
'Write maximum 3 statements for the audience and also 3 statements for the intent.' +
'Your response should be only the following object in json format : ' +
'{"audience" : "", "intent": ""}'
}
export function getPromptForOutline (postPrompt : PostPrompt) {
const { country, intent, audience } = postPrompt
const prompt = STRUCTURE_OUTLINE +
'For the title and headings, do not capitalize words unless the first one.' +
'Please make sure your title is clear, concise, and accurately represents the topic of the post.' +
'Do not add a heading for an introduction, conclusion, or to summarize the article.' +
(country ? 'Market/country/region:' + country + '.' : '') +
(audience ? 'Audience: ' + audience + '.' : '') +
(intent ? 'Content intent: ' + intent + '.' : '')
return prompt
}
export function getPromptForMainKeyword () {
const prompt = 'Give me the most important SEO keyword in a JSON array in which each item matches a word without the stop words.'
return prompt
}
export function getPromptForIntroduction (postPrompt : PostPrompt) {
return ( | !postPrompt.tone) || postPrompt.tone === 'informative' ? INFORMATIVE_INTRO_PROMPT : CAPTIVATING_INTO_PROMPT
} |
export function getPromptForHeading (tone : string, title : string, keywords : string[] | null) {
return tone === 'informative' ? getPromptForInformativeHeading(title, keywords) : getPromptForCaptivatingHeading(title, keywords)
}
export function getPromptForConclusion () {
return 'Write a compelling conclusion for this blog post topic without using transitional phrases such as, "In conclusion", "In summary", "In short", "So", "Thus", or any other transitional expressions.' +
'Focus on summarizing the main points of the post, emphasizing the significance of the topic, and leaving the reader with a lasting impression or a thought-provoking final remark.' +
'Ensure that your conclusion effectively wraps up the article and reinforces the central message or insights presented in the blog post.' +
'Do not add a heading. Your responses should be in the markdown format.'
}
function getPromptForInformativeHeading (title : string, keywords : string[] | null) {
const promptAboutKeywords = keywords ? ' based on the following list of keywords: ' + keywords.join(', ') + '.' : ''
return 'Write some informative content for the heading (without the heading) "' + title + '"' + promptAboutKeywords +
'Make sure to provide in-depth information and valuable insights. Use clear and concise language, along with relevant examples or anecdotes if needed.' +
'Do not start the first sentence with the heading. Instead, start with a sentence that introduces and provides context for the heading.' +
'I do not want a conclusion or summary at the end of the generated text. Just the information requested. ' +
'This rule applies to all languages. ' +
'So do not add a paragraph at the end of your text beginning with one of the following words or variants: in conclusion, in sum, to conclude, in summary, ... ' +
'Your response should be in the markdown format.'
}
function getPromptForCaptivatingHeading (title : string, keywords : string[] | null) {
const promptAboutKeywords = keywords ? ' based on the following list of keywords: ' + keywords.join(', ') + '.' : ''
return 'Write some captivating content for the heading (without the heading): "' + title + '"' + promptAboutKeywords +
'Make sure to provide in-depth information and valuable insights. Use clear and concise language, along with relevant examples or anecdotes, to engage the reader and enhance their understanding.' +
'Do not start the first sentence with the heading. Instead, start with a sentence that introduces and provides context for the heading.' +
'I do not want a conclusion or summary at the end of the generated text. Just the information requested. ' +
'This rule applies to all languages. ' +
'So do not add a paragraph at the end of your text beginning with one of the following words or variants: in conclusion, in sum, to conclude, in summary, ... ' +
'Your response should be in the markdown format.'
}
// ------------------------------------------------------
// PROMPTS FOR THE CUSTOM MODE (based on a template)
// ------------------------------------------------------
export function getCustomSystemPrompt (postPrompt : PostPrompt) {
// The prompt with the index 0 in the template is the system prompt
return postPrompt.prompts[0] + '\n' + ' Language: ' + postPrompt.language + '. '
}
export function getSeoSystemPrompt (postPrompt : PostPrompt) {
return 'You are a SEO expert and you need to optimize a web page based on the following info in ' + postPrompt.language + ': ' +
'\n' + postPrompt.prompts[0]
}
export function getPromptForSeoInfo (postPrompt : PostPrompt) {
return 'For content based on the topic of this conversation, Use the H1 provided in the system prompt. If not, write a new H1. ' +
'Use the slug provided in the system prompt. If not, write a new slug.' +
'Write an SEO title and an SEO description for this blog post.' +
'The SEO title should be no more than 60 characters long.' +
'The H1 and the title should be different.' +
'The SEO description should be no more than 155 characters long.' +
'Use the main keywords for the slug based on the topic of the post. Do not mention the country. Max 3 or 4 keywords, without stop words, and with text normalization and accent stripping.' +
'Your response should be in the JSON format based on the following structure: ' +
'{"h1" : "", "seoTitle": "", "": "seoDescription": "", "slug": ""}'
}
| src/lib/prompts.ts | christophebe-julius-gpt-771c35b | [
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " console.log('Presence Penalty : ' + this.completionParams.presence_penalty)\n console.log('Logit Biais : ' + this.completionParams.logit_bias)\n }\n }\n // -----------------------------------------------\n // METHODS FOR THE AUTOMATIC MODE\n // -----------------------------------------------\n async generateMainKeyword () {\n const prompt = getPromptForMainKeyword()\n if (this.postPrompt.debug) {",
"score": 0.8270021677017212
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " // METHODS FOR THE CUSTOM MODE base on a template\n // -----------------------------------------------\n /**\n * Generate a content based on one of prompt defined in the template\n * @param customPrompt : the prompt defined in the template\n * @returns the AI answer\n */\n async generateCustomPrompt (customPrompt : string) {\n this.chatParentMessage = await this.sendRequest(customPrompt, this.completionParams)\n return extractCodeBlock(this.chatParentMessage.text)",
"score": 0.823218822479248
},
{
"filename": "src/post.ts",
"retrieved_chunk": " )\n promptContents.push(content)\n }\n // We replace the prompts by the AI answer in the template content\n const content = replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents)\n const seoInfo = await oraPromise(\n this.helper.generateSeoInfo(),\n {\n text: 'Generating SEO info ...'\n }",
"score": 0.8147860765457153
},
{
"filename": "src/post.ts",
"retrieved_chunk": " * Generate a post using the custom prompt based on a template\n */\n private async customGenerate () : Promise<Post> {\n const promptContents = []\n await oraPromise(\n this.helper.init(),\n {\n text: ' Init the completion parameters ...'\n }\n )",
"score": 0.8116416931152344
},
{
"filename": "src/lib/post-helpers.ts",
"retrieved_chunk": " console.log('---------- PROMPT OUTLINE ----------')\n console.log(prompt)\n }\n // the parent message is the outline for the upcoming content\n // By this way, we can decrease the cost of the API call by minimizing the number of prompt tokens\n // TODO : add an option to disable this feature\n this.chatParentMessage = await this.sendRequest(prompt)\n if (this.postPrompt.debug) {\n console.log('---------- OUTLINE ----------')\n console.log(this.chatParentMessage.text)",
"score": 0.809337854385376
}
] | typescript | !postPrompt.tone) || postPrompt.tone === 'informative' ? INFORMATIVE_INTRO_PROMPT : CAPTIVATING_INTO_PROMPT
} |
import {
CollectionAfterChangeHook,
CollectionConfig,
Field,
GlobalConfig,
GlobalAfterChangeHook,
PayloadRequest,
} from "payload/types";
import { Descendant } from "slate";
import { PluginOptions } from "../../types";
import {
buildCrowdinHtmlObject,
buildCrowdinJsonObject,
convertSlateToHtml,
fieldChanged,
} from "../../utilities";
import deepEqual from "deep-equal";
import { getLocalizedFields } from "../../utilities";
import { payloadCrowdinSyncFilesApi } from "../../api/payload-crowdin-sync/files";
/**
* Update Crowdin collections and make updates in Crowdin
*
* This functionality used to be split into field hooks.
* However, it is more reliable to loop through localized
* fields and perform opeerations in one place. The
* asynchronous nature of operations means that
* we need to be careful updates are not made sooner than
* expected.
*/
interface CommonArgs {
pluginOptions: PluginOptions;
}
interface Args extends CommonArgs {
collection: CollectionConfig;
}
interface GlobalArgs extends CommonArgs {
global: GlobalConfig;
}
export const getGlobalAfterChangeHook =
({ global, pluginOptions }: GlobalArgs): GlobalAfterChangeHook =>
async ({
doc, // full document data
previousDoc, // document data before updating the collection
req, // full express request
}) => {
const operation = previousDoc ? "update" : "create";
return performAfterChange({
doc,
req,
previousDoc,
operation,
collection: global,
global: true,
pluginOptions,
});
};
export const getAfterChangeHook =
({ collection, pluginOptions }: Args): CollectionAfterChangeHook =>
async ({
doc, // full document data
req, // full express request
previousDoc, // document data before updating the collection
operation, // name of the operation ie. 'create', 'update'
}) => {
return performAfterChange({
doc,
req,
previousDoc,
operation,
collection,
pluginOptions,
});
};
interface IPerformChange {
doc: any;
req: PayloadRequest;
previousDoc: any;
operation: string;
collection: CollectionConfig | GlobalConfig;
global?: boolean;
pluginOptions: PluginOptions;
}
const performAfterChange = async ({
doc, // full document data
req, // full express request
previousDoc,
operation,
collection,
global = false,
pluginOptions,
}: IPerformChange) => {
/**
* Abort if token not set and not in test mode
*/
if (!pluginOptions.token && process.env.NODE_ENV !== "test") {
return doc;
}
const localizedFields: Field[] = getLocalizedFields({
fields: collection.fields,
});
/**
* Abort if there are no fields to localize
*/
if (localizedFields.length === 0) {
return doc;
}
/**
* Abort if locale is unavailable or this
* is an update from the API to the source
* locale.
*/
if (!req.locale || req.locale !== pluginOptions.sourceLocale) {
return doc;
}
/**
* Prepare JSON objects
*
* `text` fields are compiled into a single JSON file
* on Crowdin. Prepare previous and current objects.
*/
const currentCrowdinJsonData = buildCrowdinJsonObject({
doc,
fields: localizedFields,
});
const prevCrowdinJsonData = buildCrowdinJsonObject({
doc: previousDoc,
fields: localizedFields,
});
/**
* Initialize Crowdin client sourceFilesApi
*/
const filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, req.payload);
/**
* Retrieve the Crowdin Article Directory article
*
* Records of Crowdin directories are stored in Payload.
*/
const articleDirectory = | await filesApi.findOrCreateArticleDirectory({ |
document: doc,
collectionSlug: collection.slug,
global,
});
// START: function definitions
const createOrUpdateJsonFile = async () => {
await filesApi.createOrUpdateFile({
name: "fields",
value: currentCrowdinJsonData,
fileType: "json",
articleDirectory,
});
};
const createOrUpdateHtmlFile = async ({
name,
value,
}: {
name: string;
value: Descendant[];
}) => {
await filesApi.createOrUpdateFile({
name: name,
value: convertSlateToHtml(value),
fileType: "html",
articleDirectory,
});
};
const createOrUpdateJsonSource = async () => {
if (
(!deepEqual(currentCrowdinJsonData, prevCrowdinJsonData) &&
Object.keys(currentCrowdinJsonData).length !== 0) ||
process.env.PAYLOAD_CROWDIN_SYNC_ALWAYS_UPDATE === "true"
) {
await createOrUpdateJsonFile();
}
};
/**
* Recursively send rich text fields to Crowdin as HTML
*
* Name these HTML files with dot notation. Examples:
*
* * `localizedRichTextField`
* * `groupField.localizedRichTextField`
* * `arrayField[0].localizedRichTextField`
* * `arrayField[1].localizedRichTextField`
*/
const createOrUpdateHtmlSource = async () => {
const currentCrowdinHtmlData = buildCrowdinHtmlObject({
doc,
fields: localizedFields,
});
const prevCrowdinHtmlData = buildCrowdinHtmlObject({
doc: previousDoc,
fields: localizedFields,
});
Object.keys(currentCrowdinHtmlData).forEach(async (name) => {
const currentValue = currentCrowdinHtmlData[name];
const prevValue = prevCrowdinHtmlData[name];
if (
!fieldChanged(prevValue, currentValue, "richText") &&
process.env.PAYLOAD_CROWDIN_SYNC_ALWAYS_UPDATE !== "true"
) {
return;
}
const file = await createOrUpdateHtmlFile({
name,
value: currentValue as Descendant[],
});
});
};
// END: function definitions
await createOrUpdateJsonSource();
await createOrUpdateHtmlSource();
return doc;
};
| src/hooks/collections/afterChange.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/helpers.ts",
"retrieved_chunk": "import { Payload } from \"payload\";\nimport { IcrowdinFile } from \"./payload-crowdin-sync/files\";\n/**\n * get Crowdin Article Directory for a given documentId\n *\n * The Crowdin Article Directory is associated with a document,\n * so is easy to retrieve. Use this function when you only have\n * a document id.\n */\nexport async function getArticleDirectory(",
"score": 0.8688229918479919
},
{
"filename": "src/api/helpers.ts",
"retrieved_chunk": " return getFile(name, articleDirectory.id, payload);\n}\nexport async function getFilesByDocumentID(\n documentId: string,\n payload: Payload\n): Promise<IcrowdinFile[]> {\n const articleDirectory = await getArticleDirectory(documentId, payload);\n if (!articleDirectory) {\n // tests call this function to make sure files are deleted\n return [];",
"score": 0.8643370866775513
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " // Create file on Crowdin\n const crowdinFile = await this.crowdinCreateFile({\n directoryId: articleDirectory.originalId,\n name: name,\n fileData: value,\n fileType: fileType,\n });\n // createFile has been intermittent in not being available\n // perhaps logic goes wrong somewhere and express middleware\n // is hard to debug?",
"score": 0.8600636720657349
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " } else {\n const crowdinPayloadCollectionDirectory =\n await this.findOrCreateCollectionDirectory({\n collectionSlug: global ? \"globals\" : collectionSlug,\n });\n // Create article directory on Crowdin\n const crowdinDirectory = await this.sourceFilesApi.createDirectory(\n this.projectId,\n {\n directoryId: crowdinPayloadCollectionDirectory.originalId,",
"score": 0.8593688011169434
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " : uploadStorageApi;\n this.payload = payload;\n }\n async findOrCreateArticleDirectory({\n document,\n collectionSlug,\n global = false,\n }: IfindOrCreateArticleDirectory) {\n let crowdinPayloadArticleDirectory;\n if (document.crowdinArticleDirectory) {",
"score": 0.8530503511428833
}
] | typescript | await filesApi.findOrCreateArticleDirectory({ |
import {
CollectionAfterChangeHook,
CollectionConfig,
Field,
GlobalConfig,
GlobalAfterChangeHook,
PayloadRequest,
} from "payload/types";
import { Descendant } from "slate";
import { PluginOptions } from "../../types";
import {
buildCrowdinHtmlObject,
buildCrowdinJsonObject,
convertSlateToHtml,
fieldChanged,
} from "../../utilities";
import deepEqual from "deep-equal";
import { getLocalizedFields } from "../../utilities";
import { payloadCrowdinSyncFilesApi } from "../../api/payload-crowdin-sync/files";
/**
* Update Crowdin collections and make updates in Crowdin
*
* This functionality used to be split into field hooks.
* However, it is more reliable to loop through localized
* fields and perform opeerations in one place. The
* asynchronous nature of operations means that
* we need to be careful updates are not made sooner than
* expected.
*/
interface CommonArgs {
pluginOptions: PluginOptions;
}
interface Args extends CommonArgs {
collection: CollectionConfig;
}
interface GlobalArgs extends CommonArgs {
global: GlobalConfig;
}
export const getGlobalAfterChangeHook =
({ global, pluginOptions }: GlobalArgs): GlobalAfterChangeHook =>
async ({
doc, // full document data
previousDoc, // document data before updating the collection
req, // full express request
}) => {
const operation = previousDoc ? "update" : "create";
return performAfterChange({
doc,
req,
previousDoc,
operation,
collection: global,
global: true,
pluginOptions,
});
};
export const getAfterChangeHook =
({ collection, pluginOptions }: Args): CollectionAfterChangeHook =>
async ({
doc, // full document data
req, // full express request
previousDoc, // document data before updating the collection
operation, // name of the operation ie. 'create', 'update'
}) => {
return performAfterChange({
doc,
req,
previousDoc,
operation,
collection,
pluginOptions,
});
};
interface IPerformChange {
doc: any;
req: PayloadRequest;
previousDoc: any;
operation: string;
collection: CollectionConfig | GlobalConfig;
global?: boolean;
pluginOptions: PluginOptions;
}
const performAfterChange = async ({
doc, // full document data
req, // full express request
previousDoc,
operation,
collection,
global = false,
pluginOptions,
}: IPerformChange) => {
/**
* Abort if token not set and not in test mode
*/
if (!pluginOptions.token && process.env.NODE_ENV !== "test") {
return doc;
}
const localizedFields: Field[] = getLocalizedFields({
fields: collection.fields,
});
/**
* Abort if there are no fields to localize
*/
if (localizedFields.length === 0) {
return doc;
}
/**
* Abort if locale is unavailable or this
* is an update from the API to the source
* locale.
*/
if (!req.locale || req.locale !== pluginOptions.sourceLocale) {
return doc;
}
/**
* Prepare JSON objects
*
* `text` fields are compiled into a single JSON file
* on Crowdin. Prepare previous and current objects.
*/
const currentCrowdinJsonData = buildCrowdinJsonObject({
doc,
fields: localizedFields,
});
const prevCrowdinJsonData = buildCrowdinJsonObject({
doc: previousDoc,
fields: localizedFields,
});
/**
* Initialize Crowdin client sourceFilesApi
*/
const filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, req.payload);
/**
* Retrieve the Crowdin Article Directory article
*
* Records of Crowdin directories are stored in Payload.
*/
const articleDirectory = await filesApi.findOrCreateArticleDirectory({
document: doc,
collectionSlug: collection.slug,
global,
});
// START: function definitions
const createOrUpdateJsonFile = async () => {
await | filesApi.createOrUpdateFile({ |
name: "fields",
value: currentCrowdinJsonData,
fileType: "json",
articleDirectory,
});
};
const createOrUpdateHtmlFile = async ({
name,
value,
}: {
name: string;
value: Descendant[];
}) => {
await filesApi.createOrUpdateFile({
name: name,
value: convertSlateToHtml(value),
fileType: "html",
articleDirectory,
});
};
const createOrUpdateJsonSource = async () => {
if (
(!deepEqual(currentCrowdinJsonData, prevCrowdinJsonData) &&
Object.keys(currentCrowdinJsonData).length !== 0) ||
process.env.PAYLOAD_CROWDIN_SYNC_ALWAYS_UPDATE === "true"
) {
await createOrUpdateJsonFile();
}
};
/**
* Recursively send rich text fields to Crowdin as HTML
*
* Name these HTML files with dot notation. Examples:
*
* * `localizedRichTextField`
* * `groupField.localizedRichTextField`
* * `arrayField[0].localizedRichTextField`
* * `arrayField[1].localizedRichTextField`
*/
const createOrUpdateHtmlSource = async () => {
const currentCrowdinHtmlData = buildCrowdinHtmlObject({
doc,
fields: localizedFields,
});
const prevCrowdinHtmlData = buildCrowdinHtmlObject({
doc: previousDoc,
fields: localizedFields,
});
Object.keys(currentCrowdinHtmlData).forEach(async (name) => {
const currentValue = currentCrowdinHtmlData[name];
const prevValue = prevCrowdinHtmlData[name];
if (
!fieldChanged(prevValue, currentValue, "richText") &&
process.env.PAYLOAD_CROWDIN_SYNC_ALWAYS_UPDATE !== "true"
) {
return;
}
const file = await createOrUpdateHtmlFile({
name,
value: currentValue as Descendant[],
});
});
};
// END: function definitions
await createOrUpdateJsonSource();
await createOrUpdateHtmlSource();
return doc;
};
| src/hooks/collections/afterChange.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " async getTranslation({ documentId, fieldName, locale }: IgetTranslation) {\n const articleDirectory = await this.filesApi.getArticleDirectory(\n documentId\n );\n const file = await this.filesApi.getFile(fieldName, articleDirectory.id);\n // it is possible a file doesn't exist yet - e.g. an article with localized text fields that contains an empty html field.\n if (!file) {\n return;\n }\n try {",
"score": 0.885435938835144
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " : uploadStorageApi;\n this.payload = payload;\n }\n async findOrCreateArticleDirectory({\n document,\n collectionSlug,\n global = false,\n }: IfindOrCreateArticleDirectory) {\n let crowdinPayloadArticleDirectory;\n if (document.crowdinArticleDirectory) {",
"score": 0.8835941553115845
},
{
"filename": "src/api/helpers.ts",
"retrieved_chunk": " return getFile(name, articleDirectory.id, payload);\n}\nexport async function getFilesByDocumentID(\n documentId: string,\n payload: Payload\n): Promise<IcrowdinFile[]> {\n const articleDirectory = await getArticleDirectory(documentId, payload);\n if (!articleDirectory) {\n // tests call this function to make sure files are deleted\n return [];",
"score": 0.8832070231437683
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " console.error(error, options);\n }\n }\n async getArticleDirectory(documentId: string) {\n const result = await getArticleDirectory(documentId, this.payload);\n return result;\n }\n async deleteFilesAndDirectory(documentId: string) {\n const files = await this.getFilesByDocumentID(documentId);\n for (const file of files) {",
"score": 0.8748128414154053
},
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " if (global) {\n const update = await this.payload.updateGlobal({\n slug: collectionSlug,\n data: {\n crowdinArticleDirectory: crowdinPayloadArticleDirectory.id,\n },\n });\n } else {\n const update = await this.payload.update({\n collection: collectionSlug,",
"score": 0.8665685653686523
}
] | typescript | filesApi.createOrUpdateFile({ |
import {
Block,
CollapsibleField,
CollectionConfig,
Field,
GlobalConfig,
} from "payload/types";
import deepEqual from "deep-equal";
import { FieldWithName } from "../types";
import { slateToHtml, payloadSlateToDomConfig } from "slate-serializers";
import type { Descendant } from "slate";
import { get, isEmpty, map, merge, omitBy } from "lodash";
import dot from "dot-object";
const localizedFieldTypes = ["richText", "text", "textarea"];
const nestedFieldTypes = ["array", "group", "blocks"];
export const containsNestedFields = (field: Field) =>
nestedFieldTypes.includes(field.type);
export const getLocalizedFields = ({
fields,
type,
localizedParent = false,
}: {
fields: Field[];
type?: "json" | "html";
localizedParent?: boolean;
}): any[] => {
const localizedFields = getLocalizedFieldsRecursive({
fields,
type,
localizedParent,
});
return localizedFields;
};
export const getLocalizedFieldsRecursive = ({
fields,
type,
localizedParent = false,
}: {
fields: Field[];
type?: "json" | "html";
localizedParent?: boolean;
}): any[] => [
...fields
// localized or group fields only.
.filter(
(field) =>
isLocalizedField(field, localizedParent) || containsNestedFields(field)
)
// further filter on Crowdin field type
.filter((field) => {
if (containsNestedFields(field)) {
return true;
}
return type
? fieldCrowdinFileType(field as FieldWithName) === type
: true;
})
// exclude group, array and block fields with no localized fields
// TODO: find a better way to do this - block, array and group logic is duplicated, and this filter needs to be compatible with field extraction logic later in this function
.filter((field) => {
const localizedParent = hasLocalizedProp(field);
if (field.type === "group" || field.type === "array") {
return containsLocalizedFields({
fields: field.fields,
type,
localizedParent,
});
}
if (field.type === "blocks") {
return field.blocks.find((block) =>
containsLocalizedFields({
fields: block.fields,
type,
localizedParent,
})
);
}
return true;
})
// recursion for group, array and blocks field
.map((field) => {
const localizedParent = hasLocalizedProp(field);
if (field.type === "group" || field.type === "array") {
return {
...field,
fields: getLocalizedFields({
fields: field.fields,
type,
localizedParent,
}),
};
}
if (field.type === "blocks") {
const blocks = field.blocks
.map((block: Block) => {
if (
containsLocalizedFields({
fields: block.fields,
type,
localizedParent,
})
) {
return {
slug: block.slug,
fields: getLocalizedFields({
fields: block.fields,
type,
localizedParent,
}),
};
}
})
.filter((block) => block);
return {
...field,
blocks,
};
}
return field;
})
.filter(
(field) =>
(field as any).type !== "collapsible" && (field as any).type !== "tabs"
),
...convertTabs({ fields }),
// recursion for collapsible field - flatten results into the returned array
...getCollapsibleLocalizedFields({ fields, type }),
];
export const getCollapsibleLocalizedFields = ({
fields,
type,
}: {
fields: Field[];
type?: "json" | "html";
}): any[] =>
fields
.filter((field) => field.type === "collapsible")
.flatMap((field) =>
getLocalizedFields({
fields: (field as CollapsibleField).fields,
type,
})
);
export const convertTabs = ({
fields,
type,
}: {
fields: Field[];
type?: "json" | "html";
}): any[] =>
fields
.filter((field) => field.type === "tabs")
.flatMap((field) => {
if (field.type === "tabs") {
const flattenedFields = field.tabs.reduce((tabFields, tab) => {
return [
...tabFields,
"name" in tab
? ({
type: "group",
name: tab.name,
fields: tab.fields,
} as Field)
: ({
label: "fromTab",
type: "collapsible",
fields: tab.fields,
} as Field),
];
}, [] as Field[]);
return getLocalizedFields({
fields: flattenedFields,
type,
});
}
return field;
});
export const getLocalizedRequiredFields = (
collection: CollectionConfig | GlobalConfig,
type?: "json" | "html"
): any[] => {
const fields = getLocalizedFields({ fields: collection.fields, type });
return fields.filter((field) => field.required);
};
/**
* Not yet compatible with nested fields - this means nested HTML
* field translations cannot be synced from Crowdin.
*/
export const getFieldSlugs = (fields: FieldWithName[]): string[] =>
fields
.filter(
(field: Field) => field.type === "text" || field.type === "richText"
)
.map((field: FieldWithName) => | field.name); |
const hasLocalizedProp = (field: Field) =>
"localized" in field && field.localized;
/**
* Is Localized Field
*
* Note that `id` should be excluded - it is a `text` field that is added by Payload CMS.
*/
export const isLocalizedField = (
field: Field,
addLocalizedProp: boolean = false
) =>
(hasLocalizedProp(field) || addLocalizedProp) &&
localizedFieldTypes.includes(field.type) &&
!excludeBasedOnDescription(field) &&
(field as any).name !== "id";
const excludeBasedOnDescription = (field: Field) => {
const description = get(field, "admin.description", "");
if (description.includes("Not sent to Crowdin. Localize in the CMS.")) {
return true;
}
return false;
};
export const containsLocalizedFields = ({
fields,
type,
localizedParent,
}: {
fields: Field[];
type?: "json" | "html";
localizedParent?: boolean;
}): boolean => {
return !isEmpty(getLocalizedFields({ fields, type, localizedParent }));
};
export const fieldChanged = (
previousValue: string | object | undefined,
value: string | object | undefined,
type: string
) => {
if (type === "richText") {
return !deepEqual(previousValue || {}, value || {});
}
return previousValue !== value;
};
export const removeLineBreaks = (string: string) =>
string.replace(/(\r\n|\n|\r)/gm, "");
export const fieldCrowdinFileType = (field: FieldWithName): "json" | "html" =>
field.type === "richText" ? "html" : "json";
/**
* Reorder blocks and array values based on the order of the original document.
*/
export const restoreOrder = ({
updateDocument,
document,
fields,
}: {
updateDocument: { [key: string]: any };
document: { [key: string]: any };
fields: Field[];
}) => {
let response: { [key: string]: any } = {};
// it is possible the original document is empty (e.g. new document)
if (!document) {
return updateDocument;
}
fields.forEach((field: any) => {
if (!updateDocument || !updateDocument[field.name]) {
return;
}
if (field.type === "group") {
response[field.name] = restoreOrder({
updateDocument: updateDocument[field.name],
document: document[field.name],
fields: field.fields,
});
} else if (field.type === "array" || field.type === "blocks") {
response[field.name] = document[field.name]
.map((item: any) => {
const arrayItem = updateDocument[field.name].find(
(updateItem: any) => {
return updateItem.id === item.id;
}
);
if (!arrayItem) {
return;
}
const subFields =
field.type === "blocks"
? field.blocks.find(
(block: Block) => block.slug === item.blockType
)?.fields || []
: field.fields;
return {
...restoreOrder({
updateDocument: arrayItem,
document: item,
fields: subFields,
}),
id: arrayItem.id,
...(field.type === "blocks" && { blockType: arrayItem.blockType }),
};
})
.filter((item: any) => !isEmpty(item));
} else {
response[field.name] = updateDocument[field.name];
}
});
return response;
};
/**
* Convert Crowdin objects to Payload CMS data objects.
*
* * `crowdinJsonObject` is the JSON object returned from Crowdin.
* * `crowdinHtmlObject` is the HTML object returned from Crowdin. Optional. Merged into resulting object if provided.
* * `fields` is the collection or global fields array.
* * `topLevel` is a flag used internally to filter json fields before recursion.
* * `document` is the document object. Optional. Used to restore the order of `array` and `blocks` field values.
*/
export const buildPayloadUpdateObject = ({
crowdinJsonObject,
crowdinHtmlObject,
fields,
topLevel = true,
document,
}: {
crowdinJsonObject: { [key: string]: any };
crowdinHtmlObject?: { [key: string]: any };
/** Use getLocalizedFields to pass localized fields only */
fields: Field[];
/** Flag used internally to filter json fields before recursion. */
topLevel?: boolean;
document?: { [key: string]: any };
}) => {
let response: { [key: string]: any } = {};
if (crowdinHtmlObject) {
const destructured = dot.object(crowdinHtmlObject);
merge(crowdinJsonObject, destructured);
}
const filteredFields = topLevel
? getLocalizedFields({
fields,
type: !crowdinHtmlObject ? "json" : undefined,
})
: fields;
filteredFields.forEach((field) => {
if (!crowdinJsonObject[field.name]) {
return;
}
if (field.type === "group") {
response[field.name] = buildPayloadUpdateObject({
crowdinJsonObject: crowdinJsonObject[field.name],
fields: field.fields,
topLevel: false,
});
} else if (field.type === "array") {
response[field.name] = map(crowdinJsonObject[field.name], (item, id) => {
const payloadUpdateObject = buildPayloadUpdateObject({
crowdinJsonObject: item,
fields: field.fields,
topLevel: false,
});
return {
...payloadUpdateObject,
id,
};
}).filter((item: any) => !isEmpty(item));
} else if (field.type === "blocks") {
response[field.name] = map(crowdinJsonObject[field.name], (item, id) => {
// get first and only object key
const blockType = Object.keys(item)[0];
const payloadUpdateObject = buildPayloadUpdateObject({
crowdinJsonObject: item[blockType],
fields:
field.blocks.find((block: Block) => block.slug === blockType)
?.fields || [],
topLevel: false,
});
return {
...payloadUpdateObject,
id,
blockType,
};
}).filter((item: any) => !isEmpty(item));
} else {
response[field.name] = crowdinJsonObject[field.name];
}
});
if (document) {
response = restoreOrder({
updateDocument: response,
document,
fields,
});
}
return omitBy(response, isEmpty);
};
export const buildCrowdinJsonObject = ({
doc,
fields,
topLevel = true,
}: {
doc: { [key: string]: any };
/** Use getLocalizedFields to pass localized fields only */
fields: Field[];
/** Flag used internally to filter json fields before recursion. */
topLevel?: boolean;
}) => {
let response: { [key: string]: any } = {};
const filteredFields = topLevel
? getLocalizedFields({ fields, type: "json" })
: fields;
filteredFields.forEach((field) => {
if (!doc[field.name]) {
return;
}
if (field.type === "group") {
response[field.name] = buildCrowdinJsonObject({
doc: doc[field.name],
fields: field.fields,
topLevel: false,
});
} else if (field.type === "array") {
response[field.name] = doc[field.name]
.map((item: any) => {
const crowdinJsonObject = buildCrowdinJsonObject({
doc: item,
fields: field.fields,
topLevel: false,
});
if (!isEmpty(crowdinJsonObject)) {
return {
[item.id]: crowdinJsonObject,
};
}
})
.filter((item: any) => !isEmpty(item))
.reduce((acc: object, item: any) => ({ ...acc, ...item }), {});
} else if (field.type === "blocks") {
response[field.name] = doc[field.name]
.map((item: any) => {
const crowdinJsonObject = buildCrowdinJsonObject({
doc: item,
fields:
field.blocks.find((block: Block) => block.slug === item.blockType)
?.fields || [],
topLevel: false,
});
if (!isEmpty(crowdinJsonObject)) {
return {
[item.id]: {
[item.blockType]: crowdinJsonObject,
},
};
}
})
.filter((item: any) => !isEmpty(item))
.reduce((acc: object, item: any) => ({ ...acc, ...item }), {});
} else {
response[field.name] = doc[field.name];
}
});
return omitBy(response, isEmpty);
};
export const buildCrowdinHtmlObject = ({
doc,
fields,
prefix = "",
topLevel = true,
}: {
doc: { [key: string]: any };
/** Use getLocalizedFields to pass localized fields only */
fields: Field[];
/** Use to build dot notation field during recursion. */
prefix?: string;
/** Flag used internally to filter html fields before recursion. */
topLevel?: boolean;
}) => {
let response: { [key: string]: any } = {};
// it is convenient to be able to pass all fields - filter in this case
const filteredFields = topLevel
? getLocalizedFields({ fields, type: "html" })
: fields;
filteredFields.forEach((field) => {
const name = [prefix, (field as FieldWithName).name]
.filter((string) => string)
.join(".");
if (!doc[field.name]) {
return;
}
if (field.type === "group") {
const subPrefix = `${[prefix, field.name]
.filter((string) => string)
.join(".")}`;
response = {
...response,
...buildCrowdinHtmlObject({
doc: doc[field.name],
fields: field.fields,
prefix: subPrefix,
topLevel: false,
}),
};
} else if (field.type === "array") {
const arrayValues = doc[field.name].map((item: any, index: number) => {
const subPrefix = `${[prefix, `${field.name}`, `${item.id}`]
.filter((string) => string)
.join(".")}`;
return buildCrowdinHtmlObject({
doc: item,
fields: field.fields,
prefix: subPrefix,
topLevel: false,
});
});
response = {
...response,
...merge({}, ...arrayValues),
};
} else if (field.type === "blocks") {
const arrayValues = doc[field.name].map((item: any, index: number) => {
const subPrefix = `${[
prefix,
`${field.name}`,
`${item.id}`,
`${item.blockType}`,
]
.filter((string) => string)
.join(".")}`;
return buildCrowdinHtmlObject({
doc: item,
fields:
field.blocks.find((block: Block) => block.slug === item.blockType)
?.fields || [],
prefix: subPrefix,
topLevel: false,
});
});
response = {
...response,
...merge({}, ...arrayValues),
};
} else {
if (doc[field.name]?.en) {
response[name] = doc[field.name].en;
} else {
response[name] = doc[field.name];
}
}
});
return response;
};
export const convertSlateToHtml = (slate: Descendant[]): string => {
return slateToHtml(slate, {
...payloadSlateToDomConfig,
encodeEntities: false,
alwaysEncodeBreakingEntities: true,
});
};
| src/utilities/index.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " return files\n .filter((file: any) => file.type === \"html\")\n .map((file: any) => file.field);\n }\n /**\n * Retrieve translations for a document field name\n *\n * * returns Slate object for html fields\n * * returns all json fields if fieldName is 'fields'\n */",
"score": 0.8692554235458374
},
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " * TODO: make this work for nested blocks.\n */\n restoreIdAndBlockType = (\n document: any,\n translations: any,\n key: string = \"layout\"\n ) => {\n if (translations.hasOwnProperty(key)) {\n translations[key] = translations[key].map(\n (block: any, index: number) => ({",
"score": 0.8362236022949219
},
{
"filename": "src/utilities/containsLocalizedFields.spec.ts",
"retrieved_chunk": " * * help ensure no errors during version 0 development\n * * mitigate against errors if a new field type is introduced by Payload CMS\n */\n it(\"does not include unrecognized field types\", () => {\n const fields: any[] = [\n {\n name: \"textLocalizedField\",\n type: \"text\",\n },\n {",
"score": 0.8275264501571655
},
{
"filename": "src/utilities/containsLocalizedFields.spec.ts",
"retrieved_chunk": " });\n describe(\"extract rich text localized fields\", () => {\n const fields: Field[] = [\n {\n name: \"simpleLocalizedField\",\n type: \"richText\",\n },\n {\n name: \"simpleNonLocalizedField\",\n type: \"text\",",
"score": 0.8274948596954346
},
{
"filename": "src/utilities/tests/buildPayloadUpdateObject/blocks-field-type.spec.ts",
"retrieved_chunk": " },\n },\n };\n const fields: FieldWithName[] = [\n {\n name: \"title\",\n type: \"text\",\n localized: true,\n },\n // select not supported yet",
"score": 0.8251355886459351
}
] | typescript | field.name); |
import {
App,
ButtonComponent,
MarkdownRenderChild,
MarkdownRenderer,
MarkdownRendererConstructorType,
OpenViewState,
TFile,
setIcon,
} from "obsidian";
import { openFile } from "../utils";
import { MaybeNoteRef, RefRange, getRefContentRange, anchorToLinkSubpath } from "../engine/ref";
import { dendronActivityBarName } from "../icons";
const MarkdownRendererConstructor = MarkdownRenderer as unknown as MarkdownRendererConstructorType;
class RefMarkdownRenderer extends MarkdownRendererConstructor {
constructor(public parent: NoteRefRenderChild, queed: boolean) {
super(parent.app, parent.previewEl, queed);
}
get file(): TFile {
return this.parent.file;
}
edit(markdown: string) {
this.parent.editContent(markdown);
}
}
export class NoteRefRenderChild extends MarkdownRenderChild {
previewEl: HTMLElement;
renderer: RefMarkdownRenderer;
file: TFile;
range: RefRange | null;
markdown?: string;
found = false;
constructor(
public readonly app: App,
public readonly containerEl: HTMLElement,
public readonly ref: MaybeNoteRef
) {
super(containerEl);
if (!ref.note || !ref.note.file)
throw Error("NoteRefChild only accept ref with non-blank note and file");
this.file = ref.note.file;
this.containerEl.classList.add("dendron-embed", "markdown-embed", "inline-embed", "is-loaded");
this.containerEl.setText("");
const icon = this.containerEl.createDiv("dendron-icon");
setIcon(icon, dendronActivityBarName);
this.previewEl = this.containerEl.createDiv("markdown-embed-content");
const buttonComponent = new ButtonComponent(this.containerEl);
buttonComponent.buttonEl.remove();
buttonComponent.buttonEl = this.containerEl.createDiv(
"markdown-embed-link"
) as unknown as HTMLButtonElement;
buttonComponent.setIcon("lucide-link").setTooltip("Open link");
buttonComponent.buttonEl.onclick = () => {
const openState: OpenViewState = {};
if (this.ref.subpath) {
openState.eState = {
subpath | : anchorToLinkSubpath(
this.ref.subpath.start,
this.app.metadataCache.getFileCache(this.file)?.headings
),
}; |
}
openFile(this.app, this.ref.note?.file, openState);
};
this.renderer = new RefMarkdownRenderer(this, true);
this.addChild(this.renderer);
}
async getContent(): Promise<string> {
this.markdown = await this.app.vault.cachedRead(this.file);
if (!this.ref.subpath) {
this.found = true;
return this.markdown;
}
const metadata = this.app.metadataCache.getFileCache(this.file);
if (metadata) {
this.range = getRefContentRange(this.ref.subpath, metadata);
if (this.range) {
let currentLineIndex = 0;
while (currentLineIndex < this.range.startLineOffset) {
if (this.markdown[this.range.start] === "\n") currentLineIndex++;
this.range.start++;
}
this.found = true;
return this.markdown.substring(this.range.start, this.range.end);
}
}
this.found = false;
return "### Unable to find section "
.concat(this.ref.subpath.text, " in ")
.concat(this.file.basename);
}
editContent(target: string) {
if (!this.found || !this.markdown) return;
let md;
if (!this.range) {
md = target;
} else {
const before = this.markdown.substring(0, this.range.start);
md = before + target;
if (this.range.end) {
const after = this.markdown.substring(this.range.end);
md += after;
}
}
this.app.vault.modify(this.file, md);
}
async loadFile() {
const content = await this.getContent();
this.renderer.renderer.set(content);
}
onload(): void {
super.onload();
this.registerEvent(
this.app.metadataCache.on("changed", async (file, data) => {
if (file === this.file) {
this.loadFile();
}
})
);
}
}
export class UnresolvedRefRenderChild extends MarkdownRenderChild {
constructor(app: App, containerEl: HTMLElement, target: MaybeNoteRef) {
super(containerEl);
this.containerEl.classList.add("dendron-embed", "file-embed", "mod-empty", "is-loaded");
this.containerEl.setText("");
const icon = this.containerEl.createDiv("dendron-icon");
setIcon(icon, dendronActivityBarName);
const content = this.containerEl.createDiv();
const { vaultName, vault, path } = target;
if (vaultName === "") {
content.setText("Vault name are unspecified in link.");
return;
} else if (!vault) {
content.setText(`Vault ${vaultName} are not found.`);
return;
} else if (path === "") {
content.setText("Note path are unspecified in link.");
return;
}
content.setText(`"${target.path}" is not created yet. Click to create.`);
this.containerEl.onclick = () => {
vault.createNote(path).then((file) => openFile(app, file));
};
}
}
export function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) {
if (!target.note || !target.note.file) {
return new UnresolvedRefRenderChild(app, container, target);
} else {
return new NoteRefRenderChild(app, container, target);
}
}
| src/custom-resolver/ref-render.ts | levirs565-obsidian-dendron-tree-b11ea1e | [
{
"filename": "src/custom-resolver/link-open.ts",
"retrieved_chunk": " new Notice(\"Note path is unspecified in link.\");\n return;\n }\n file = await target.vault.createNote(target.path);\n }\n let newLink = file.path;\n if (target.subpath)\n newLink += anchorToLinkSubpath(\n target.subpath.start,\n app.metadataCache.getFileCache(file)?.headings",
"score": 0.8008875250816345
},
{
"filename": "src/custom-resolver/link-live.ts",
"retrieved_chunk": " this.app.workspace.openLinkText(this.href, this.sourcePath);\n });\n }\n updateTitle() {\n this.containerEl.children[0].setText(\n renderLinkTitle(this.app, this.workspace, this.href, this.title, this.sourcePath)\n );\n }\n toDOM(view: EditorView): HTMLElement {\n if (!this.containerEl) this.initDOM();",
"score": 0.7844674587249756
},
{
"filename": "src/modal/lookup.ts",
"retrieved_chunk": " });\n });\n if (!item || !item.note.file)\n el.createEl(\"div\", { cls: \"suggestion-aux\" }, (el) => {\n el.append(getIcon(\"plus\")!);\n });\n }\n async onChooseSuggestion(item: LookupItem | null, evt: MouseEvent | KeyboardEvent) {\n if (item && item.note.file) {\n openFile(this.app, item.note.file);",
"score": 0.7312914133071899
},
{
"filename": "src/custom-resolver/link-open.ts",
"retrieved_chunk": "import { Notice, Workspace } from \"obsidian\";\nimport { anchorToLinkSubpath } from \"src/engine/ref\";\nimport { DendronWorkspace } from \"src/engine/workspace\";\nexport function createLinkOpenHandler(\n workspace: DendronWorkspace,\n originalBoundedFunction: Workspace[\"openLinkText\"]\n): Workspace[\"openLinkText\"] {\n return async (linktext, sourcePath, newLeaf, openViewState) => {\n const target = workspace.resolveRef(sourcePath, linktext);\n if (!target || target.type !== \"maybe-note\")",
"score": 0.7309591174125671
},
{
"filename": "src/modal/add-vault.ts",
"retrieved_chunk": " bottom: loc.top + this.inputEl.offsetHeight,\n });\n };\n getSuggestions(query: string) {\n const queryLowercase = query.toLowerCase();\n return this.app.vault\n .getAllLoadedFiles()\n .filter(\n (file) => file instanceof TFolder && file.path.toLowerCase().contains(queryLowercase)\n ) as TFolder[];",
"score": 0.727539598941803
}
] | typescript | : anchorToLinkSubpath(
this.ref.subpath.start,
this.app.metadataCache.getFileCache(this.file)?.headings
),
}; |
import { CollectionConfig, Field } from "payload/types";
import { buildCrowdinJsonObject } from "../..";
import {
field,
fieldJsonCrowdinObject,
fieldDocValue,
} from "../fixtures/blocks-field-type.fixture";
describe("fn: buildCrowdinHtmlObject: blocks field type", () => {
it("includes localized fields", () => {
const doc = {
id: "638641358b1a140462752076",
title: "Test Policy created with title",
blocksField: fieldDocValue,
status: "draft",
createdAt: "2022-11-29T17:28:21.644Z",
updatedAt: "2022-11-29T17:28:21.644Z",
};
const fields: Field[] = [
{
name: "title",
type: "text",
localized: true,
},
// select not supported yet
{
name: "select",
type: "select",
localized: true,
options: ["one", "two"],
},
field,
];
const expected = {
title: "Test Policy created with title",
...fieldJsonCrowdinObject(),
};
| expect(buildCrowdinJsonObject({ doc, fields })).toEqual(expected); |
});
it("includes localized fields within a collapsible field", () => {
const doc = {
id: "638641358b1a140462752076",
title: "Test Policy created with title",
blocksField: fieldDocValue,
status: "draft",
createdAt: "2022-11-29T17:28:21.644Z",
updatedAt: "2022-11-29T17:28:21.644Z",
};
const fields: Field[] = [
{
name: "title",
type: "text",
localized: true,
},
// select not supported yet
{
name: "select",
type: "select",
localized: true,
options: ["one", "two"],
},
{
label: "Array fields",
type: "collapsible",
fields: [field],
},
];
const expected = {
title: "Test Policy created with title",
...fieldJsonCrowdinObject(),
};
expect(buildCrowdinJsonObject({ doc, fields })).toEqual(expected);
});
it("includes localized fields within an array field", () => {
const doc = {
id: "638641358b1a140462752076",
title: "Test Policy created with title",
arrayField: [
{
blocksField: fieldDocValue,
id: "63ea4adb6ff825cddad3c1f2",
},
],
status: "draft",
createdAt: "2022-11-29T17:28:21.644Z",
updatedAt: "2022-11-29T17:28:21.644Z",
};
const fields: Field[] = [
{
name: "title",
type: "text",
localized: true,
},
// select not supported yet
{
name: "select",
type: "select",
localized: true,
options: ["one", "two"],
},
{
name: "arrayField",
type: "array",
fields: [field],
},
];
const expected = {
title: "Test Policy created with title",
...fieldJsonCrowdinObject("arrayField.63ea4adb6ff825cddad3c1f2"),
};
expect(buildCrowdinJsonObject({ doc, fields })).toEqual(expected);
});
});
| src/utilities/tests/buildJsonCrowdinObject/blocks-field-type-fixture.spec.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/group-field-type.spec.ts",
"retrieved_chunk": " const expected = {\n title: \"Test Policy created with title\",\n groupField: {\n nestedGroupField: fieldJsonCrowdinObject(),\n secondNestedGroupField: fieldJsonCrowdinObject(),\n },\n };\n expect(buildCrowdinJsonObject({ doc, fields: localizedFields })).toEqual(\n expected\n );",
"score": 0.9218869209289551
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/blocks-field-type.spec.ts",
"retrieved_chunk": " name: \"blocksField\",\n type: \"blocks\",\n blocks: [TestBlockArrayOfRichText],\n },\n ];\n const localizedFields = getLocalizedFields({ fields, type: \"json\" });\n const expected = {\n title: \"Test Policy created with title\",\n };\n expect(buildCrowdinJsonObject({ doc, fields: localizedFields })).toEqual(",
"score": 0.9178619384765625
},
{
"filename": "src/utilities/tests/buildPayloadUpdateObject/add-rich-text-fields.spec.ts",
"retrieved_chunk": " const crowdinJsonObject = {\n title: \"Test Policy created with title\",\n ...fieldJsonCrowdinObject(),\n };\n const crowdinHtmlObject = fieldHtmlCrowdinObject();\n const expected = {\n title: \"Test Policy created with title\",\n blocksField: fieldDocValue,\n };\n expect(",
"score": 0.914751410484314
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/group-field-type.spec.ts",
"retrieved_chunk": " const expected = {\n title: \"Test Policy created with title\",\n groupField: fieldJsonCrowdinObject(),\n };\n expect(buildCrowdinJsonObject({ doc, fields: localizedFields })).toEqual(\n expected\n );\n });\n it(\"includes localized fields and meta @payloadcms/plugin-seo \", () => {\n const doc = {",
"score": 0.9067589044570923
},
{
"filename": "src/utilities/tests/buildHtmlCrowdinObject/blocks-field-type.spec.ts",
"retrieved_chunk": " fields: [field],\n },\n ];\n const expected = fieldHtmlCrowdinObject();\n expect(buildCrowdinHtmlObject({ doc, fields })).toEqual(expected);\n });\n it(\"includes localized fields within an array field\", () => {\n const doc = {\n id: \"638641358b1a140462752076\",\n title: \"Test Policy created with title\",",
"score": 0.9019839763641357
}
] | typescript | expect(buildCrowdinJsonObject({ doc, fields })).toEqual(expected); |
import type { Config } from "payload/config";
import type { PluginOptions } from "./types";
import {
getAfterChangeHook,
getGlobalAfterChangeHook,
} from "./hooks/collections/afterChange";
import { getAfterDeleteHook } from "./hooks/collections/afterDelete";
import { getFields } from "./fields/getFields";
import CrowdinFiles from "./collections/CrowdinFiles";
import CrowdinCollectionDirectories from "./collections/CrowdinCollectionDirectories";
import CrowdinArticleDirectories from "./collections/CrowdinArticleDirectories";
import { containsLocalizedFields } from "./utilities";
import { getReviewTranslationEndpoint } from "./endpoints/globals/reviewTranslation";
import { getReviewFieldsEndpoint } from "./endpoints/globals/reviewFields";
import Joi from "joi";
/**
* This plugin extends all collections that contain localized fields
* by uploading all translation-enabled field content in the default
* language to Crowdin for translation. Crowdin translations are
* are synced to fields in all other locales (except the default language).
*
**/
export const crowdinSync =
(pluginOptions: PluginOptions) =>
(config: Config): Config => {
const initFunctions: (() => void)[] = [];
// schema validation
const schema = Joi.object({
projectId: Joi.number().required(),
directoryId: Joi.number(),
// optional - if not provided, the plugin will not do anything in the afterChange hook.
token: Joi.string().required(),
localeMap: Joi.object().pattern(
/./,
Joi.object({
crowdinId: Joi.string().required(),
}).pattern(/./, Joi.any())
),
sourceLocale: Joi.string().required(),
});
const validate = schema.validate(pluginOptions);
if (validate.error) {
console.log(
"Payload Crowdin Sync option validation errors:",
validate.error
);
}
return {
...config,
admin: {
...(config.admin || {}),
},
collections: [
...(config.collections || []).map((existingCollection) => {
if | (containsLocalizedFields({ fields: existingCollection.fields })) { |
const fields = getFields({
collection: existingCollection,
});
return {
...existingCollection,
hooks: {
...(existingCollection.hooks || {}),
afterChange: [
...(existingCollection.hooks?.afterChange || []),
getAfterChangeHook({
collection: existingCollection,
pluginOptions,
}),
],
afterDelete: [
...(existingCollection.hooks?.afterDelete || []),
getAfterDeleteHook({
pluginOptions,
}),
],
},
fields,
};
}
return existingCollection;
}),
CrowdinFiles,
CrowdinCollectionDirectories,
{
...CrowdinArticleDirectories,
fields: [
...(CrowdinArticleDirectories.fields || []),
{
name: "excludeLocales",
type: "select",
options: Object.keys(pluginOptions.localeMap),
hasMany: true,
admin: {
description:
"Select locales to exclude from translation synchronization.",
},
},
],
endpoints: [
...(CrowdinArticleDirectories.endpoints || []),
getReviewTranslationEndpoint({
pluginOptions,
}),
getReviewTranslationEndpoint({
pluginOptions,
type: "update",
}),
getReviewFieldsEndpoint({
pluginOptions
})
],
},
],
globals: [
...(config.globals || []).map((existingGlobal) => {
if (containsLocalizedFields({ fields: existingGlobal.fields })) {
const fields = getFields({
collection: existingGlobal,
});
return {
...existingGlobal,
hooks: {
...(existingGlobal.hooks || {}),
afterChange: [
...(existingGlobal.hooks?.afterChange || []),
getGlobalAfterChangeHook({
global: existingGlobal,
pluginOptions,
}),
],
},
fields,
};
}
return existingGlobal;
}),
],
onInit: async (payload) => {
initFunctions.forEach((fn) => fn());
if (config.onInit) await config.onInit(payload);
},
};
};
| src/plugin.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/endpoints/globals/reviewFields.ts",
"retrieved_chunk": " req.payload\n );\n try {\n const collectionConfig = await translationsApi.getCollectionConfig(global ? articleDirectory.name : articleDirectory.crowdinCollectionDirectory.collectionSlug, global)\n const response = {\n fields: collectionConfig.fields,\n localizedFields: getLocalizedFields({ fields: collectionConfig.fields })\n }\n res.status(200).send(response);\n } catch (error) {",
"score": 0.8309134840965271
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": " }\n const filteredFields = topLevel\n ? getLocalizedFields({\n fields,\n type: !crowdinHtmlObject ? \"json\" : undefined,\n })\n : fields;\n filteredFields.forEach((field) => {\n if (!crowdinJsonObject[field.name]) {\n return;",
"score": 0.8289119005203247
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": " localizedParent?: boolean;\n}): any[] => [\n ...fields\n // localized or group fields only.\n .filter(\n (field) =>\n isLocalizedField(field, localizedParent) || containsNestedFields(field)\n )\n // further filter on Crowdin field type\n .filter((field) => {",
"score": 0.8243089914321899
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": " .map((field) => {\n const localizedParent = hasLocalizedProp(field);\n if (field.type === \"group\" || field.type === \"array\") {\n return {\n ...field,\n fields: getLocalizedFields({\n fields: field.fields,\n type,\n localizedParent,\n }),",
"score": 0.8200310468673706
},
{
"filename": "src/utilities/index.ts",
"retrieved_chunk": " };\n }\n if (field.type === \"blocks\") {\n const blocks = field.blocks\n .map((block: Block) => {\n if (\n containsLocalizedFields({\n fields: block.fields,\n type,\n localizedParent,",
"score": 0.819251537322998
}
] | typescript | (containsLocalizedFields({ fields: existingCollection.fields })) { |
import type { Config } from "payload/config";
import type { PluginOptions } from "./types";
import {
getAfterChangeHook,
getGlobalAfterChangeHook,
} from "./hooks/collections/afterChange";
import { getAfterDeleteHook } from "./hooks/collections/afterDelete";
import { getFields } from "./fields/getFields";
import CrowdinFiles from "./collections/CrowdinFiles";
import CrowdinCollectionDirectories from "./collections/CrowdinCollectionDirectories";
import CrowdinArticleDirectories from "./collections/CrowdinArticleDirectories";
import { containsLocalizedFields } from "./utilities";
import { getReviewTranslationEndpoint } from "./endpoints/globals/reviewTranslation";
import { getReviewFieldsEndpoint } from "./endpoints/globals/reviewFields";
import Joi from "joi";
/**
* This plugin extends all collections that contain localized fields
* by uploading all translation-enabled field content in the default
* language to Crowdin for translation. Crowdin translations are
* are synced to fields in all other locales (except the default language).
*
**/
export const crowdinSync =
(pluginOptions: PluginOptions) =>
(config: Config): Config => {
const initFunctions: (() => void)[] = [];
// schema validation
const schema = Joi.object({
projectId: Joi.number().required(),
directoryId: Joi.number(),
// optional - if not provided, the plugin will not do anything in the afterChange hook.
token: Joi.string().required(),
localeMap: Joi.object().pattern(
/./,
Joi.object({
crowdinId: Joi.string().required(),
}).pattern(/./, Joi.any())
),
sourceLocale: Joi.string().required(),
});
const validate = schema.validate(pluginOptions);
if (validate.error) {
console.log(
"Payload Crowdin Sync option validation errors:",
validate.error
);
}
return {
...config,
admin: {
...(config.admin || {}),
},
collections: [
...(config.collections || []).map((existingCollection) => {
if (containsLocalizedFields({ fields: existingCollection.fields })) {
const fields = getFields({
collection: existingCollection,
});
return {
...existingCollection,
hooks: {
...(existingCollection.hooks || {}),
afterChange: [
...(existingCollection.hooks?.afterChange || []),
getAfterChangeHook({
collection: existingCollection,
pluginOptions,
}),
],
afterDelete: [
...(existingCollection.hooks?.afterDelete || []),
getAfterDeleteHook({
pluginOptions,
}),
],
},
fields,
};
}
return existingCollection;
}),
CrowdinFiles,
CrowdinCollectionDirectories,
{
...CrowdinArticleDirectories,
fields: [
| ...(CrowdinArticleDirectories.fields || []),
{ |
name: "excludeLocales",
type: "select",
options: Object.keys(pluginOptions.localeMap),
hasMany: true,
admin: {
description:
"Select locales to exclude from translation synchronization.",
},
},
],
endpoints: [
...(CrowdinArticleDirectories.endpoints || []),
getReviewTranslationEndpoint({
pluginOptions,
}),
getReviewTranslationEndpoint({
pluginOptions,
type: "update",
}),
getReviewFieldsEndpoint({
pluginOptions
})
],
},
],
globals: [
...(config.globals || []).map((existingGlobal) => {
if (containsLocalizedFields({ fields: existingGlobal.fields })) {
const fields = getFields({
collection: existingGlobal,
});
return {
...existingGlobal,
hooks: {
...(existingGlobal.hooks || {}),
afterChange: [
...(existingGlobal.hooks?.afterChange || []),
getGlobalAfterChangeHook({
global: existingGlobal,
pluginOptions,
}),
],
},
fields,
};
}
return existingGlobal;
}),
],
onInit: async (payload) => {
initFunctions.forEach((fn) => fn());
if (config.onInit) await config.onInit(payload);
},
};
};
| src/plugin.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/api/payload-crowdin-sync/files.ts",
"retrieved_chunk": " id: document.id,\n data: {\n crowdinArticleDirectory: crowdinPayloadArticleDirectory.id,\n },\n });\n }\n }\n return crowdinPayloadArticleDirectory;\n }\n private async findOrCreateCollectionDirectory({",
"score": 0.8412963151931763
},
{
"filename": "src/fields/getFields.ts",
"retrieved_chunk": "import type { CollectionConfig, Field, GlobalConfig } from \"payload/types\";\ninterface Args {\n collection: CollectionConfig | GlobalConfig;\n}\nexport const getFields = ({ collection }: Args): Field[] => {\n const fields = [...collection.fields];\n const crowdinArticleDirectoryField: Field = {\n name: \"crowdinArticleDirectory\",\n type: \"relationship\",\n relationTo: \"crowdin-article-directories\",",
"score": 0.8115103840827942
},
{
"filename": "src/collections/CrowdinArticleDirectories.ts",
"retrieved_chunk": "import { CollectionConfig } from \"payload/types\";\nconst CrowdinArticleDirectories: CollectionConfig = {\n slug: \"crowdin-article-directories\",\n admin: {\n defaultColumns: [\n \"name\",\n \"title\",\n \"crowdinCollectionDirectory\",\n \"createdAt\",\n ],",
"score": 0.8044527173042297
},
{
"filename": "src/api/helpers.ts",
"retrieved_chunk": " collection: \"crowdin-files\",\n where: {\n field: { equals: name },\n crowdinArticleDirectory: {\n equals: crowdinArticleDirectoryId,\n },\n },\n });\n return result.docs[0];\n}",
"score": 0.8042986989021301
},
{
"filename": "src/api/payload-crowdin-sync/translations.ts",
"retrieved_chunk": " locale: locale,\n });\n }\n docTranslations = buildPayloadUpdateObject({\n crowdinJsonObject,\n crowdinHtmlObject,\n fields: localizedFields,\n document: doc,\n });\n // Add required fields if not present",
"score": 0.7942076325416565
}
] | typescript | ...(CrowdinArticleDirectories.fields || []),
{ |
import type { Config } from "payload/config";
import type { PluginOptions } from "./types";
import {
getAfterChangeHook,
getGlobalAfterChangeHook,
} from "./hooks/collections/afterChange";
import { getAfterDeleteHook } from "./hooks/collections/afterDelete";
import { getFields } from "./fields/getFields";
import CrowdinFiles from "./collections/CrowdinFiles";
import CrowdinCollectionDirectories from "./collections/CrowdinCollectionDirectories";
import CrowdinArticleDirectories from "./collections/CrowdinArticleDirectories";
import { containsLocalizedFields } from "./utilities";
import { getReviewTranslationEndpoint } from "./endpoints/globals/reviewTranslation";
import { getReviewFieldsEndpoint } from "./endpoints/globals/reviewFields";
import Joi from "joi";
/**
* This plugin extends all collections that contain localized fields
* by uploading all translation-enabled field content in the default
* language to Crowdin for translation. Crowdin translations are
* are synced to fields in all other locales (except the default language).
*
**/
export const crowdinSync =
(pluginOptions: PluginOptions) =>
(config: Config): Config => {
const initFunctions: (() => void)[] = [];
// schema validation
const schema = Joi.object({
projectId: Joi.number().required(),
directoryId: Joi.number(),
// optional - if not provided, the plugin will not do anything in the afterChange hook.
token: Joi.string().required(),
localeMap: Joi.object().pattern(
/./,
Joi.object({
crowdinId: Joi.string().required(),
}).pattern(/./, Joi.any())
),
sourceLocale: Joi.string().required(),
});
const validate = schema.validate(pluginOptions);
if (validate.error) {
console.log(
"Payload Crowdin Sync option validation errors:",
validate.error
);
}
return {
...config,
admin: {
...(config.admin || {}),
},
collections: [
...(config.collections || []).map((existingCollection) => {
if (containsLocalizedFields({ fields: existingCollection.fields })) {
const fields = getFields({
collection: existingCollection,
});
return {
...existingCollection,
hooks: {
...(existingCollection.hooks || {}),
afterChange: [
...(existingCollection.hooks?.afterChange || []),
getAfterChangeHook({
collection: existingCollection,
pluginOptions,
}),
],
afterDelete: [
...(existingCollection.hooks?.afterDelete || []),
getAfterDeleteHook({
pluginOptions,
}),
],
},
fields,
};
}
return existingCollection;
}),
CrowdinFiles,
CrowdinCollectionDirectories,
{
...CrowdinArticleDirectories,
fields: [
...(CrowdinArticleDirectories.fields || []),
{
name: "excludeLocales",
type: "select",
options: Object.keys(pluginOptions.localeMap),
hasMany: true,
admin: {
description:
"Select locales to exclude from translation synchronization.",
},
},
],
endpoints: [
| ...(CrowdinArticleDirectories.endpoints || []),
getReviewTranslationEndpoint({ |
pluginOptions,
}),
getReviewTranslationEndpoint({
pluginOptions,
type: "update",
}),
getReviewFieldsEndpoint({
pluginOptions
})
],
},
],
globals: [
...(config.globals || []).map((existingGlobal) => {
if (containsLocalizedFields({ fields: existingGlobal.fields })) {
const fields = getFields({
collection: existingGlobal,
});
return {
...existingGlobal,
hooks: {
...(existingGlobal.hooks || {}),
afterChange: [
...(existingGlobal.hooks?.afterChange || []),
getGlobalAfterChangeHook({
global: existingGlobal,
pluginOptions,
}),
],
},
fields,
};
}
return existingGlobal;
}),
],
onInit: async (payload) => {
initFunctions.forEach((fn) => fn());
if (config.onInit) await config.onInit(payload);
},
};
};
| src/plugin.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/utilities/tests/inline-snapshots/collections/shared/heroField.ts",
"retrieved_chunk": " },\n {\n name: \"link\",\n type: \"text\",\n admin: {\n description: \"Not sent to CrowdIn. Localize in the CMS.\",\n },\n },\n ],\n },",
"score": 0.8637633323669434
},
{
"filename": "src/utilities/getLocalizedFields.spec.ts",
"retrieved_chunk": " hidden: true,\n disableBulkEdit: true,\n },\n hooks: {},\n access: {},\n },\n ];\n const fields: Field[] = localizedFieldCollection;\n expect(getLocalizedFields({ fields })).toMatchInlineSnapshot(`\n [",
"score": 0.8574544191360474
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/group-field-type.spec.ts",
"retrieved_chunk": " name: \"description\",\n type: \"textarea\",\n localized: true,\n admin: {\n components: {},\n },\n },\n ],\n },\n ];",
"score": 0.8565176129341125
},
{
"filename": "src/utilities/getFieldSlugs.spec.ts",
"retrieved_chunk": " },\n access: {\n read: () => true,\n },\n versions: {\n drafts: true,\n },\n fields: [\n {\n name: \"title\",",
"score": 0.8524798154830933
},
{
"filename": "src/utilities/getLocalizedFields.spec.ts",
"retrieved_chunk": " access: {},\n admin: {},\n },\n ],\n },\n ],\n },\n {\n label: \"SEO\",\n fields: [",
"score": 0.8519219160079956
}
] | typescript | ...(CrowdinArticleDirectories.endpoints || []),
getReviewTranslationEndpoint({ |
import { CollectionConfig, Field } from "payload/types";
import { buildCrowdinJsonObject, getLocalizedFields } from "../..";
import { FieldWithName } from "../../../types";
describe("fn: buildCrowdinJsonObject: group nested in array", () => {
const doc = {
id: "6474a81bef389b66642035ff",
title: "Experience the magic of our product!",
text: "Get in touch with us or try it out yourself",
ctas: [
{
link: {
text: "Talk to us",
href: "#",
type: "ctaPrimary",
},
id: "6474a80221baea4f5f169757",
},
{
link: {
text: "Try for free",
href: "#",
type: "ctaSecondary",
},
id: "6474a81021baea4f5f169758",
},
],
createdAt: "2023-05-29T13:26:51.734Z",
updatedAt: "2023-05-29T14:47:45.957Z",
crowdinArticleDirectory: {
id: "6474baaf73b854f4d464e38f",
updatedAt: "2023-05-29T14:46:07.000Z",
createdAt: "2023-05-29T14:46:07.000Z",
name: "6474a81bef389b66642035ff",
crowdinCollectionDirectory: {
id: "6474baaf73b854f4d464e38d",
updatedAt: "2023-05-29T14:46:07.000Z",
createdAt: "2023-05-29T14:46:07.000Z",
name: "promos",
title: "Promos",
collectionSlug: "promos",
originalId: 1633,
projectId: 323731,
directoryId: 1169,
},
originalId: 1635,
projectId: 323731,
directoryId: 1633,
},
};
const linkField: Field = {
name: "link",
type: "group",
fields: [
{
name: "text",
type: "text",
localized: true,
},
{
name: "href",
type: "text",
},
{
name: "type",
type: "select",
options: ["ctaPrimary", "ctaSecondary"],
},
],
};
const Promos: CollectionConfig = {
slug: "promos",
admin: {
defaultColumns: ["title", "updatedAt"],
useAsTitle: "title",
group: "Shared",
},
access: {
read: () => true,
},
fields: [
{
name: "title",
type: "text",
localized: true,
},
{
name: "text",
type: "text",
localized: true,
},
{
name: "ctas",
type: "array",
minRows: 1,
maxRows: 2,
fields: [linkField],
},
],
};
const expected: any = {
ctas: {
"6474a80221baea4f5f169757": {
link: {
text: "Talk to us",
},
},
"6474a81021baea4f5f169758": {
link: {
text: "Try for free",
},
},
},
text: "Get in touch with us or try it out yourself",
title: "Experience the magic of our product!",
};
it("includes group json fields nested inside of array field items", () => {
expect(
buildCrowdinJsonObject({
doc,
fields: | getLocalizedFields({ fields: Promos.fields, type: "json" }),
})
).toEqual(expected); |
});
it("includes group json fields nested inside of array field items even when getLocalizedFields is run twice", () => {
expect(
buildCrowdinJsonObject({
doc,
fields: getLocalizedFields({
fields: getLocalizedFields({ fields: Promos.fields }),
type: "json",
}),
})
).toEqual(expected);
});
/**
* afterChange builds a JSON object for the previous version of
* a document to compare with the current version. Ensure this
* function works in that scenario. Also important for dealing
* with non-required empty fields.
*/
it("can work with an empty document", () => {
expect(
buildCrowdinJsonObject({
doc: {},
fields: getLocalizedFields({ fields: Promos.fields }),
})
).toEqual({});
});
it("can work with an empty array field", () => {
expect(
buildCrowdinJsonObject({
doc: {
...doc,
ctas: undefined,
},
fields: getLocalizedFields({ fields: Promos.fields }),
})
).toEqual({
text: "Get in touch with us or try it out yourself",
title: "Experience the magic of our product!",
});
});
it("can work with an empty group field in an array", () => {
expect(
buildCrowdinJsonObject({
doc: {
...doc,
ctas: [{}, {}],
},
fields: getLocalizedFields({ fields: Promos.fields }),
})
).toEqual({
text: "Get in touch with us or try it out yourself",
title: "Experience the magic of our product!",
});
});
});
| src/utilities/tests/buildJsonCrowdinObject/combined-field-types.spec.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/utilities/tests/buildHtmlCrowdinObject/array-field-type.spec.ts",
"retrieved_chunk": " ],\n },\n ],\n };\n it(\"includes group json fields nested inside of array field items\", () => {\n expect(buildCrowdinHtmlObject({ doc, fields: Promos.fields })).toEqual(\n expected\n );\n });\n it(\"can work with an empty group field in an array\", () => {",
"score": 0.9334434270858765
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/array-field-type.spec.ts",
"retrieved_chunk": " const localizedFields = getLocalizedFields({ fields });\n const expected = {\n title: \"Test Policy created with title\",\n };\n expect(buildCrowdinJsonObject({ doc, fields: localizedFields })).toEqual(\n expected\n );\n });\n it(\"includes localized fields nested in an array\", () => {\n const doc = {",
"score": 0.9309934973716736
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/array-field-type.spec.ts",
"retrieved_chunk": " text: \"Array field text content two\",\n },\n },\n };\n expect(buildCrowdinJsonObject({ doc, fields: localizedFields })).toEqual(\n expected\n );\n });\n it(\"does not include localized fields richText fields nested in an array field in the `fields.json` file\", () => {\n const doc = {",
"score": 0.9304563999176025
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/blocks-field-type-fixture.spec.ts",
"retrieved_chunk": " field,\n ];\n const expected = {\n title: \"Test Policy created with title\",\n ...fieldJsonCrowdinObject(),\n };\n expect(buildCrowdinJsonObject({ doc, fields })).toEqual(expected);\n });\n it(\"includes localized fields within a collapsible field\", () => {\n const doc = {",
"score": 0.9246219396591187
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/group-field-type.spec.ts",
"retrieved_chunk": " const expected = {\n title: \"Test Policy created with title\",\n groupField: fieldJsonCrowdinObject(),\n };\n expect(buildCrowdinJsonObject({ doc, fields: localizedFields })).toEqual(\n expected\n );\n });\n it(\"includes localized fields and meta @payloadcms/plugin-seo \", () => {\n const doc = {",
"score": 0.9236174821853638
}
] | typescript | getLocalizedFields({ fields: Promos.fields, type: "json" }),
})
).toEqual(expected); |
import type { Config } from "payload/config";
import type { PluginOptions } from "./types";
import {
getAfterChangeHook,
getGlobalAfterChangeHook,
} from "./hooks/collections/afterChange";
import { getAfterDeleteHook } from "./hooks/collections/afterDelete";
import { getFields } from "./fields/getFields";
import CrowdinFiles from "./collections/CrowdinFiles";
import CrowdinCollectionDirectories from "./collections/CrowdinCollectionDirectories";
import CrowdinArticleDirectories from "./collections/CrowdinArticleDirectories";
import { containsLocalizedFields } from "./utilities";
import { getReviewTranslationEndpoint } from "./endpoints/globals/reviewTranslation";
import { getReviewFieldsEndpoint } from "./endpoints/globals/reviewFields";
import Joi from "joi";
/**
* This plugin extends all collections that contain localized fields
* by uploading all translation-enabled field content in the default
* language to Crowdin for translation. Crowdin translations are
* are synced to fields in all other locales (except the default language).
*
**/
export const crowdinSync =
(pluginOptions: PluginOptions) =>
(config: Config): Config => {
const initFunctions: (() => void)[] = [];
// schema validation
const schema = Joi.object({
projectId: Joi.number().required(),
directoryId: Joi.number(),
// optional - if not provided, the plugin will not do anything in the afterChange hook.
token: Joi.string().required(),
localeMap: Joi.object().pattern(
/./,
Joi.object({
crowdinId: Joi.string().required(),
}).pattern(/./, Joi.any())
),
sourceLocale: Joi.string().required(),
});
const validate = schema.validate(pluginOptions);
if (validate.error) {
console.log(
"Payload Crowdin Sync option validation errors:",
validate.error
);
}
return {
...config,
admin: {
...(config.admin || {}),
},
collections: [
...(config.collections || []).map((existingCollection) => {
if (containsLocalizedFields({ fields: existingCollection.fields })) {
const fields = getFields({
collection: existingCollection,
});
return {
...existingCollection,
hooks: {
...(existingCollection.hooks || {}),
afterChange: [
...(existingCollection.hooks?.afterChange || []),
getAfterChangeHook({
collection: existingCollection,
pluginOptions,
}),
],
afterDelete: [
...(existingCollection.hooks?.afterDelete || []),
getAfterDeleteHook({
pluginOptions,
}),
],
},
fields,
};
}
return existingCollection;
}),
CrowdinFiles,
CrowdinCollectionDirectories,
{
...CrowdinArticleDirectories,
fields: [
...(CrowdinArticleDirectories.fields || []),
{
name: "excludeLocales",
type: "select",
| options: Object.keys(pluginOptions.localeMap),
hasMany: true,
admin: { |
description:
"Select locales to exclude from translation synchronization.",
},
},
],
endpoints: [
...(CrowdinArticleDirectories.endpoints || []),
getReviewTranslationEndpoint({
pluginOptions,
}),
getReviewTranslationEndpoint({
pluginOptions,
type: "update",
}),
getReviewFieldsEndpoint({
pluginOptions
})
],
},
],
globals: [
...(config.globals || []).map((existingGlobal) => {
if (containsLocalizedFields({ fields: existingGlobal.fields })) {
const fields = getFields({
collection: existingGlobal,
});
return {
...existingGlobal,
hooks: {
...(existingGlobal.hooks || {}),
afterChange: [
...(existingGlobal.hooks?.afterChange || []),
getGlobalAfterChangeHook({
global: existingGlobal,
pluginOptions,
}),
],
},
fields,
};
}
return existingGlobal;
}),
],
onInit: async (payload) => {
initFunctions.forEach((fn) => fn());
if (config.onInit) await config.onInit(payload);
},
};
};
| src/plugin.ts | thompsonsj-payload-crowdin-sync-506cfd2 | [
{
"filename": "src/collections/CrowdinFiles.ts",
"retrieved_chunk": "*/\nconst CrowdinFiles: CollectionConfig = {\n slug: \"crowdin-files\",\n admin: {\n defaultColumns: [\"path\", \"title\", \"field\", \"revisionId\", \"updatedAt\"],\n useAsTitle: \"path\",\n group: \"Crowdin Admin\",\n },\n access: {\n read: () => true,",
"score": 0.8494643568992615
},
{
"filename": "src/utilities/getLocalizedFields.spec.ts",
"retrieved_chunk": " },\n ],\n };\n const global: GlobalConfig = {\n slug: \"global\",\n fields: [\n {\n name: \"simpleLocalizedField\",\n type: \"text\",\n localized: true,",
"score": 0.8431628942489624
},
{
"filename": "src/utilities/getLocalizedFields.spec.ts",
"retrieved_chunk": " name: \"type\",\n type: \"select\",\n options: [\"ctaPrimary\", \"ctaSecondary\"],\n },\n ],\n };\n const Promos: CollectionConfig = {\n slug: \"promos\",\n admin: {\n defaultColumns: [\"title\", \"updatedAt\"],",
"score": 0.8391087055206299
},
{
"filename": "src/utilities/getLocalizedFields.spec.ts",
"retrieved_chunk": " ...localizedFieldCollection,\n {\n name: \"arrayField\",\n type: \"array\",\n localized: true,\n fields: [\n {\n name: \"title\",\n type: \"text\",\n },",
"score": 0.8390915393829346
},
{
"filename": "src/utilities/tests/buildJsonCrowdinObject/array-field-type.spec.ts",
"retrieved_chunk": " localized: true,\n options: [\"one\", \"two\"],\n },\n {\n name: \"arrayField\",\n type: \"array\",\n fields: [\n {\n name: \"title\",\n type: \"text\",",
"score": 0.8366056084632874
}
] | typescript | options: Object.keys(pluginOptions.localeMap),
hasMany: true,
admin: { |
import { App, MarkdownPostProcessor } from "obsidian";
import { DendronWorkspace } from "../engine/workspace";
import { renderLinkTitle } from "./link-render";
export function createLinkMarkdownProcessor(
app: App,
workspace: DendronWorkspace
): MarkdownPostProcessor {
return (el, ctx) => {
console.log();
const linksEl = el.querySelectorAll(".internal-link");
if (linksEl.length == 0) return;
const section = ctx.getSectionInfo(el);
const cache = app.metadataCache.getCache(ctx.sourcePath);
if (!section || !cache?.links) return;
const links = cache.links.filter(
(link) =>
link.position.start.line >= section.lineStart && link.position.end.line <= section.lineEnd
);
if (links.length !== linksEl.length) {
console.warn("Cannot post process link");
return;
}
linksEl.forEach((el, index) => {
const link = links[index];
// used to check is wikilink or not
// aria-label and data-tooltip-position only appear when link is wikilink with alias
if (!link.original.startsWith("[[") || !link.original.endsWith("]]")) return;
let title: string | undefined, href: string;
const split = link.original.substring(2, link.original.length - 2).split("|", 2);
if (split.length == 1) href = split[0];
else {
title = split[0];
href = split[1];
}
| const titleText = renderLinkTitle(app, workspace, href, title, ctx.sourcePath); |
el.setText(titleText);
el.setAttribute("href", href);
el.setAttribute("data-href", href);
el.setAttribute("aria-label", href);
el.setAttribute("data-tooltip-position", "top");
});
};
}
| src/custom-resolver/link-markdown-processor.ts | levirs565-obsidian-dendron-tree-b11ea1e | [
{
"filename": "src/path.ts",
"retrieved_chunk": "export function parsePath(path: string): ParsedPath {\n const pathComponent = path.split(lastSeparatorRegex);\n let dir = \"\";\n let name;\n if (pathComponent.length == 2) [dir, name] = pathComponent;\n else [name] = pathComponent;\n const nameComponent = name.split(lastPeriodRegex);\n const basename = nameComponent[0];\n let extension = \"\";\n if (nameComponent.length > 1) extension = nameComponent[1];",
"score": 0.8109129667282104
},
{
"filename": "src/custom-resolver/link-live.ts",
"retrieved_chunk": " if (found) break;\n }\n }\n getWidget(link: LinkData, sourcePath: string) {\n const lastWidgetIndex = this.widgets.findIndex(\n (widget) => widget.href === link.href && widget.sourcePath === sourcePath\n );\n if (lastWidgetIndex >= 0) {\n const widget = this.widgets[lastWidgetIndex];\n widget.title = link.title;",
"score": 0.8015980124473572
},
{
"filename": "src/main.ts",
"retrieved_chunk": " async migrateSettings() {\n function pathToVaultConfig(path: string) {\n const { name } = parsePath(path);\n if (name.length === 0)\n return {\n name: \"root\",\n path: \"/\",\n };\n let processed = path;\n if (processed.endsWith(\"/\")) processed = processed.slice(0, -1);",
"score": 0.8015637397766113
},
{
"filename": "src/engine/workspace.ts",
"retrieved_chunk": " const [vaultName, rest] = link.slice(DENDRON_URI_START.length).split(\"/\", 2) as (\n | string\n | undefined\n )[];\n const { path, subpath } = rest\n ? parseLinktext(rest)\n : {\n path: undefined,\n subpath: undefined,\n };",
"score": 0.8009998798370361
},
{
"filename": "src/engine/ref.ts",
"retrieved_chunk": "): string | null {\n if (anchor.type === \"header\") {\n let name = anchor.name;\n if (headings) {\n const { heading } = findHeadingByGithubSlug(headings, name);\n if (heading) {\n name = heading.heading;\n }\n }\n return `#${name}`;",
"score": 0.7964658737182617
}
] | typescript | const titleText = renderLinkTitle(app, workspace, href, title, ctx.sourcePath); |
import type { Stat, TFile, Vault } from "obsidian";
import { Note, NoteTree, generateNoteTitle, isUseTitleCase } from "./note";
import { parsePath } from "../path";
describe("note title", () => {
it("use title case when file name is lowercase", () => {
expect(generateNoteTitle("kamu-milikku", isUseTitleCase("aku.cinta.kamu-milikku.md"))).toBe(
"Kamu Milikku"
);
});
it("use file name when note name contain uppercase", () => {
expect(generateNoteTitle("Kamu-Milikku", isUseTitleCase("aku.cinta.Kamu-Milikku.md"))).toBe(
"Kamu-Milikku"
);
});
it("use file name when file name contain uppercase", () => {
expect(generateNoteTitle("kamu-milikku", isUseTitleCase("Aku.cinta.kamu-milikku.md"))).toBe(
"kamu-milikku"
);
});
});
describe("note class", () => {
it("append and remove child work", () => {
const child = new Note("lala", true);
expect(child.parent).toBeUndefined();
const parent = new Note("apa", true);
expect(parent.children).toEqual([]);
parent.appendChild(child);
expect(child.parent).toBe(parent);
expect(parent.children).toEqual([child]);
parent.removeChildren(child);
expect(child.parent).toBeUndefined();
expect(parent.children).toEqual([]);
});
it("append child must throw if child already has parent", () => {
const origParent = new Note("root", true);
const parent = new Note("root2", true);
const child = new Note("child", true);
origParent.appendChild(child);
expect(() => parent.appendChild(child)).toThrowError("has parent");
});
it("find children work", () => {
const parent = new Note("parent", true);
const child1 = new Note("child1", true);
const child2 = new Note("child2", true);
const child3 = new Note("child3", true);
parent.appendChild(child1);
parent.appendChild(child2);
parent.appendChild(child3);
expect(parent.findChildren("child1")).toBe(child1);
expect(parent.findChildren("child2")).toBe(child2);
expect(parent.findChildren("child3")).toBe(child3);
expect(parent.findChildren("child4")).toBeUndefined();
});
it("non-recursive sort children work", () => {
const parent = new Note("parent", true);
const child1 = new Note("gajak", true);
const child2 = new Note("lumba", true);
const child3 = new Note("biawak", true);
parent.appendChild(child1);
parent.appendChild(child2);
parent.appendChild(child3);
expect(parent.children).toEqual([child1, child2, child3]);
parent.sortChildren(false);
expect(parent.children).toEqual([child3, child1, child2]);
});
it("recursive sort children work", () => {
const parent = new Note("parent", true);
const child1 = new Note("lumba", true);
const child2 = new Note("galak", true);
const grandchild1 = new Note("lupa", true);
const grandchild2 = new Note("apa", true);
const grandchild3 = new Note("abu", true);
const grandchild4 = new Note("lagi", true);
parent.appendChild(child1);
child1.appendChild(grandchild1);
child1.appendChild(grandchild2);
parent.appendChild(child2);
child2.appendChild(grandchild3);
child2.appendChild(grandchild4);
expect(parent.children).toEqual([child1, child2]);
expect(child1.children).toEqual([grandchild1, grandchild2]);
expect(child2.children).toEqual([grandchild3, grandchild4]);
parent.sortChildren(true);
expect(parent.children).toEqual([child2, child1]);
expect(child1.children).toEqual([grandchild2, grandchild1]);
expect(child2.children).toEqual([grandchild3, grandchild4]);
});
it("get path on non-root", () => {
const root = new Note("root", true);
const ch1 = new Note("parent", true);
const ch2 = new Note("parent2", true);
const ch3 = new Note("child", true);
root.appendChild(ch1);
ch1.appendChild(ch2);
ch2.appendChild(ch3);
expect(ch3.getPath()).toBe("parent.parent2.child");
expect(ch3.getPathNotes()).toEqual([root, ch1, ch2, ch3]);
});
it("get path on root", () => {
const root = new Note("root", true);
expect(root.getPath()).toBe("root");
expect(root.getPathNotes()).toEqual([root]);
});
it("use generated title when titlecase true", () => {
const note = new Note("aku-cinta", true);
expect(note.title).toBe("Aku Cinta");
});
it("use filename as title when titlecase false", () => {
const note = new Note("aKu-ciNta", false);
expect(note.title).toBe("aKu-ciNta");
});
it("use metadata title when has metadata", () => {
const note = new Note("aKu-ciNta", false);
note.syncMetadata({
title: "Butuh Kamu",
});
expect(note.title).toBe("Butuh Kamu");
});
});
function createTFile(path: string): TFile {
const { | basename, name, extension } = parsePath(path); |
return {
basename,
extension,
name,
parent: null,
path: path,
stat: null as unknown as Stat,
vault: null as unknown as Vault,
};
}
describe("tree class", () => {
it("add file without sort", () => {
const tree = new NoteTree();
tree.addFile(createTFile("abc.def.jkl.md"));
tree.addFile(createTFile("abc.def.ghi.md"));
expect(tree.root.children.length).toBe(1);
expect(tree.root.children[0].name).toBe("abc");
expect(tree.root.children[0].children.length).toBe(1);
expect(tree.root.children[0].children[0].name).toBe("def");
expect(tree.root.children[0].children[0].children.length).toBe(2);
expect(tree.root.children[0].children[0].children[0].name).toBe("jkl");
expect(tree.root.children[0].children[0].children[1].name).toBe("ghi");
});
it("add file with sort", () => {
const tree = new NoteTree();
tree.addFile(createTFile("abc.def.jkl.md"), true);
tree.addFile(createTFile("abc.def.ghi.md"), true);
tree.addFile(createTFile("abc.def.mno.md"), true);
expect(tree.root.children[0].children[0].children.length).toBe(3);
expect(tree.root.children[0].children[0].children[0].name).toBe("ghi");
expect(tree.root.children[0].children[0].children[1].name).toBe("jkl");
expect(tree.root.children[0].children[0].children[2].name).toBe("mno");
});
it("get note by file base name", () => {
const tree = new NoteTree();
tree.addFile(createTFile("abc.def.jkl.md"));
tree.addFile(createTFile("abc.def.ghi.md"));
expect(tree.getFromFileName("abc.def.jkl")?.name).toBe("jkl");
expect(tree.getFromFileName("abc.def.ghi")?.name).toBe("ghi");
expect(tree.getFromFileName("abc.def.mno")).toBeUndefined();
});
it("get note using blank path", () => {
const tree = new NoteTree();
tree.addFile(createTFile("abc.def.jkl.md"));
tree.addFile(createTFile("abc.def.ghi.md"));
expect(tree.getFromFileName("")).toBeUndefined()
})
it("delete note if do not have children", () => {
const tree = new NoteTree();
tree.addFile(createTFile("abc.md"));
tree.deleteByFileName("abc");
expect(tree.getFromFileName("abc")).toBeUndefined();
});
it("do not delete note if have children", () => {
const tree = new NoteTree();
tree.addFile(createTFile("abc.md"));
tree.addFile(createTFile("abc.def.md"));
tree.deleteByFileName("abc");
expect(tree.getFromFileName("abc")?.name).toBe("abc");
expect(tree.getFromFileName("abc.def")?.name).toBe("def");
});
it("delete note and parent if do not have children and parent file is null", () => {
const tree = new NoteTree();
tree.addFile(createTFile("abc"));
tree.addFile(createTFile("abc.def.ghi.md"));
tree.deleteByFileName("abc.def.ghi");
expect(tree.getFromFileName("abc.def.ghi")).toBeUndefined();
expect(tree.getFromFileName("abc.def")).toBeUndefined();
expect(tree.getFromFileName("abc")?.name).toBe("abc");
});
it("sort note", () => {
const tree = new NoteTree();
tree.addFile(createTFile("abc.def.jkl.md"));
tree.addFile(createTFile("abc.def.ghi.md"));
tree.addFile(createTFile("abc.def.mno.md"));
expect(tree.root.children[0].children[0].children.length).toBe(3);
expect(tree.root.children[0].children[0].children[0].name).toBe("jkl");
expect(tree.root.children[0].children[0].children[1].name).toBe("ghi");
expect(tree.root.children[0].children[0].children[2].name).toBe("mno");
tree.sort();
expect(tree.root.children[0].children[0].children[0].name).toBe("ghi");
expect(tree.root.children[0].children[0].children[1].name).toBe("jkl");
expect(tree.root.children[0].children[0].children[2].name).toBe("mno");
});
it("flatten note", () => {
const tree = new NoteTree();
tree.addFile(createTFile("abc.def.md"));
tree.addFile(createTFile("abc.def.ghi.md"));
tree.addFile(createTFile("abc.jkl.mno.md"));
expect(tree.flatten().map((note) => note.getPath())).toEqual([
"root",
"abc",
"abc.def",
"abc.def.ghi",
"abc.jkl",
"abc.jkl.mno",
]);
});
});
| src/engine/note.test.ts | levirs565-obsidian-dendron-tree-b11ea1e | [
{
"filename": "src/path.test.ts",
"retrieved_chunk": "import { parsePath } from \"./path\";\ndescribe(\"parse path\", () => {\n it(\"parse path with 2 component\", () => {\n expect(parsePath(\"abc/ll.md\")).toStrictEqual({\n dir: \"abc\",\n name: \"ll.md\",\n basename: \"ll\",\n extension: \"md\",\n });\n });",
"score": 0.7968486547470093
},
{
"filename": "src/path.test.ts",
"retrieved_chunk": " basename: \"pacar\",\n extension: \"md\",\n });\n });\n it(\"parse windows path\", () => {\n expect(parsePath(\"abc\\\\ll.md\")).toStrictEqual({\n dir: \"abc\",\n name: \"ll.md\",\n basename: \"ll\",\n extension: \"md\",",
"score": 0.7844513654708862
},
{
"filename": "src/path.test.ts",
"retrieved_chunk": " it(\"parse path with 1 component\", () => {\n expect(parsePath(\"hugo.md\")).toStrictEqual({\n dir: \"\",\n name: \"hugo.md\",\n basename: \"hugo\",\n extension: \"md\",\n });\n });\n it(\"parse path with name contain multiple dot\", () => {\n expect(parsePath(\"baca.buku.md\")).toStrictEqual({",
"score": 0.7736091613769531
},
{
"filename": "src/engine/note.ts",
"retrieved_chunk": "import { TFile } from \"obsidian\";\nexport interface NoteMetadata {\n title?: string;\n}\nexport class Note {\n name: string;\n children: Note[] = [];\n file?: TFile;\n parent?: Note;\n title = \"\";",
"score": 0.7726438045501709
},
{
"filename": "src/engine/vault.ts",
"retrieved_chunk": " folder: TFolder;\n tree: NoteTree;\n isIniatialized = false;\n constructor(public app: App, public config: VaultConfig) {}\n private resolveMetadata(file: TFile): NoteMetadata | undefined {\n const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter;\n if (!frontmatter) return undefined;\n return {\n title: frontmatter[\"title\"],\n };",
"score": 0.7635797262191772
}
] | typescript | basename, name, extension } = parsePath(path); |
import { EditorView, PluginValue, ViewUpdate } from "@codemirror/view";
import { App, Component, editorLivePreviewField } from "obsidian";
import { NoteRefRenderChild, createRefRenderer } from "./ref-render";
import { DendronWorkspace } from "../engine/workspace";
interface InternalEmbedWidget {
end: number;
href: string;
sourcePath: string;
start: string;
title: string;
children: Component[];
containerEl: HTMLElement;
hacked?: boolean;
initDOM(): HTMLElement;
addChild(c: Component): void;
applyTitle(container: HTMLElement, title: string): void;
}
export class RefLivePlugin implements PluginValue {
constructor(public app: App, public workspace: DendronWorkspace) {}
update(update: ViewUpdate) {
if (!update.state.field(editorLivePreviewField)) {
return;
}
update.view.state.facet(EditorView.decorations).forEach((d) => {
if (typeof d !== "function") {
const iter = d.iter();
while (iter.value) {
const widget = iter.value.spec.widget;
if (widget && widget.href && widget.sourcePath && widget.title) {
const internalWidget = widget as InternalEmbedWidget;
this.hack(internalWidget);
}
iter.next();
}
}
});
}
hack(widget: InternalEmbedWidget) {
if (widget.hacked) {
return;
}
widget.hacked = true;
const target = this.workspace.resolveRef(widget.sourcePath, widget.href);
if (!target || target.type !== "maybe-note") return;
const loadComponent = (widget: InternalEmbedWidget) => {
const renderer = createRefRenderer(target, this.app, widget.containerEl);
if (renderer instanceof | NoteRefRenderChild) renderer.loadFile(); |
widget.addChild(renderer);
};
widget.initDOM = function (this: InternalEmbedWidget) {
this.containerEl = createDiv("internal-embed");
loadComponent(this);
return this.containerEl;
};
widget.applyTitle = function (
this: InternalEmbedWidget,
container: HTMLElement,
title: string
) {
this.title = title;
};
if (widget.containerEl) {
console.log("Workaround");
widget.children[0].unload();
widget.children.pop();
loadComponent(widget);
}
}
}
| src/custom-resolver/ref-live.ts | levirs565-obsidian-dendron-tree-b11ea1e | [
{
"filename": "src/custom-resolver/ref-markdown-processor.ts",
"retrieved_chunk": " embeddedItems.forEach((el) => {\n const link = el.getAttribute(\"src\");\n if (!link) return;\n const target = workspace.resolveRef(context.sourcePath, link);\n if (!target || target.type !== \"maybe-note\") return;\n const renderer = createRefRenderer(target, app, el as HTMLElement);\n if (renderer instanceof NoteRefRenderChild) promises.push(renderer.loadFile());\n context.addChild(renderer);\n });\n return Promise.all(promises);",
"score": 0.8877526521682739
},
{
"filename": "src/custom-resolver/ref-render.ts",
"retrieved_chunk": " content.setText(`\"${target.path}\" is not created yet. Click to create.`);\n this.containerEl.onclick = () => {\n vault.createNote(path).then((file) => openFile(app, file));\n };\n }\n}\nexport function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) {\n if (!target.note || !target.note.file) {\n return new UnresolvedRefRenderChild(app, container, target);\n } else {",
"score": 0.8493505120277405
},
{
"filename": "src/custom-resolver/link-live.ts",
"retrieved_chunk": " widget.updateTitle();\n this.widgets.splice(lastWidgetIndex, 1);\n return widget;\n }\n return new LinkWidget(this.app, this.workspace, sourcePath, link.href, link.title);\n }\n buildDecorations(view: EditorView): DecorationSet {\n if (!view.state.field(editorLivePreviewField)) {\n return Decoration.none;\n }",
"score": 0.8241581916809082
},
{
"filename": "src/custom-resolver/link-live.ts",
"retrieved_chunk": " if (found) break;\n }\n }\n getWidget(link: LinkData, sourcePath: string) {\n const lastWidgetIndex = this.widgets.findIndex(\n (widget) => widget.href === link.href && widget.sourcePath === sourcePath\n );\n if (lastWidgetIndex >= 0) {\n const widget = this.widgets[lastWidgetIndex];\n widget.title = link.title;",
"score": 0.8160557746887207
},
{
"filename": "src/custom-resolver/link-live.ts",
"retrieved_chunk": " this.app.workspace.openLinkText(this.href, this.sourcePath);\n });\n }\n updateTitle() {\n this.containerEl.children[0].setText(\n renderLinkTitle(this.app, this.workspace, this.href, this.title, this.sourcePath)\n );\n }\n toDOM(view: EditorView): HTMLElement {\n if (!this.containerEl) this.initDOM();",
"score": 0.8051855564117432
}
] | typescript | NoteRefRenderChild) renderer.loadFile(); |
import { Component, MarkdownPreviewRenderer, PagePreviewPlugin, Plugin, Workspace } from "obsidian";
import { DendronWorkspace } from "../engine/workspace";
import { createLinkHoverHandler } from "./link-hover";
import { ViewPlugin } from "@codemirror/view";
import { RefLivePlugin } from "./ref-live";
import { createRefMarkdownProcessor } from "./ref-markdown-processor";
import { createLinkOpenHandler } from "./link-open";
import { LinkLivePlugin } from "./link-live";
import { createLinkMarkdownProcessor } from "./link-markdown-processor";
import { LinkRefClickbale } from "./link-ref-clickbale";
export class CustomResolver extends Component {
pagePreviewPlugin?: PagePreviewPlugin;
originalLinkHover: PagePreviewPlugin["onLinkHover"];
originalOpenLinkText: Workspace["openLinkText"];
refPostProcessor = createRefMarkdownProcessor(this.plugin.app, this.workspace);
linkPostProcessor = createLinkMarkdownProcessor(this.plugin.app, this.workspace);
refEditorExtenstion = ViewPlugin.define((v) => {
return new RefLivePlugin(this.plugin.app, this.workspace);
});
linkEditorExtenstion = ViewPlugin.define(
(view) => {
return new LinkLivePlugin(this.plugin.app, this.workspace, view);
},
{
decorations: (value) => value.decorations,
}
);
linkRefClickbaleExtension = ViewPlugin.define((v) => {
return new LinkRefClickbale(v);
});
constructor(public plugin: Plugin, public workspace: DendronWorkspace) {
super();
}
onload(): void {
this.plugin.app.workspace.onLayoutReady(() => {
this.plugin.app.workspace.registerEditorExtension(this.refEditorExtenstion);
this.plugin.app.workspace.registerEditorExtension(this.linkEditorExtenstion);
this.plugin.app.workspace.registerEditorExtension(this.linkRefClickbaleExtension);
this.pagePreviewPlugin = this.plugin.app.internalPlugins.getEnabledPluginById("page-preview");
if (!this.pagePreviewPlugin) return;
this.originalLinkHover = this.pagePreviewPlugin.onLinkHover;
this.pagePreviewPlugin. | onLinkHover = createLinkHoverHandler(
this.plugin.app,
this.workspace,
this.originalLinkHover.bind(this.pagePreviewPlugin)
); |
});
MarkdownPreviewRenderer.registerPostProcessor(this.refPostProcessor);
MarkdownPreviewRenderer.registerPostProcessor(this.linkPostProcessor);
this.originalOpenLinkText = this.plugin.app.workspace.openLinkText;
this.plugin.app.workspace.openLinkText = createLinkOpenHandler(
this.workspace,
this.originalOpenLinkText.bind(this.plugin.app.workspace)
);
}
onunload(): void {
this.plugin.app.workspace.openLinkText = this.originalOpenLinkText;
MarkdownPreviewRenderer.unregisterPostProcessor(this.linkPostProcessor);
MarkdownPreviewRenderer.unregisterPostProcessor(this.refPostProcessor);
this.plugin.app.workspace.unregisterEditorExtension(this.linkRefClickbaleExtension);
this.plugin.app.workspace.unregisterEditorExtension(this.linkEditorExtenstion);
this.plugin.app.workspace.unregisterEditorExtension(this.refEditorExtenstion);
if (!this.pagePreviewPlugin) return;
this.pagePreviewPlugin.onLinkHover = this.originalLinkHover;
}
}
| src/custom-resolver/index.ts | levirs565-obsidian-dendron-tree-b11ea1e | [
{
"filename": "src/custom-resolver/link-ref-clickbale.ts",
"retrieved_chunk": " if (editor && editor.getClickableTokenAt) {\n this.getClickableTokenAtOrig = editor.getClickableTokenAt;\n editor.getClickableTokenAt = LinkRefClickbale.createClickableTokenAtWrapper(\n this.getClickableTokenAtOrig\n );\n }\n }\n destroy(): void {\n if (this.getClickableTokenAtOrig) {\n const editor = this.view.state.field(editorInfoField).editor;",
"score": 0.7313305139541626
},
{
"filename": "src/custom-resolver/link-live.ts",
"retrieved_chunk": " this.app.workspace.openLinkText(this.href, this.sourcePath);\n });\n }\n updateTitle() {\n this.containerEl.children[0].setText(\n renderLinkTitle(this.app, this.workspace, this.href, this.title, this.sourcePath)\n );\n }\n toDOM(view: EditorView): HTMLElement {\n if (!this.containerEl) this.initDOM();",
"score": 0.708859920501709
},
{
"filename": "src/main.ts",
"retrieved_chunk": " this.onRootFolderChanged();\n this.registerEvent(this.app.vault.on(\"create\", this.onCreateFile));\n this.registerEvent(this.app.vault.on(\"delete\", this.onDeleteFile));\n this.registerEvent(this.app.vault.on(\"rename\", this.onRenameFile));\n this.registerEvent(this.app.metadataCache.on(\"resolve\", this.onResolveMetadata));\n this.registerEvent(this.app.workspace.on(\"file-open\", this.onOpenFile, this));\n this.registerEvent(this.app.workspace.on(\"file-menu\", this.onFileMenu));\n });\n this.configureCustomResolver();\n }",
"score": 0.7050460577011108
},
{
"filename": "src/main.ts",
"retrieved_chunk": " this.workspace.changeVault(this.settings.vaultList);\n this.updateNoteStore();\n }\n configureCustomResolver() {\n if (this.settings.customResolver && !this.customResolver) {\n this.customResolver = new CustomResolver(this, this.workspace);\n this.addChild(this.customResolver);\n } else if (!this.settings.customResolver && this.customResolver) {\n this.removeChild(this.customResolver);\n this.customResolver = undefined;",
"score": 0.7045766115188599
},
{
"filename": "src/custom-resolver/ref-render.ts",
"retrieved_chunk": " ) as unknown as HTMLButtonElement;\n buttonComponent.setIcon(\"lucide-link\").setTooltip(\"Open link\");\n buttonComponent.buttonEl.onclick = () => {\n const openState: OpenViewState = {};\n if (this.ref.subpath) {\n openState.eState = {\n subpath: anchorToLinkSubpath(\n this.ref.subpath.start,\n this.app.metadataCache.getFileCache(this.file)?.headings\n ),",
"score": 0.7045042514801025
}
] | typescript | onLinkHover = createLinkHoverHandler(
this.plugin.app,
this.workspace,
this.originalLinkHover.bind(this.pagePreviewPlugin)
); |
import { App, TAbstractFile, TFile, TFolder } from "obsidian";
import { NoteMetadata, NoteTree } from "./note";
import { InvalidRootModal } from "../modal/invalid-root";
import { generateUUID, getFolderFile } from "../utils";
import { ParsedPath } from "../path";
export interface VaultConfig {
path: string;
name: string;
}
export class DendronVault {
folder: TFolder;
tree: NoteTree;
isIniatialized = false;
constructor(public app: App, public config: VaultConfig) {}
private resolveMetadata(file: TFile): NoteMetadata | undefined {
const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter;
if (!frontmatter) return undefined;
return {
title: frontmatter["title"],
};
}
init() {
if (this.isIniatialized) return;
this.tree = new NoteTree();
const root = getFolderFile(this.app.vault, this.config.path);
if (!(root instanceof TFolder)) {
new InvalidRootModal(this).open();
return;
}
this.folder = root;
for (const child of root.children)
if (child instanceof TFile && this.isNote(child.extension))
this.tree.addFile(child).syncMetadata(this.resolveMetadata(child));
this.tree.sort();
this.isIniatialized = true;
}
async createRootFolder() {
return await this.app.vault.createFolder(this.config.path);
}
async createNote(baseName: string) {
const filePath = `${this.config.path}/${baseName}.md`;
return await this.app.vault.create(filePath, "");
}
async generateFronmatter(file: TFile) {
if (!this.isNote(file.extension)) return;
const note = this.tree.getFromFileName(file.basename);
if (!note) return false;
return await this.app.fileManager.processFrontMatter(file, (fronmatter) => {
| if (!fronmatter.id) fronmatter.id = generateUUID(); |
if (!fronmatter.title) fronmatter.title = note.title;
if (fronmatter.desc === undefined) fronmatter.desc = "";
if (!fronmatter.created) fronmatter.created = file.stat.ctime;
if (!fronmatter.updated) fronmatter.updated = file.stat.mtime;
});
}
isNote(extension: string) {
return extension === "md";
}
onFileCreated(file: TAbstractFile): boolean {
if (!(file instanceof TFile) || !this.isNote(file.extension)) return false;
this.tree.addFile(file, true).syncMetadata(this.resolveMetadata(file));
return true;
}
onMetadataChanged(file: TFile): boolean {
if (!this.isNote(file.extension)) return false;
const note = this.tree.getFromFileName(file.basename);
if (!note) return false;
note.syncMetadata(this.resolveMetadata(file));
return true;
}
onFileDeleted(parsed: ParsedPath): boolean {
if (!this.isNote(parsed.extension)) return false;
const note = this.tree.deleteByFileName(parsed.basename);
if (note?.parent) {
note.syncMetadata(undefined);
}
return true;
}
}
| src/engine/vault.ts | levirs565-obsidian-dendron-tree-b11ea1e | [
{
"filename": "src/main.ts",
"retrieved_chunk": " }\n }\n updateNoteStore() {\n dendronVaultList.set(this.workspace.vaultList);\n }\n onCreateFile = async (file: TAbstractFile) => {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (vault && vault.onFileCreated(file)) {\n if (this.settings.autoGenerateFrontmatter && file instanceof TFile && file.stat.size === 0)\n await vault.generateFronmatter(file);",
"score": 0.7934808135032654
},
{
"filename": "src/main.ts",
"retrieved_chunk": " this.updateNoteStore();\n }\n };\n revealFile(file: TFile) {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (!vault) return;\n const note = vault.tree.getFromFileName(file.basename);\n if (!note) return;\n for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON)) {\n if (!(leaf.view instanceof DendronView)) continue;",
"score": 0.7907847166061401
},
{
"filename": "src/engine/note.ts",
"retrieved_chunk": " }\n addFile(file: TFile, sort = false) {\n const titlecase = isUseTitleCase(file.basename);\n const path = NoteTree.getPathFromFileName(file.basename);\n let currentNote: Note = this.root;\n if (!NoteTree.isRootPath(path))\n for (const name of path) {\n let note: Note | undefined = currentNote.findChildren(name);\n if (!note) {\n note = new Note(name, titlecase);",
"score": 0.7715766429901123
},
{
"filename": "src/custom-resolver/ref-render.ts",
"retrieved_chunk": " };\n }\n openFile(this.app, this.ref.note?.file, openState);\n };\n this.renderer = new RefMarkdownRenderer(this, true);\n this.addChild(this.renderer);\n }\n async getContent(): Promise<string> {\n this.markdown = await this.app.vault.cachedRead(this.file);\n if (!this.ref.subpath) {",
"score": 0.7706983089447021
},
{
"filename": "src/custom-resolver/link-render.ts",
"retrieved_chunk": " return title;\n }\n const ref = workspace.resolveRef(sourcePath, href);\n if (!ref || ref.type !== \"maybe-note\" || !ref.note?.file) {\n return href;\n }\n const fileTitle = app.metadataCache.getFileCache(ref.note.file)?.frontmatter?.[\"title\"];\n return fileTitle ?? href;\n}",
"score": 0.7705056667327881
}
] | typescript | if (!fronmatter.id) fronmatter.id = generateUUID(); |
import { App, SuggestModal, getIcon } from "obsidian";
import { Note } from "../engine/note";
import { openFile } from "../utils";
import { DendronVault } from "../engine/vault";
import { SelectVaultModal } from "./select-vault";
import { DendronWorkspace } from "../engine/workspace";
interface LookupItem {
note: Note;
vault: DendronVault;
}
export class LookupModal extends SuggestModal<LookupItem | null> {
constructor(app: App, private workspace: DendronWorkspace, private initialQuery: string = "") {
super(app);
}
onOpen(): void {
super.onOpen();
if (this.initialQuery.length > 0) {
this.inputEl.value = this.initialQuery;
this.inputEl.dispatchEvent(new Event("input"));
}
}
getSuggestions(query: string): (LookupItem | null)[] {
const queryLowercase = query.toLowerCase();
const result: (LookupItem | null)[] = [];
let foundExact = true;
for (const vault of this.workspace.vaultList) {
let currentFoundExact = false;
for (const note of vault.tree.flatten()) {
const path = note.getPath();
const item: LookupItem = {
note,
vault,
};
if (path === queryLowercase) {
currentFoundExact = true;
result.unshift(item);
continue;
}
if (
note.title.toLowerCase().includes(queryLowercase) ||
note.name.includes(queryLowercase) ||
path.includes(queryLowercase)
)
result.push(item);
}
foundExact = foundExact && currentFoundExact;
}
if (!foundExact && queryLowercase.trim().length > 0) result.unshift(null);
return result;
}
renderSuggestion(item: LookupItem | null, el: HTMLElement) {
el.classList.add("mod-complex");
el.createEl("div", { cls: "suggestion-content" }, (el) => {
el.createEl("div", { text: item?.note.title ?? "Create New", cls: "suggestion-title" });
el.createEl("small", {
text: item
? item.note.getPath() +
(this.workspace.vaultList.length > 1 ? ` (${item.vault.config.name})` : "")
: "Note does not exist",
cls: "suggestion-content",
});
});
if (!item || !item.note.file)
el.createEl("div", { cls: "suggestion-aux" }, (el) => {
el.append(getIcon("plus")!);
});
}
async onChooseSuggestion(item: LookupItem | null, evt: MouseEvent | KeyboardEvent) {
if (item && item.note.file) {
openFile(this.app, item.note.file);
return;
}
const path = item ? item.note.getPath() : this.inputEl.value;
const doCreate = async (vault: DendronVault) => {
const file = await vault.createNote(path);
return openFile(vault.app, file);
};
if (item?.vault) {
await doCreate(item.vault);
} else if (this.workspace.vaultList.length == 1) {
await doCreate(this.workspace.vaultList[0]);
} else {
new | SelectVaultModal(this.app, this.workspace, doCreate).open(); |
}
}
}
| src/modal/lookup.ts | levirs565-obsidian-dendron-tree-b11ea1e | [
{
"filename": "src/main.ts",
"retrieved_chunk": " }\n }\n updateNoteStore() {\n dendronVaultList.set(this.workspace.vaultList);\n }\n onCreateFile = async (file: TAbstractFile) => {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (vault && vault.onFileCreated(file)) {\n if (this.settings.autoGenerateFrontmatter && file instanceof TFile && file.stat.size === 0)\n await vault.generateFronmatter(file);",
"score": 0.8084506988525391
},
{
"filename": "src/settings.ts",
"retrieved_chunk": " this.plugin.settings.customResolver = value;\n await this.plugin.saveSettings();\n });\n });\n new Setting(containerEl).setName(\"Vault List\").setHeading();\n for (const vault of this.plugin.settings.vaultList) {\n new Setting(containerEl)\n .setName(vault.name)\n .setDesc(`Folder: ${vault.path}`)\n .addButton((btn) => {",
"score": 0.7859271764755249
},
{
"filename": "src/main.ts",
"retrieved_chunk": " this.updateNoteStore();\n }\n };\n revealFile(file: TFile) {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (!vault) return;\n const note = vault.tree.getFromFileName(file.basename);\n if (!note) return;\n for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON)) {\n if (!(leaf.view instanceof DendronView)) continue;",
"score": 0.7817131280899048
},
{
"filename": "src/main.ts",
"retrieved_chunk": " this.updateNoteStore();\n }\n };\n onDeleteFile = (file: TAbstractFile) => {\n // file.parent is null when file is deleted\n const parsed = parsePath(file.path);\n const vault = this.workspace.findVaultByParentPath(parsed.dir);\n if (vault && vault.onFileDeleted(parsed)) {\n this.updateNoteStore();\n }",
"score": 0.7758308053016663
},
{
"filename": "src/engine/vault.ts",
"retrieved_chunk": " for (const child of root.children)\n if (child instanceof TFile && this.isNote(child.extension))\n this.tree.addFile(child).syncMetadata(this.resolveMetadata(child));\n this.tree.sort();\n this.isIniatialized = true;\n }\n async createRootFolder() {\n return await this.app.vault.createFolder(this.config.path);\n }\n async createNote(baseName: string) {",
"score": 0.7704453468322754
}
] | typescript | SelectVaultModal(this.app, this.workspace, doCreate).open(); |
import {
App,
ButtonComponent,
MarkdownRenderChild,
MarkdownRenderer,
MarkdownRendererConstructorType,
OpenViewState,
TFile,
setIcon,
} from "obsidian";
import { openFile } from "../utils";
import { MaybeNoteRef, RefRange, getRefContentRange, anchorToLinkSubpath } from "../engine/ref";
import { dendronActivityBarName } from "../icons";
const MarkdownRendererConstructor = MarkdownRenderer as unknown as MarkdownRendererConstructorType;
class RefMarkdownRenderer extends MarkdownRendererConstructor {
constructor(public parent: NoteRefRenderChild, queed: boolean) {
super(parent.app, parent.previewEl, queed);
}
get file(): TFile {
return this.parent.file;
}
edit(markdown: string) {
this.parent.editContent(markdown);
}
}
export class NoteRefRenderChild extends MarkdownRenderChild {
previewEl: HTMLElement;
renderer: RefMarkdownRenderer;
file: TFile;
range: RefRange | null;
markdown?: string;
found = false;
constructor(
public readonly app: App,
public readonly containerEl: HTMLElement,
public readonly ref | : MaybeNoteRef
) { |
super(containerEl);
if (!ref.note || !ref.note.file)
throw Error("NoteRefChild only accept ref with non-blank note and file");
this.file = ref.note.file;
this.containerEl.classList.add("dendron-embed", "markdown-embed", "inline-embed", "is-loaded");
this.containerEl.setText("");
const icon = this.containerEl.createDiv("dendron-icon");
setIcon(icon, dendronActivityBarName);
this.previewEl = this.containerEl.createDiv("markdown-embed-content");
const buttonComponent = new ButtonComponent(this.containerEl);
buttonComponent.buttonEl.remove();
buttonComponent.buttonEl = this.containerEl.createDiv(
"markdown-embed-link"
) as unknown as HTMLButtonElement;
buttonComponent.setIcon("lucide-link").setTooltip("Open link");
buttonComponent.buttonEl.onclick = () => {
const openState: OpenViewState = {};
if (this.ref.subpath) {
openState.eState = {
subpath: anchorToLinkSubpath(
this.ref.subpath.start,
this.app.metadataCache.getFileCache(this.file)?.headings
),
};
}
openFile(this.app, this.ref.note?.file, openState);
};
this.renderer = new RefMarkdownRenderer(this, true);
this.addChild(this.renderer);
}
async getContent(): Promise<string> {
this.markdown = await this.app.vault.cachedRead(this.file);
if (!this.ref.subpath) {
this.found = true;
return this.markdown;
}
const metadata = this.app.metadataCache.getFileCache(this.file);
if (metadata) {
this.range = getRefContentRange(this.ref.subpath, metadata);
if (this.range) {
let currentLineIndex = 0;
while (currentLineIndex < this.range.startLineOffset) {
if (this.markdown[this.range.start] === "\n") currentLineIndex++;
this.range.start++;
}
this.found = true;
return this.markdown.substring(this.range.start, this.range.end);
}
}
this.found = false;
return "### Unable to find section "
.concat(this.ref.subpath.text, " in ")
.concat(this.file.basename);
}
editContent(target: string) {
if (!this.found || !this.markdown) return;
let md;
if (!this.range) {
md = target;
} else {
const before = this.markdown.substring(0, this.range.start);
md = before + target;
if (this.range.end) {
const after = this.markdown.substring(this.range.end);
md += after;
}
}
this.app.vault.modify(this.file, md);
}
async loadFile() {
const content = await this.getContent();
this.renderer.renderer.set(content);
}
onload(): void {
super.onload();
this.registerEvent(
this.app.metadataCache.on("changed", async (file, data) => {
if (file === this.file) {
this.loadFile();
}
})
);
}
}
export class UnresolvedRefRenderChild extends MarkdownRenderChild {
constructor(app: App, containerEl: HTMLElement, target: MaybeNoteRef) {
super(containerEl);
this.containerEl.classList.add("dendron-embed", "file-embed", "mod-empty", "is-loaded");
this.containerEl.setText("");
const icon = this.containerEl.createDiv("dendron-icon");
setIcon(icon, dendronActivityBarName);
const content = this.containerEl.createDiv();
const { vaultName, vault, path } = target;
if (vaultName === "") {
content.setText("Vault name are unspecified in link.");
return;
} else if (!vault) {
content.setText(`Vault ${vaultName} are not found.`);
return;
} else if (path === "") {
content.setText("Note path are unspecified in link.");
return;
}
content.setText(`"${target.path}" is not created yet. Click to create.`);
this.containerEl.onclick = () => {
vault.createNote(path).then((file) => openFile(app, file));
};
}
}
export function createRefRenderer(target: MaybeNoteRef, app: App, container: HTMLElement) {
if (!target.note || !target.note.file) {
return new UnresolvedRefRenderChild(app, container, target);
} else {
return new NoteRefRenderChild(app, container, target);
}
}
| src/custom-resolver/ref-render.ts | levirs565-obsidian-dendron-tree-b11ea1e | [
{
"filename": "src/custom-resolver/link-live.ts",
"retrieved_chunk": " public workspace: DendronWorkspace,\n public sourcePath: string,\n public href: string,\n public title: string | undefined\n ) {\n super();\n }\n initDOM() {\n this.containerEl = createSpan(\n {",
"score": 0.8845031261444092
},
{
"filename": "src/obsidian-ex.d.ts",
"retrieved_chunk": " onLinkHover(\n parent: HoverParent,\n tergetEl: HTMLElement,\n link: string,\n sourcePath: string,\n state: EditorState\n );\n }\n interface InternalPlugins {\n \"page-preview\": PagePreviewPlugin;",
"score": 0.8664077520370483
},
{
"filename": "src/custom-resolver/link-live.ts",
"retrieved_chunk": " return this.containerEl;\n }\n}\ninterface LinkData {\n start: number;\n end: number;\n href: string;\n title: string | undefined;\n hasAlias: boolean;\n showSource: boolean;",
"score": 0.864266037940979
},
{
"filename": "src/engine/ref.ts",
"retrieved_chunk": " }\n | {\n type: \"header\";\n name: string;\n lineOffset: number;\n };\nexport interface RefRange {\n start: number;\n startLineOffset: number;\n /* undefined = end of file */",
"score": 0.838390588760376
},
{
"filename": "src/custom-resolver/link-render.ts",
"retrieved_chunk": "import { App } from \"obsidian\";\nimport { DendronWorkspace } from \"../engine/workspace\";\nexport function renderLinkTitle(\n app: App,\n workspace: DendronWorkspace,\n href: string,\n title: string | undefined,\n sourcePath: string\n) {\n if (title) {",
"score": 0.8382537364959717
}
] | typescript | : MaybeNoteRef
) { |
import { App, TAbstractFile, TFile, TFolder } from "obsidian";
import { NoteMetadata, NoteTree } from "./note";
import { InvalidRootModal } from "../modal/invalid-root";
import { generateUUID, getFolderFile } from "../utils";
import { ParsedPath } from "../path";
export interface VaultConfig {
path: string;
name: string;
}
export class DendronVault {
folder: TFolder;
tree: NoteTree;
isIniatialized = false;
constructor(public app: App, public config: VaultConfig) {}
private resolveMetadata(file: TFile): NoteMetadata | undefined {
const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter;
if (!frontmatter) return undefined;
return {
title: frontmatter["title"],
};
}
init() {
if (this.isIniatialized) return;
this.tree = new NoteTree();
const root = getFolderFile(this.app.vault, this.config.path);
if (!(root instanceof TFolder)) {
new InvalidRootModal(this).open();
return;
}
this.folder = root;
for (const child of root.children)
if (child instanceof TFile && this.isNote(child.extension))
this.tree.addFile(child).syncMetadata(this.resolveMetadata(child));
this.tree.sort();
this.isIniatialized = true;
}
async createRootFolder() {
return await this.app.vault.createFolder(this.config.path);
}
async createNote(baseName: string) {
const filePath = `${this.config.path}/${baseName}.md`;
return await this.app.vault.create(filePath, "");
}
async generateFronmatter(file: TFile) {
if (!this.isNote(file.extension)) return;
const note = this.tree.getFromFileName(file.basename);
if (!note) return false;
return await this.app.fileManager.processFrontMatter(file, (fronmatter) => {
if (!fronmatter.id) fronmatter.id = generateUUID();
if (!fronmatter.title) fronmatter.title = note.title;
if (fronmatter.desc === undefined) fronmatter.desc = "";
if (!fronmatter.created) fronmatter.created = file.stat.ctime;
if (!fronmatter.updated) fronmatter.updated = file.stat.mtime;
});
}
isNote(extension: string) {
return extension === "md";
}
onFileCreated(file: TAbstractFile): boolean {
if (!(file instanceof TFile) || !this.isNote(file.extension)) return false;
this.tree.addFile(file, true).syncMetadata(this.resolveMetadata(file));
return true;
}
onMetadataChanged(file: TFile): boolean {
if (!this.isNote(file.extension)) return false;
const note = this.tree.getFromFileName(file.basename);
if (!note) return false;
note.syncMetadata(this.resolveMetadata(file));
return true;
}
| onFileDeleted(parsed: ParsedPath): boolean { |
if (!this.isNote(parsed.extension)) return false;
const note = this.tree.deleteByFileName(parsed.basename);
if (note?.parent) {
note.syncMetadata(undefined);
}
return true;
}
}
| src/engine/vault.ts | levirs565-obsidian-dendron-tree-b11ea1e | [
{
"filename": "src/main.ts",
"retrieved_chunk": " this.updateNoteStore();\n }\n };\n onDeleteFile = (file: TAbstractFile) => {\n // file.parent is null when file is deleted\n const parsed = parsePath(file.path);\n const vault = this.workspace.findVaultByParentPath(parsed.dir);\n if (vault && vault.onFileDeleted(parsed)) {\n this.updateNoteStore();\n }",
"score": 0.8361974954605103
},
{
"filename": "src/main.ts",
"retrieved_chunk": " this.updateNoteStore();\n }\n };\n revealFile(file: TFile) {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (!vault) return;\n const note = vault.tree.getFromFileName(file.basename);\n if (!note) return;\n for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON)) {\n if (!(leaf.view instanceof DendronView)) continue;",
"score": 0.8202565908432007
},
{
"filename": "src/engine/note.ts",
"retrieved_chunk": " }\n addFile(file: TFile, sort = false) {\n const titlecase = isUseTitleCase(file.basename);\n const path = NoteTree.getPathFromFileName(file.basename);\n let currentNote: Note = this.root;\n if (!NoteTree.isRootPath(path))\n for (const name of path) {\n let note: Note | undefined = currentNote.findChildren(name);\n if (!note) {\n note = new Note(name, titlecase);",
"score": 0.818966269493103
},
{
"filename": "src/engine/note.ts",
"retrieved_chunk": " currentNote.appendChild(note);\n if (sort) currentNote.sortChildren(false);\n }\n currentNote = note;\n }\n currentNote.file = file;\n return currentNote;\n }\n getFromFileName(name: string) {\n const path = NoteTree.getPathFromFileName(name);",
"score": 0.8152607679367065
},
{
"filename": "src/engine/note.ts",
"retrieved_chunk": " if (NoteTree.isRootPath(path)) return this.root;\n let currentNote: Note = this.root;\n for (const name of path) {\n const found = currentNote.findChildren(name);\n if (!found) return undefined;\n currentNote = found;\n }\n return currentNote;\n }\n deleteByFileName(name: string) {",
"score": 0.8139248490333557
}
] | typescript | onFileDeleted(parsed: ParsedPath): boolean { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.