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
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": 23.751290078051113 }, { "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": 18.59190442962408 }, { "filename": "src/main/ipfs.ts", "retrieved_chunk": " res.on('data', (chunk) => {\n data += chunk;\n });\n res.on('end', () => {\n resolve(data.trim().split('\\n').pop() || '');\n });\n })\n .on('error', (err) => {\n reject(err);\n });", "score": 15.717274628626258 }, { "filename": "src/main/follower.ts", "retrieved_chunk": " .get('https://dist.ipfs.tech/ipfs-cluster-follow/versions', (res) => {\n let data = '';\n res.on('data', (chunk) => {\n data += chunk;\n });\n res.on('end', () => {\n resolve(data.trim().split('\\n').pop() || '');\n });\n })\n .on('error', (err) => {", "score": 15.6788289564654 }, { "filename": "src/renderer/Ipfs/useIsFollowerRunning.ts", "retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { useIsFollowerInstalled } from './useIsFollowerInstalled';\nconst { ipcRenderer } = window?.electron || {};\nexport function useIsFollowerRunning() {\n const { data: isInstalled } = useIsFollowerInstalled();\n return useQuery({\n queryKey: ['follower', 'isRunning'],\n queryFn: () => ipcRenderer.invoke('follower-isRunning'),\n initialData: () => false,\n placeholderData: false,", "score": 15.670573062920743 } ]
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('tray@3x.png')); 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": 15.730567778584716 }, { "filename": "src/main/peers.ts", "retrieved_chunk": " if (response.ok) {\n const state = (await response.json()) as { peers: Peer[] };\n return state.peers.sort((a, b) => a.id.localeCompare(b.id));\n }\n return [];\n } catch (e) {\n logger.error(e);\n return [];\n }\n}", "score": 12.112682840375149 }, { "filename": "src/main/follower.ts", "retrieved_chunk": " 'utf8'\n )\n );\n return identity.id;\n } catch (_error) {\n return '';\n }\n}\nexport async function configureFollower({ log = logger.log } = {}) {\n if (await isConfigured()) {", "score": 10.926677161182285 }, { "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": 9.791622386775071 }, { "filename": "src/main/follower.ts", "retrieved_chunk": " logger.log('Killing ipfs-cluster-follow', pid);\n process.kill(pid);\n }\n );\n } catch (_e) {\n // whatever\n }\n}\nexport async function followerPid() {\n return await getPid(", "score": 9.689704684320352 } ]
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('tray@3x.png')); 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": 73.41281221238009 }, { "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": 69.7520215634495 }, { "filename": "src/renderer/DApps/Dapps.tsx", "retrieved_chunk": " <DappButton key={dapp.id} dapp={dapp} />\n ))}\n </Stack>\n </Box>\n </Box>\n );\n}", "score": 66.52216973312065 }, { "filename": "src/renderer/DApps/Dapps.tsx", "retrieved_chunk": " colorScheme=\"teal\"\n leftIcon={<Image src={dapp.icon} alt={dapp.label} width=\"1em\" />}\n rightIcon={dapp.url ? <ExternalLinkIcon /> : <Spinner size=\"xs\" />}\n isDisabled={!dapp.url}\n _hover={{ textDecoration: 'none' }}\n >\n {dapp.label}\n </Button>\n );\n}", "score": 61.04673744919594 }, { "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": 57.950346568371444 } ]
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/config.ts", "retrieved_chunk": "import { z } from 'zod';\nexport const DappSchema = z\n .object({\n id: z.string(),\n label: z.string(),\n icon: z.string(),\n ens: z.string().optional(),\n ipns: z.string().optional(),\n qm: z.string().optional(),\n bafy: z.string().optional(),", "score": 26.67584528157746 }, { "filename": "src/main/main.ts", "retrieved_chunk": " await ipfs(`cat /ipns/${SYNTHETIX_NODE_APP_CONFIG}`)\n );\n logger.log('App config fetched', config);\n if (config.dapps) {\n const oldDapps = DAPPS.splice(0);\n for (const dapp of config.dapps) {\n const oldDapp = oldDapps.find((d) => d.id === dapp.id);\n if (oldDapp) {\n DAPPS.push(Object.assign({}, oldDapp, dapp));\n } else {", "score": 25.215621905666303 }, { "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": 20.2574334064396 }, { "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": 15.568482734833031 }, { "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": 14.96865906540795 } ]
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": 25.886473851712438 }, { "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": 20.72221018844969 }, { "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": 20.29065268139376 }, { "filename": "src/main/ipfs.ts", "retrieved_chunk": " res.on('data', (chunk) => {\n data += chunk;\n });\n res.on('end', () => {\n resolve(data.trim().split('\\n').pop() || '');\n });\n })\n .on('error', (err) => {\n reject(err);\n });", "score": 19.646593285782824 }, { "filename": "src/main/follower.ts", "retrieved_chunk": " .get('https://dist.ipfs.tech/ipfs-cluster-follow/versions', (res) => {\n let data = '';\n res.on('data', (chunk) => {\n data += chunk;\n });\n res.on('end', () => {\n resolve(data.trim().split('\\n').pop() || '');\n });\n })\n .on('error', (err) => {", "score": 19.59853619558175 } ]
typescript
const { data: peerId } = usePeerId();
/** * 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('tray@3x.png')); 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/config-check.ts", "retrieved_chunk": "import { ConfigSchema } from './config';\nimport config from '../config.json';\nConfigSchema.parse(config);", "score": 31.467681379007814 }, { "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": 28.368827549936533 }, { "filename": "src/renderer/DApps/useDapps.ts", "retrieved_chunk": "import { useQuery } from '@tanstack/react-query';\nimport { DappsSchema } from '../../config';\nconst { ipcRenderer } = window?.electron || {};\nexport function useDapps() {\n return useQuery({\n queryKey: ['dapps'],\n queryFn: async () => {\n return DappsSchema.parse(await ipcRenderer.invoke('dapps'));\n },\n initialData: () => [],", "score": 27.530914060040406 }, { "filename": "src/main/ipfs.ts", "retrieved_chunk": " log(\n await ipfs(\n 'config --json API.HTTPHeaders.Access-Control-Allow-Origin \\'[\"*\"]\\''\n )\n );\n log(\n await ipfs(\n 'config --json API.HTTPHeaders.Access-Control-Allow-Methods \\'[\"PUT\", \"POST\", \"GET\"]\\''\n )\n );", "score": 23.846614801968045 }, { "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": 23.71838795827325 } ]
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('tray@3x.png')); 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": 20.935998923689517 }, { "filename": "src/main/dapps.ts", "retrieved_chunk": "}\nexport async function isPinned(qm: string): Promise<boolean> {\n try {\n const result = await ipfs(`pin ls --type recursive ${qm}`);\n return result.includes(qm);\n } catch (e) {\n return false;\n }\n}\nexport async function resolveDapp(dapp: DappType): Promise<void> {", "score": 15.392525928606839 }, { "filename": "src/main/dapps.ts", "retrieved_chunk": " if (dapp.ipns) {\n return {\n codec: 'ipns-ns',\n hash: dapp.ipns,\n };\n }\n if (!dapp.ens) {\n throw new Error('Neither ipns nor ens was set, cannot resolve');\n }\n const name = normalize(dapp.ens);", "score": 14.337907867934726 }, { "filename": "src/main/dapps.ts", "retrieved_chunk": " try {\n const { codec, hash } = await resolveEns(dapp);\n logger.log(dapp.id, 'resolved', codec, hash);\n const qm =\n codec === 'ipns-ns'\n ? await resolveQm(hash)\n : codec === 'ipfs-ns'\n ? hash\n : undefined;\n if (qm) {", "score": 13.741814045335405 }, { "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": 12.267093512495697 } ]
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": 28.021657625373763 }, { "filename": "src/main/ipfs.ts", "retrieved_chunk": " res.on('data', (chunk) => {\n data += chunk;\n });\n res.on('end', () => {\n resolve(data.trim().split('\\n').pop() || '');\n });\n })\n .on('error', (err) => {\n reject(err);\n });", "score": 23.57591194293939 }, { "filename": "src/main/follower.ts", "retrieved_chunk": " .get('https://dist.ipfs.tech/ipfs-cluster-follow/versions', (res) => {\n let data = '';\n res.on('data', (chunk) => {\n data += chunk;\n });\n res.on('end', () => {\n resolve(data.trim().split('\\n').pop() || '');\n });\n })\n .on('error', (err) => {", "score": 23.5182434346981 }, { "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": 22.8525159472753 }, { "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": 22.39661064307168 } ]
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('tray@3x.png')); 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": 16.16108240654201 }, { "filename": "src/renderer/preload.d.ts", "retrieved_chunk": "import { ElectronHandler } from 'main/preload';\ndeclare global {\n // eslint-disable-next-line no-unused-vars\n interface Window {\n electron: ElectronHandler;\n }\n}\nexport {};", "score": 15.679102449598567 }, { "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": 8.796326851008098 }, { "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": 8.613569355442415 }, { "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": 8.501517232918971 } ]
typescript
mainWindow.loadURL(resolveHtmlPath('index.html'));
/** * 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('tray@3x.png')); 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": 10.588639509345558 }, { "filename": "src/renderer/DApps/Dapps.tsx", "retrieved_chunk": "export function Dapps() {\n const { data: dapps } = useDapps();\n return (\n <Box pt=\"4\" px=\"4\" pb=\"4\">\n <Box flex=\"1\" p=\"0\">\n <Heading mb=\"3\" size=\"sm\">\n Available DApps:\n </Heading>\n <Stack direction=\"row\" spacing={6} justifyContent=\"start\" mb=\"2\">\n {dapps.map((dapp: DappType) => (", "score": 8.842885543169833 }, { "filename": "src/main/dapps.ts", "retrieved_chunk": "Object.assign(global, { fetch });\nexport const DAPPS: DappType[] = [];\nconst client = createPublicClient({\n chain: mainnet,\n transport: http(),\n});\nconst resolverAbi = [\n {\n constant: true,\n inputs: [{ internalType: 'bytes32', name: 'node', type: 'bytes32' }],", "score": 8.300056487441854 }, { "filename": "src/config.ts", "retrieved_chunk": " dapps: DappsSchema,\n })\n .strict();\nexport type DappType = z.infer<typeof DappSchema>;", "score": 8.097298837721121 }, { "filename": "src/main/dapps.ts", "retrieved_chunk": " if (dapp.ipns) {\n return {\n codec: 'ipns-ns',\n hash: dapp.ipns,\n };\n }\n if (!dapp.ens) {\n throw new Error('Neither ipns nor ens was set, cannot resolve');\n }\n const name = normalize(dapp.ens);", "score": 8.020743645506698 } ]
typescript
dapps: DAPPS.map((dapp) => {
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/config.ts", "retrieved_chunk": " url: z.string().optional(),\n })\n .strict()\n .refine((obj) => Boolean(obj.ens || obj.ipns), {\n message: 'ens or ipns must be defined',\n path: ['ens'],\n });\nexport const DappsSchema = z.array(DappSchema);\nexport const ConfigSchema = z\n .object({", "score": 19.778902481583273 }, { "filename": "src/config.ts", "retrieved_chunk": "import { z } from 'zod';\nexport const DappSchema = z\n .object({\n id: z.string(),\n label: z.string(),\n icon: z.string(),\n ens: z.string().optional(),\n ipns: z.string().optional(),\n qm: z.string().optional(),\n bafy: z.string().optional(),", "score": 18.09944228853063 }, { "filename": "src/main/follower.ts", "retrieved_chunk": " } else {\n resolve(stdout.trim());\n }\n }\n );\n });\n}\nexport async function getLatestVersion(): Promise<string> {\n return new Promise((resolve, reject) => {\n https", "score": 15.147660866008131 }, { "filename": "src/main/follower.ts", "retrieved_chunk": " return;\n }\n try {\n log(\n await follower(\n `synthetix init \"http://127.0.0.1:8080/ipns/${SYNTHETIX_IPNS}\"`\n )\n );\n } catch (_error) {\n // ignore", "score": 14.292901946351376 }, { "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": 14.137417750694866 } ]
typescript
const ipfsPath = await ipfs(`resolve /ipns/${ipns}`);
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": 26.19892862348295 }, { "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": 23.102810979195652 }, { "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": 17.763236394420492 }, { "filename": "src/modals/CssSnippetCreateModal.ts", "retrieved_chunk": "\t\tthis.plugin = plugin;\n\t}\n\tonOpen(): void {\n\t\tsuper.onOpen();\n\t\tthis.titleEl.setText(\"Create CSS Snippet\");\n\t\tthis.containerEl.addClass(\"css-editor-create-modal\");\n\t\tthis.buildForm();\n\t}\n\tprivate buildForm() {\n\t\tconst textInput = new TextComponent(this.contentEl);", "score": 14.161434167305714 }, { "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": 9.782361857722687 } ]
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('tray@3x.png')); 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/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": 24.77660677834614 }, { "filename": "src/main/follower.ts", "retrieved_chunk": " } catch (_e) {\n return false;\n }\n}\nexport async function followerDaemon() {\n const isInstalled = await followerIsInstalled();\n if (!isInstalled) {\n return;\n }\n const pid = await getPid(", "score": 7.842939992216374 }, { "filename": "src/main/dapps.ts", "retrieved_chunk": " if (dapp.ipns) {\n return {\n codec: 'ipns-ns',\n hash: dapp.ipns,\n };\n }\n if (!dapp.ens) {\n throw new Error('Neither ipns nor ens was set, cannot resolve');\n }\n const name = normalize(dapp.ens);", "score": 7.4939420765502955 }, { "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": 7.1721124621643835 }, { "filename": "src/main/ipfs.ts", "retrieved_chunk": " if (statusCode === 404) {\n resolve(true);\n } else {\n resolve(false);\n }\n res.resume();\n })\n .once('error', (_error) => resolve(false));\n });\n}", "score": 6.891930807078097 } ]
typescript
settings.set('dock', false);
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/file-system-helpers.ts", "retrieved_chunk": "\tconst errors = {\n\t\texists: \"\",\n\t\tregex: \"\",\n\t};\n\tif (value.length > 0 && (await checkSnippetExists(this.app, value))) {\n\t\terrors.exists = \"File already exists.\";\n\t}\n\tconst regex = /^[0-9a-zA-Z\\-_ ]+\\.css$/;\n\tif (!regex.test(value)) {\n\t\terrors.regex =", "score": 15.866397942455038 }, { "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": 12.81275556156111 }, { "filename": "src/obsidian.d.ts", "retrieved_chunk": "/* eslint-disable no-mixed-spaces-and-tabs */\nimport \"obsidian\";\ndeclare module \"obsidian\" {\n\tinterface App {\n\t\tcustomCss:\n\t\t\t| {\n\t\t\t\t\tsnippets: string[] | undefined;\n\t\t\t\t\tsetCssEnabledStatus:\n\t\t\t\t\t\t| ((name: string, value: boolean) => void)\n\t\t\t\t\t\t| undefined;", "score": 12.236280662434172 }, { "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": 11.501922457293784 }, { "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": 11.427266699087792 } ]
typescript
ErrorNotice(err.message);
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": 28.32997488806753 }, { "filename": "src/main/ipfs.ts", "retrieved_chunk": " // whatever\n }\n}\nexport async function ipfsPid() {\n return await getPid('.synthetix/go-ipfs/ipfs daemon');\n}\nexport async function ipfsIsInstalled() {\n try {\n await fs.access(path.join(ROOT, 'go-ipfs/ipfs'), fs.constants.F_OK);\n return true;", "score": 20.427980312698846 }, { "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": 17.875753941704197 }, { "filename": "src/main/settings.ts", "retrieved_chunk": " path.join(ROOT, 'setting.json'),\n JSON.stringify(settings, null, 2),\n 'utf8'\n );\n } catch (_error) {\n // whatever\n }\n return settings;\n}\nexport async function get(key: string) {", "score": 15.939685400353447 }, { "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": 13.775496021704202 } ]
typescript
return service.includes(SYNTHETIX_IPNS);
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": 15.010668369325096 }, { "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": 11.490895215355422 }, { "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": 11.293924521388691 }, { "filename": "src/workspace-helpers.ts", "retrieved_chunk": "\t});\n\tworkspace.setActiveLeaf(leaf);\n}\nexport function detachLeavesOfTypeAndDisplay(\n\tworkspace: Workspace,\n\ttype: ViewState[\"type\"],\n\tdisplay: string\n) {\n\tconst leaves = workspace.getLeavesOfType(type);\n\tleaves.forEach((leaf) => {", "score": 11.236807298430662 }, { "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": 11.024355492184908 } ]
typescript
VIEW_TYPE_CSS, (leaf) => new CssEditorView(leaf));
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/main.ts", "retrieved_chunk": "\t\topenView(this.app.workspace, VIEW_TYPE_CSS, { filename });\n\t}\n}", "score": 38.009131918839586 }, { "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": 34.75934180662291 }, { "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": 18.716190702601196 }, { "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": 17.589608172720194 }, { "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": 17.363475198092804 } ]
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": 26.19892862348295 }, { "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": 23.102810979195652 }, { "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": 17.763236394420492 }, { "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": 9.782361857722687 }, { "filename": "src/file-system-helpers.ts", "retrieved_chunk": "}\nexport async function deleteSnippetFile(app: App, fileName: string) {\n\tawait app.vault.adapter.remove(`${getSnippetDirectory(app)}${fileName}`);\n}\nasync function _createSnippetDirectoryIfNotExists(app: App) {\n\tif (!(await app.vault.adapter.exists(getSnippetDirectory(app)))) {\n\t\tawait app.vault.adapter.mkdir(getSnippetDirectory(app));\n\t}\n}\nasync function _validateFilename(value: string) {", "score": 9.470780752064762 } ]
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": 40.07961430540606 }, { "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": 34.222244034565364 }, { "filename": "src/components/UserIP/index.tsx", "retrieved_chunk": " </div>\n );\n};\nexport default UserIP;", "score": 15.597408341616106 }, { "filename": "src/hooks/useIPScanner.ts", "retrieved_chunk": " currentIP: ip,\n tryChar: TRY_CHARS[i] || \"\",\n };\n if (i === 0) {\n timeout = multiply * state.maxLatency;\n newState.color = \"red\";\n newState.currentLatency = 0;\n } else {\n timeout = 1.2 * multiply * state.maxLatency;\n newState.color = \"green\";", "score": 15.340142932151313 }, { "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": 14.275834714421412 } ]
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/workspace-helpers.ts", "retrieved_chunk": "\t});\n\tworkspace.setActiveLeaf(leaf);\n}\nexport function detachLeavesOfTypeAndDisplay(\n\tworkspace: Workspace,\n\ttype: ViewState[\"type\"],\n\tdisplay: string\n) {\n\tconst leaves = workspace.getLeavesOfType(type);\n\tleaves.forEach((leaf) => {", "score": 15.160481262293452 }, { "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": 15.010668369325096 }, { "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": 11.490895215355422 }, { "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": 11.293924521388691 }, { "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": 11.024355492184908 } ]
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": 42.97579962659358 }, { "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": 30.184128799087656 }, { "filename": "src/hooks/useIPScanner.ts", "retrieved_chunk": " currentIP: ip,\n tryChar: TRY_CHARS[i] || \"\",\n };\n if (i === 0) {\n timeout = multiply * state.maxLatency;\n newState.color = \"red\";\n newState.currentLatency = 0;\n } else {\n timeout = 1.2 * multiply * state.maxLatency;\n newState.color = \"green\";", "score": 21.166355039446604 }, { "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": 17.3862037018555 }, { "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": 17.022165314922507 } ]
typescript
className={`mx-2 inline-block h-6 w-6 transform-gpu text-center text-blue-600 duration-300 ${tryCharToRotation[tryChar]}`}
/* 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": 40.07961430540606 }, { "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": 34.222244034565364 }, { "filename": "src/components/UserIP/index.tsx", "retrieved_chunk": " </div>\n );\n};\nexport default UserIP;", "score": 15.597408341616106 }, { "filename": "src/hooks/useIPScanner.ts", "retrieved_chunk": " currentIP: ip,\n tryChar: TRY_CHARS[i] || \"\",\n };\n if (i === 0) {\n timeout = multiply * state.maxLatency;\n newState.color = \"red\";\n newState.currentLatency = 0;\n } else {\n timeout = 1.2 * multiply * state.maxLatency;\n newState.color = \"green\";", "score": 15.340142932151313 }, { "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": 14.275834714421412 } ]
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": 14.174222742986478 }, { "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": 8.24334904037595 }, { "filename": "src/helpers/copyIPToClipboard.ts", "retrieved_chunk": "import { toast } from \"react-hot-toast\";\nexport async function copyIPToClipboard(ip: string) {\n try {\n await navigator.clipboard.writeText(ip);\n toast.success(`IP ${ip} copied to clipboard!`);\n } catch (error) {\n toast.error(`Failed to copy IP ${ip} to clipboard!`);\n console.error(error);\n }\n}", "score": 7.6025477433413755 }, { "filename": "src/hooks/useIPScanner.ts", "retrieved_chunk": " addValidIP({\n ip,\n latency,\n });\n }\n if (\n getScanState() !== \"scanning\" ||\n getValidIPCount() >= state.maxIPCount\n ) {\n break;", "score": 7.093092764757808 }, { "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": 6.576369252405758 } ]
typescript
onClick={() => copyIPToClipboard(ip)}
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/file-system-helpers.ts", "retrieved_chunk": "\tconst errors = {\n\t\texists: \"\",\n\t\tregex: \"\",\n\t};\n\tif (value.length > 0 && (await checkSnippetExists(this.app, value))) {\n\t\terrors.exists = \"File already exists.\";\n\t}\n\tconst regex = /^[0-9a-zA-Z\\-_ ]+\\.css$/;\n\tif (!regex.test(value)) {\n\t\terrors.regex =", "score": 22.93365018061628 }, { "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": 15.699044441108079 }, { "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": 15.286743832453244 }, { "filename": "src/obsidian.d.ts", "retrieved_chunk": "/* eslint-disable no-mixed-spaces-and-tabs */\nimport \"obsidian\";\ndeclare module \"obsidian\" {\n\tinterface App {\n\t\tcustomCss:\n\t\t\t| {\n\t\t\t\t\tsnippets: string[] | undefined;\n\t\t\t\t\tsetCssEnabledStatus:\n\t\t\t\t\t\t| ((name: string, value: boolean) => void)\n\t\t\t\t\t\t| undefined;", "score": 14.976530946912316 }, { "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": 14.194714937075965 } ]
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": 14.174222742986478 }, { "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": 8.24334904037595 }, { "filename": "src/helpers/copyIPToClipboard.ts", "retrieved_chunk": "import { toast } from \"react-hot-toast\";\nexport async function copyIPToClipboard(ip: string) {\n try {\n await navigator.clipboard.writeText(ip);\n toast.success(`IP ${ip} copied to clipboard!`);\n } catch (error) {\n toast.error(`Failed to copy IP ${ip} to clipboard!`);\n console.error(error);\n }\n}", "score": 7.6025477433413755 }, { "filename": "src/hooks/useIPScanner.ts", "retrieved_chunk": " addValidIP({\n ip,\n latency,\n });\n }\n if (\n getScanState() !== \"scanning\" ||\n getValidIPCount() >= state.maxIPCount\n ) {\n break;", "score": 7.093092764757808 }, { "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": 6.576369252405758 } ]
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/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": 13.962390803811575 }, { "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": 13.57872929229638 }, { "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": 12.262111676993054 }, { "filename": "src/helpers/copyIPToClipboard.ts", "retrieved_chunk": "import { toast } from \"react-hot-toast\";\nexport async function copyIPToClipboard(ip: string) {\n try {\n await navigator.clipboard.writeText(ip);\n toast.success(`IP ${ip} copied to clipboard!`);\n } catch (error) {\n toast.error(`Failed to copy IP ${ip} to clipboard!`);\n console.error(error);\n }\n}", "score": 11.232113323032783 }, { "filename": "src/helpers/rangeToIpArray.ts", "retrieved_chunk": " i & 0xff,\n ].join(\".\");\n ips.push(ip);\n }\n return ips;\n}", "score": 11.013822887948745 } ]
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": " crowdinPayloadArticleDirectory.originalId\n );\n await this.payload.delete({\n collection: \"crowdin-article-directories\",\n id: crowdinPayloadArticleDirectory.id,\n });\n }\n async getFileByDocumentID(name: string, documentId: string) {\n const result = await getFileByDocumentID(name, documentId, this.payload);\n return result;", "score": 33.36069728935818 }, { "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": 29.24231961344304 }, { "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": 25.52316458756436 }, { "filename": "src/api/payload-crowdin-sync/files.ts", "retrieved_chunk": " }\n async getFile(name: string, crowdinArticleDirectoryId: string): Promise<any> {\n return getFile(name, crowdinArticleDirectoryId, this.payload);\n }\n async getFiles(crowdinArticleDirectoryId: string): Promise<any> {\n return getFiles(crowdinArticleDirectoryId, this.payload);\n }\n /**\n * Create/Update/Delete a file on Crowdin\n *", "score": 23.72955451280685 }, { "filename": "src/api/payload-crowdin-sync/files.ts", "retrieved_chunk": " getArticleDirectory,\n getFile,\n getFiles,\n getFileByDocumentID,\n getFilesByDocumentID,\n} from \"../helpers\";\nimport { isEmpty } from \"lodash\";\nexport interface IcrowdinFile {\n id: string;\n originalId: number;", "score": 20.25042570019383 } ]
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": 94.00798499973267 }, { "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": 52.47828689430215 }, { "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": 51.44687914845274 }, { "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": 41.58488157947414 }, { "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": 37.849093991234 } ]
typescript
mockCrowdinClient(pluginOptions) as any) : translationsApi;
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": 18.875812404448652 }, { "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": 14.695062223356196 }, { "filename": "src/bin/command/wp.ts", "retrieved_chunk": " console.log(`\\nContent has been updated on https://${domainFound.domain}${slug}\\n\\n`)\n })\n}\nasync function getAllWp () {\n const wpSites = await getAllWordpress()\n if (wpSites.length === 0) {\n console.log('\\nNo Wordpress site found\\n')\n return\n }\n console.log('\\nWordpress sites :\\n')", "score": 14.202879903564504 }, { "filename": "src/lib/post-helpers.ts", "retrieved_chunk": " }\n return extractPostOutlineFromCodeBlock(this.chatParentMessage.text)\n }\n async generateAudienceIntent () {\n const prompt = getPromptForAudienceIntent(this.postPrompt)\n if (this.postPrompt.debug) {\n console.log('---------- PROMPT AUDIENCE INTENT ----------')\n console.log(prompt)\n }\n const response = await this.sendRequest(prompt)", "score": 13.136170638839385 }, { "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": 12.635591738116098 } ]
typescript
) : PostOutline {
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/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": 24.56329424716607 }, { "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": 23.737935589065167 }, { "filename": "src/api/payload-crowdin-sync/files.ts", "retrieved_chunk": " // Update not possible. Article name needs to be updated manually on Crowdin.\n // The name of the directory is Crowdin specific helper text to give\n // context to translators.\n // See https://developer.crowdin.com/api/v2/#operation/api.projects.directories.getMany\n crowdinPayloadArticleDirectory = await this.payload.findByID({\n collection: \"crowdin-article-directories\",\n id:\n document.crowdinArticleDirectory.id ||\n document.crowdinArticleDirectory,\n });", "score": 22.228679397110998 }, { "filename": "src/hooks/collections/afterDelete.ts", "retrieved_chunk": "import { CollectionAfterDeleteHook } from \"payload/types\";\nimport { payloadCrowdinSyncFilesApi } from \"../../api/payload-crowdin-sync/files\";\nimport { PluginOptions } from \"../../types\";\ninterface CommonArgs {\n pluginOptions: PluginOptions;\n}\ninterface Args extends CommonArgs {}\nexport const getAfterDeleteHook =\n ({ pluginOptions }: Args): CollectionAfterDeleteHook =>\n async ({", "score": 20.12608400167096 }, { "filename": "src/api/connection.ts", "retrieved_chunk": "import crowdin from \"@crowdin/crowdin-api-client\";\nexport const { uploadStorageApi, sourceFilesApi } = new crowdin({\n token: process.env.CROWDIN_API_TOKEN as string,\n});", "score": 19.927872895926633 } ]
typescript
mockCrowdinClient(pluginOptions: PluginOptions) {
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": 38.9618965881897 }, { "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": 29.04128544587607 }, { "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": 24.03276306781009 }, { "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": 20.094233445307587 }, { "filename": "src/lib/wp/wp-api.ts", "retrieved_chunk": " postData.meta = {\n yoast_wpseo_title: post.seoTitle,\n yoast_wpseo_metadesc: post.seoDescription\n }\n return await axios.post(`${getApiUrl(domain)}/posts`, postData, authenticate(username, password))\n}\nexport async function updatePost (wp : Wordpress, slug: string, newContent : Post, publishDate : string) {\n const { domain, username, password } = wp\n const apiUrl = getApiUrl(domain)\n const response = await axios.get(`${apiUrl}/posts?slug=${slug}`, authenticate(username, password))", "score": 18.48819308792851 } ]
typescript
const categories = await getCategories(domainFound) console.log(categories) } else {
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": 37.78515246868089 }, { "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": 21.67166255589732 }, { "filename": "src/utilities/index.ts", "retrieved_chunk": "}: {\n fields: Field[];\n type?: \"json\" | \"html\";\n localizedParent?: boolean;\n}): boolean => {\n return !isEmpty(getLocalizedFields({ fields, type, localizedParent }));\n};\nexport const fieldChanged = (\n previousValue: string | object | undefined,\n value: string | object | undefined,", "score": 20.64259452733324 }, { "filename": "src/api/payload-crowdin-sync/files.ts", "retrieved_chunk": " document: any;\n global?: boolean;\n}\ninterface IupdateOrCreateFile {\n name: string;\n value: string | object;\n fileType: \"html\" | \"json\";\n articleDirectory: any;\n}\ninterface IcreateOrUpdateFile {", "score": 20.017980638535832 }, { "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": 18.092908376968886 } ]
typescript
payloadCrowdinSyncFilesApi; // our wrapper for file operations projectId: number;
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": " // 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": 45.78748626138197 }, { "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": 34.79435657979614 }, { "filename": "src/lib/prompts.ts", "retrieved_chunk": "'\"seoDescription : \"\" // Max 155 characters }'\nconst INFORMATIVE_INTRO_PROMPT = 'Compose the introduction for this blog post topic, without using phrases such as, \"In this article,...\" to introduce the subject.' +\n '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.' +\n 'Do not add a heading. Your responses should be in the markdown format. Do not add the title in the beginning of the introduction.'\nconst CAPTIVATING_INTO_PROMPT = 'Compose a captivating introduction for this blog post topic, without using phrases such as, \"In this article,...\" to introduce the subject.' +\n '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.' +\n 'Your introduction should entice readers to continue reading the article and learn more about the subject presented.' +\n ' Do not add a heading. Your responses should be in the markdown format. Do not add the title in the beginning of the introduction.'\n// ------------------------------------------------------\n// PROMPTS FOR THE INTERACTIVE / AUTO MODE", "score": 31.988449049138957 }, { "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": 31.799797153370722 }, { "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": 31.69575810749283 } ]
typescript
return extractPostOutlineFromCodeBlock(this.chatParentMessage.text) }
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": " 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": 30.885719906760684 }, { "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": 27.004459283079925 }, { "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": 26.491187962631535 }, { "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": 25.726784668489554 }, { "filename": "src/plugin.ts", "retrieved_chunk": " *\n **/\nexport const crowdinSync =\n (pluginOptions: PluginOptions) =>\n (config: Config): Config => {\n const initFunctions: (() => void)[] = [];\n // schema validation\n const schema = Joi.object({\n projectId: Joi.number().required(),\n directoryId: Joi.number(),", "score": 24.259371490276454 } ]
typescript
: PluginOptions["sourceLocale"];
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": 31.38570615282518 }, { "filename": "src/post.ts", "retrieved_chunk": " */\nexport class PostGenerator {\n private helper : GeneratorHelperInterface\n public constructor (helper : GeneratorHelperInterface) {\n this.helper = helper\n }\n public async generate () : Promise<Post> {\n return this.helper.isCustom() ? await this.customGenerate() : await this.autoGenerate()\n }\n /**", "score": 28.02847150801038 }, { "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": 27.602780926752672 }, { "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": 25.420769287597594 }, { "filename": "src/lib/prompts.ts", "retrieved_chunk": "// ------------------------------------------------------\nexport function getAutoSystemPrompt (postPrompt : PostPrompt) {\n 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 + '\".' +\n 'Do not add a paragraph summarizing your response/explanation at the end of your answers.'\n}\nexport function getPromptForIntentAudience (postPrompt : PostPrompt) {\n return 'For a post based on the topic : ' + postPrompt.topic + ', describe the ideal audience and intent for this topic.' +\n 'Write maximum 3 statements for the audience and also 3 statements for the intent.' +\n 'Your response should be only the following object in json format : ' +\n '{\"audience\" : \"\", \"intent\": \"\"}'", "score": 24.802634039193975 } ]
typescript
prompts = extractPrompts(this.postPrompt.templateContent) }
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/translations.ts", "retrieved_chunk": " (col: GlobalConfig) => col.slug === collection\n );\n } else {\n collectionConfig = this.payload.config.collections.find(\n (col: CollectionConfig) => col.slug === collection\n );\n }\n if (!collectionConfig)\n throw new Error(`Collection ${collection} not found in payload config`);\n return collectionConfig;", "score": 28.281494104899224 }, { "filename": "src/utilities/tests/inline-snapshots/collections/shared/heroField.ts", "retrieved_chunk": " options.image && {\n name: \"image\",\n type: \"upload\",\n relationTo: \"media\",\n },\n ].filter(Boolean),\n };\n return config;\n};", "score": 19.31761521785078 }, { "filename": "src/api/payload-crowdin-sync/translations.ts", "retrieved_chunk": " getCollectionConfig(\n collection: string,\n global: boolean\n ): CollectionConfig | GlobalConfig {\n let collectionConfig:\n | SanitizedGlobalConfig\n | SanitizedCollectionConfig\n | undefined;\n if (global) {\n collectionConfig = this.payload.config.globals.find(", "score": 15.887492084636147 }, { "filename": "src/utilities/index.ts", "retrieved_chunk": " const description = get(field, \"admin.description\", \"\");\n if (description.includes(\"Not sent to Crowdin. Localize in the CMS.\")) {\n return true;\n }\n return false;\n};\nexport const containsLocalizedFields = ({\n fields,\n type,\n localizedParent,", "score": 12.406238239491337 }, { "filename": "src/utilities/tests/inline-snapshots/collections/shared/heroField.ts", "retrieved_chunk": "interface IHeroFieldOptions {\n image?: boolean;\n badge?: boolean;\n}\nconst defaultOptions = { image: false, badge: false };\nexport const heroField = (options: IHeroFieldOptions = {}): any => {\n options = { ...defaultOptions, ...options };\n const config = {\n name: \"hero\",\n type: \"group\",", "score": 11.638805986060355 } ]
typescript
containsLocalizedFields({ fields: existingCollection.fields })) {
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/utils/messages.ts", "retrieved_chunk": "export const ListNotFound = (listId: string) =>\n `List not found!, make sure this '${listId}' id exists!`;", "score": 15.749768084038386 }, { "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": 14.667800994696007 }, { "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": 11.600923386197618 }, { "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": 11.235807880391766 }, { "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": 8.948400854043102 } ]
typescript
task: Task, @Param('id') listId: string): string {
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": " 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": 26.318680726935305 }, { "filename": "src/lib/prompts.ts", "retrieved_chunk": "// ------------------------------------------------------\nexport function getAutoSystemPrompt (postPrompt : PostPrompt) {\n 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 + '\".' +\n 'Do not add a paragraph summarizing your response/explanation at the end of your answers.'\n}\nexport function getPromptForIntentAudience (postPrompt : PostPrompt) {\n return 'For a post based on the topic : ' + postPrompt.topic + ', describe the ideal audience and intent for this topic.' +\n 'Write maximum 3 statements for the audience and also 3 statements for the intent.' +\n 'Your response should be only the following object in json format : ' +\n '{\"audience\" : \"\", \"intent\": \"\"}'", "score": 22.62413525363561 }, { "filename": "src/lib/extractor.ts", "retrieved_chunk": "}\nexport function extractAudienceIntentInfo (text : string) : AudienceIntentInfo {\n return JSON5.parse(extractCodeBlock(text))\n}", "score": 22.59126410225047 }, { "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": 21.546246829719653 }, { "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": 19.701435676976132 } ]
typescript
return extractCodeBlock(response.text) }
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/CrowdinArticleDirectories.ts", "retrieved_chunk": " type: \"number\",\n },\n {\n name: \"directoryId\",\n type: \"number\",\n },\n ],\n};\nexport default CrowdinArticleDirectories;", "score": 15.315333157203327 }, { "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": 11.974771501203046 }, { "filename": "src/collections/CrowdinFiles.ts", "retrieved_chunk": " ],\n },\n ],\n};\nexport default CrowdinFiles;", "score": 9.40719570347037 }, { "filename": "src/collections/CrowdinCollectionDirectories.ts", "retrieved_chunk": " name: \"projectId\",\n type: \"number\",\n },\n {\n name: \"directoryId\",\n type: \"number\",\n },\n ],\n};\nexport default CrowdinCollectionDirectories;", "score": 7.210659179790572 }, { "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": 5.581570639939699 } ]
typescript
...CrowdinArticleDirectories, fields: [ ...(CrowdinArticleDirectories.fields || []), {
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": 19.405231679497305 }, { "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": 18.043415256854306 }, { "filename": "src/lib/wp/wp-api.ts", "retrieved_chunk": "}\nfunction authenticate (username : string, password : string) {\n const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')\n return {\n headers: {\n Authorization: `Basic ${token}`,\n 'Content-Type': 'application/json'\n }\n }\n};", "score": 18.003296196959223 }, { "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": 15.023620341182102 }, { "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": 14.647599673290028 } ]
typescript
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": " 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": 28.147092931206334 }, { "filename": "src/bin/command/wp.ts", "retrieved_chunk": " wpCommand\n .command('info <domain|index>')\n .description('Info on a Wordpress site')\n .action(async (domain) => {\n const domainFound = await getWordpress(domain)\n if (domainFound) {\n console.log('\\nWordpress site found :\\n')\n console.log(`\\ndomain : ${domainFound.domain}`)\n console.log(`username : ${domainFound.username}`)\n console.log(`password : ${domainFound.password}\\n`)", "score": 27.179240876439476 }, { "filename": "src/bin/command/wp.ts", "retrieved_chunk": " console.log(`\\nContent has been updated on https://${domainFound.domain}${slug}\\n\\n`)\n })\n}\nasync function getAllWp () {\n const wpSites = await getAllWordpress()\n if (wpSites.length === 0) {\n console.log('\\nNo Wordpress site found\\n')\n return\n }\n console.log('\\nWordpress sites :\\n')", "score": 26.823328509469974 }, { "filename": "src/bin/command/wp.ts", "retrieved_chunk": " .command('categories <domain|index>')\n .description('Fetch the categories for one Wordpress site')\n .action(async (domain) => {\n const domainFound = await getWordpress(domain)\n if (domainFound) {\n const categories = await getCategories(domainFound)\n console.log(categories)\n } else {\n console.log(`\\nWordpress site ${domain} not found\\n`)\n }", "score": 22.761762427261335 }, { "filename": "src/bin/command/wp.ts", "retrieved_chunk": " console.log(wpSites.map((wp, index) => `${index + 1}. ${wp.domain} (${wp.username})`).join('\\n') + '\\n')\n}\nasync function addWpSite (site) {\n const [domain, username, password] = site.split(':')\n if (!domain || !username || !password) {\n console.error('Invalid format for adding a new wp site. Expected : domain:username:password')\n return\n }\n await addWordpress({ domain, username, password })\n console.log(`\\nWordpress site ${domain} added successfully\\n`)", "score": 21.719119875028948 } ]
typescript
return extractJsonArray(response.text) }
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": 28.435046168626336 }, { "filename": "src/collections/CrowdinFiles.ts", "retrieved_chunk": " },\n fields: [\n /* Crowdin field */\n {\n name: \"title\",\n type: \"text\",\n },\n /* Internal fields */\n {\n name: \"field\",", "score": 24.951462048037396 }, { "filename": "src/utilities/tests/inline-snapshots/collections/shared/heroField.ts", "retrieved_chunk": " options.image && {\n name: \"image\",\n type: \"upload\",\n relationTo: \"media\",\n },\n ].filter(Boolean),\n };\n return config;\n};", "score": 24.734621427253362 }, { "filename": "src/utilities/isLocalizedField.spec.ts", "retrieved_chunk": " expect(isLocalizedField(field)).toBe(false);\n });\n});", "score": 23.544784324063336 }, { "filename": "src/utilities/isLocalizedField.spec.ts", "retrieved_chunk": "import { Field } from \"payload/types\";\nimport { isLocalizedField } from \".\";\ndescribe(\"fn: isLocalizedField\", () => {\n it(\"excludes a select localized field\", () => {\n const field: Field = {\n name: \"select\",\n type: \"select\",\n localized: true,\n options: [\"one\", \"two\"],\n };", "score": 23.133180032802475 } ]
typescript
? fieldCrowdinFileType(field as FieldWithName) === type : true;
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/utils/messages.ts", "retrieved_chunk": "export const ListNotFound = (listId: string) =>\n `List not found!, make sure this '${listId}' id exists!`;", "score": 15.749768084038386 }, { "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": 14.667800994696007 }, { "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": 11.600923386197618 }, { "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": 11.235807880391766 }, { "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": 8.948400854043102 } ]
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/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": 32.147539440874134 }, { "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": 27.209256444744707 }, { "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": 27.127062619510138 }, { "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": 23.358758800716526 }, { "filename": "src/collections/CrowdinCollectionDirectories.ts", "retrieved_chunk": " name: \"projectId\",\n type: \"number\",\n },\n {\n name: \"directoryId\",\n type: \"number\",\n },\n ],\n};\nexport default CrowdinCollectionDirectories;", "score": 22.473259958081133 } ]
typescript
localeMap: PluginOptions["localeMap"];
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": 100.16035212323686 }, { "filename": "src/api/connection.ts", "retrieved_chunk": "import crowdin from \"@crowdin/crowdin-api-client\";\nexport const { uploadStorageApi, sourceFilesApi } = new crowdin({\n token: process.env.CROWDIN_API_TOKEN as string,\n});", "score": 55.49222491626528 }, { "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": 54.09650007298494 }, { "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": 41.306530835694005 }, { "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": 37.570640703729474 } ]
typescript
mockCrowdinClient(pluginOptions) as any) : sourceFilesApi;
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": 19.405231679497305 }, { "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": 18.043415256854306 }, { "filename": "src/lib/wp/wp-api.ts", "retrieved_chunk": "}\nfunction authenticate (username : string, password : string) {\n const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')\n return {\n headers: {\n Authorization: `Basic ${token}`,\n 'Content-Type': 'application/json'\n }\n }\n};", "score": 18.003296196959223 }, { "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": 15.773843343624023 }, { "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": 15.196811446398847 } ]
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/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": 26.13679558556015 }, { "filename": "src/lib/prompts.ts", "retrieved_chunk": "'\"seoDescription : \"\" // Max 155 characters }'\nconst INFORMATIVE_INTRO_PROMPT = 'Compose the introduction for this blog post topic, without using phrases such as, \"In this article,...\" to introduce the subject.' +\n '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.' +\n 'Do not add a heading. Your responses should be in the markdown format. Do not add the title in the beginning of the introduction.'\nconst CAPTIVATING_INTO_PROMPT = 'Compose a captivating introduction for this blog post topic, without using phrases such as, \"In this article,...\" to introduce the subject.' +\n '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.' +\n 'Your introduction should entice readers to continue reading the article and learn more about the subject presented.' +\n ' Do not add a heading. Your responses should be in the markdown format. Do not add the title in the beginning of the introduction.'\n// ------------------------------------------------------\n// PROMPTS FOR THE INTERACTIVE / AUTO MODE", "score": 23.093394297764682 }, { "filename": "src/lib/prompts.ts", "retrieved_chunk": "// ------------------------------------------------------\nexport function getAutoSystemPrompt (postPrompt : PostPrompt) {\n 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 + '\".' +\n 'Do not add a paragraph summarizing your response/explanation at the end of your answers.'\n}\nexport function getPromptForIntentAudience (postPrompt : PostPrompt) {\n return 'For a post based on the topic : ' + postPrompt.topic + ', describe the ideal audience and intent for this topic.' +\n 'Write maximum 3 statements for the audience and also 3 statements for the intent.' +\n 'Your response should be only the following object in json format : ' +\n '{\"audience\" : \"\", \"intent\": \"\"}'", "score": 22.90735706449011 }, { "filename": "src/bin/question/questions.ts", "retrieved_chunk": " {\n type: 'number',\n name: 'presencePenalty',\n message: 'Presence Penalty (-2/2) ?',\n default: 1\n },\n {\n type: 'number',\n name: 'logitBias',\n message: 'Logit bias ?',", "score": 22.39291734997564 }, { "filename": "src/bin/command/post.ts", "retrieved_chunk": " topic: string\n country: string\n generate: boolean // generate the audience and intent\n conclusion: boolean\n tone: string\n temperature: number\n frequencyPenalty: number\n presencePenalty: number\n logitBias: number\n}", "score": 22.15086955027037 } ]
typescript
const encoded = encode(kw) encoded.forEach((element) => {
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/translations.ts", "retrieved_chunk": " (col: GlobalConfig) => col.slug === collection\n );\n } else {\n collectionConfig = this.payload.config.collections.find(\n (col: CollectionConfig) => col.slug === collection\n );\n }\n if (!collectionConfig)\n throw new Error(`Collection ${collection} not found in payload config`);\n return collectionConfig;", "score": 28.281494104899224 }, { "filename": "src/utilities/tests/inline-snapshots/collections/shared/heroField.ts", "retrieved_chunk": " options.image && {\n name: \"image\",\n type: \"upload\",\n relationTo: \"media\",\n },\n ].filter(Boolean),\n };\n return config;\n};", "score": 19.31761521785078 }, { "filename": "src/api/payload-crowdin-sync/translations.ts", "retrieved_chunk": " getCollectionConfig(\n collection: string,\n global: boolean\n ): CollectionConfig | GlobalConfig {\n let collectionConfig:\n | SanitizedGlobalConfig\n | SanitizedCollectionConfig\n | undefined;\n if (global) {\n collectionConfig = this.payload.config.globals.find(", "score": 15.887492084636147 }, { "filename": "src/utilities/index.ts", "retrieved_chunk": " const description = get(field, \"admin.description\", \"\");\n if (description.includes(\"Not sent to Crowdin. Localize in the CMS.\")) {\n return true;\n }\n return false;\n};\nexport const containsLocalizedFields = ({\n fields,\n type,\n localizedParent,", "score": 13.005181053927789 }, { "filename": "src/utilities/tests/inline-snapshots/collections/shared/heroField.ts", "retrieved_chunk": "interface IHeroFieldOptions {\n image?: boolean;\n badge?: boolean;\n}\nconst defaultOptions = { image: false, badge: false };\nexport const heroField = (options: IHeroFieldOptions = {}): any => {\n options = { ...defaultOptions, ...options };\n const config = {\n name: \"hero\",\n type: \"group\",", "score": 12.262951099983184 } ]
typescript
const fields = getFields({
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": 49.32142416078241 }, { "filename": "src/utilities/getLocalizedFields.spec.ts", "retrieved_chunk": " ];\n expect(getLocalizedFields({ fields: global.fields, type: \"html\" })).toEqual(\n expected\n );\n });\n it(\"returns nested json fields in a group inside an array\", () => {\n const linkField: Field = {\n name: \"link\",\n type: \"group\",\n fields: [", "score": 30.598399641509705 }, { "filename": "src/utilities/containsLocalizedFields.spec.ts", "retrieved_chunk": " },\n ];\n expect(containsLocalizedFields({ fields })).toEqual(true);\n });\n it(\"returns nested json fields in a group inside an array\", () => {\n const linkField: Field = {\n name: \"link\",\n type: \"group\",\n fields: [\n {", "score": 28.567187253220034 }, { "filename": "src/utilities/containsLocalizedFields.spec.ts", "retrieved_chunk": " },\n ];\n expect(containsLocalizedFields({ fields })).toEqual(false);\n });\n it(\"returns nested json fields in a group inside an array\", () => {\n const linkField: Field = {\n name: \"link\",\n type: \"group\",\n fields: [\n {", "score": 28.567187253220034 }, { "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": 28.52199208212955 } ]
typescript
fields: getLocalizedFields({ fields: Promos.fields, type: "json" }), }) ).toEqual(expected);
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": " */\nexport class PostGenerator {\n private helper : GeneratorHelperInterface\n public constructor (helper : GeneratorHelperInterface) {\n this.helper = helper\n }\n public async generate () : Promise<Post> {\n return this.helper.isCustom() ? await this.customGenerate() : await this.autoGenerate()\n }\n /**", "score": 35.88396664418557 }, { "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": 34.76304741865344 }, { "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": 34.74162545982399 }, { "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": 33.10482133270216 }, { "filename": "src/post.ts", "retrieved_chunk": " /**\n * Generate a post using the auto mode\n */\n private async autoGenerate () : Promise<Post> {\n await oraPromise(\n this.helper.init(),\n {\n text: ' Init the completion parameters ...'\n }\n )", "score": 29.05574706807926 } ]
typescript
return extractSeoInfo(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/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": 34.35055073551857 }, { "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": 28.838433325225022 }, { "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": 27.7626030609109 }, { "filename": "src/utilities/tests/buildJsonCrowdinObject/group-field-type.spec.ts", "retrieved_chunk": " 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 nested in a group with a localization setting on the group field\", () => {\n const doc = {\n id: \"638641358b1a140462752076\",", "score": 25.71725787607035 }, { "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": 25.619955719457355 } ]
typescript
buildCrowdinJsonObject({ doc, fields })).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": 72.19228915390592 }, { "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": 41.773154756091856 }, { "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": 38.188887462973895 }, { "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": 23.59934588881646 }, { "filename": "src/api/connection.ts", "retrieved_chunk": "import crowdin from \"@crowdin/crowdin-api-client\";\nexport const { uploadStorageApi, sourceFilesApi } = new crowdin({\n token: process.env.CROWDIN_API_TOKEN as string,\n});", "score": 20.662675099495686 } ]
typescript
const 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/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": 24.000672462538265 }, { "filename": "src/lib/extractor.ts", "retrieved_chunk": " },\n required: [\n 'title',\n 'headings',\n 'slug',\n 'seoTitle',\n 'seoDescription'\n ],\n additionalProperties: false,\n definitions: {", "score": 21.602730711145917 }, { "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": 21.025172023721193 }, { "filename": "src/bin/command/post.ts", "retrieved_chunk": " return `\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"UTF-8\">\n <title>${post.seoTitle}</title>\n <meta name=\"description\" content=\"${post.seoDescription}\">\n </head>\n <body>\n <h1>${post.title}</h1>", "score": 20.96131955641381 }, { "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": 19.26246624349835 } ]
typescript
seoInfo.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": " 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": 15.532512949270194 }, { "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": 14.142110402632849 }, { "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": 13.901562135778601 }, { "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": 13.346245454546732 }, { "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": 11.221029228330913 } ]
typescript
this.helper.generateHeadingContents(tableOfContent), {
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": " 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": 45.91515803419891 }, { "filename": "src/api/payload-crowdin-sync/files.ts", "retrieved_chunk": " await this.deleteFile(file);\n }\n await this.deleteArticleDirectory(documentId);\n }\n async deleteArticleDirectory(documentId: string) {\n const crowdinPayloadArticleDirectory = await this.getArticleDirectory(\n documentId\n );\n await this.sourceFilesApi.deleteDirectory(\n this.projectId,", "score": 44.63293437185187 }, { "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": 42.452831728419355 }, { "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": 39.187917837480384 }, { "filename": "src/api/payload-crowdin-sync/files.ts", "retrieved_chunk": " articleDirectory,\n }: IupdateOrCreateFile) {\n const empty = isEmpty(value);\n // Check whether file exists on Crowdin\n let crowdinFile = await this.getFile(name, articleDirectory.id);\n let updatedCrowdinFile;\n if (!empty) {\n if (!crowdinFile) {\n updatedCrowdinFile = await this.createFile({\n name,", "score": 35.83715518977321 } ]
typescript
const file = await this.filesApi.getFile(fieldName, articleDirectory.id);
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": " postData.meta = {\n yoast_wpseo_title: post.seoTitle,\n yoast_wpseo_metadesc: post.seoDescription\n }\n return await axios.post(`${getApiUrl(domain)}/posts`, postData, authenticate(username, password))\n}\nexport async function updatePost (wp : Wordpress, slug: string, newContent : Post, publishDate : string) {\n const { domain, username, password } = wp\n const apiUrl = getApiUrl(domain)\n const response = await axios.get(`${apiUrl}/posts?slug=${slug}`, authenticate(username, password))", "score": 34.889455019968715 }, { "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": 34.150227871542334 }, { "filename": "src/lib/store/types.ts", "retrieved_chunk": "export type Wordpress = {\n domain : string,\n username: string,\n password: string\n}", "score": 34.07000135120545 }, { "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": 29.009454101563414 }, { "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": 28.421050733454997 } ]
typescript
domainFound.username}`) console.log(`password : ${domainFound.password}\n`) } else {
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/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": 24.000672462538265 }, { "filename": "src/lib/extractor.ts", "retrieved_chunk": " },\n required: [\n 'title',\n 'headings',\n 'slug',\n 'seoTitle',\n 'seoDescription'\n ],\n additionalProperties: false,\n definitions: {", "score": 21.602730711145917 }, { "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": 21.025172023721193 }, { "filename": "src/bin/command/post.ts", "retrieved_chunk": " return `\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"UTF-8\">\n <title>${post.seoTitle}</title>\n <meta name=\"description\" content=\"${post.seoDescription}\">\n </head>\n <body>\n <h1>${post.title}</h1>", "score": 20.96131955641381 }, { "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": 19.26246624349835 } ]
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": " }\n async getFilesByDocumentID(documentId: string) {\n const result = await getFilesByDocumentID(documentId, this.payload);\n return result;\n }\n}", "score": 38.63932146469559 }, { "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": 38.22653804180827 }, { "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": 29.37270213523187 }, { "filename": "src/api/payload-crowdin-sync/files.ts", "retrieved_chunk": " await this.deleteFile(file);\n }\n await this.deleteArticleDirectory(documentId);\n }\n async deleteArticleDirectory(documentId: string) {\n const crowdinPayloadArticleDirectory = await this.getArticleDirectory(\n documentId\n );\n await this.sourceFilesApi.deleteDirectory(\n this.projectId,", "score": 29.23091445321287 }, { "filename": "src/api/payload-crowdin-sync/files.ts", "retrieved_chunk": " crowdinPayloadArticleDirectory.originalId\n );\n await this.payload.delete({\n collection: \"crowdin-article-directories\",\n id: crowdinPayloadArticleDirectory.id,\n });\n }\n async getFileByDocumentID(name: string, documentId: string) {\n const result = await getFileByDocumentID(name, documentId, this.payload);\n return result;", "score": 25.58593268399889 } ]
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/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": 24.000672462538265 }, { "filename": "src/lib/extractor.ts", "retrieved_chunk": " },\n required: [\n 'title',\n 'headings',\n 'slug',\n 'seoTitle',\n 'seoDescription'\n ],\n additionalProperties: false,\n definitions: {", "score": 21.602730711145917 }, { "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": 21.025172023721193 }, { "filename": "src/bin/command/post.ts", "retrieved_chunk": " return `\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"UTF-8\">\n <title>${post.seoTitle}</title>\n <meta name=\"description\" content=\"${post.seoDescription}\">\n </head>\n <body>\n <h1>${post.title}</h1>", "score": 20.96131955641381 }, { "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": 19.26246624349835 } ]
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/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": 38.49667957836247 }, { "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": 34.43903816828104 }, { "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": 32.783422413027836 }, { "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": 29.333747942595195 }, { "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": 28.772154089245326 } ]
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": 32.19125608547412 }, { "filename": "src/utility.ts", "retrieved_chunk": "import { ok } from \"assert\";\nimport { join } from \"path\";\nimport { v4 as uuid } from \"uuid\";\nexport function createTempPath(): string {\n return join(getTempDirectory(), uuid());\n}\nexport function getTempDirectory(): string {\n const tempDirectory = process.env[\"RUNNER_TEMP\"] || \"\";\n ok(tempDirectory, \"Expected RUNNER_TEMP to be defined\");\n return tempDirectory;", "score": 31.678604329595696 }, { "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": 17.90798324850846 }, { "filename": "src/config.ts", "retrieved_chunk": "import { ok } from \"assert\";\nimport * as core from \"@actions/core\";\nimport { join } from \"path\";\nimport { createTempPath } from \"./utility\";\nexport type Config = {\n commitBranch: string;\n commitMessage: string;\n commitUserEmail: string;\n commitUserName: string;\n fullPath: string;", "score": 11.071886930426679 }, { "filename": "src/templates.ts", "retrieved_chunk": "import * as core from \"@actions/core\";\nimport * as glob from \"@actions/glob\";\nimport { open, readFile, writeFile } from \"fs/promises\";\nimport Handlebars from \"handlebars\";\nimport { dirname, join, relative } from \"path\";\nimport { mkdirP } from \"@actions/io\";\nimport { Config } from \"./config\";\nexport async function templateFiles(config: Config): Promise<void> {\n const templateGlob = await glob.create(`${config.syncPath}/templates/*`, {\n matchDirectories: false,", "score": 9.034140616591463 } ]
typescript
(config.prToken, "Expected PR_TOKEN to be defined");
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": " }),\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": 9.113233949286155 }, { "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": 5.710358198529345 }, { "filename": "src/templates.test.ts", "retrieved_chunk": " path: string;\n prAssignee?: string;\n prBody: string;\n prEnabled: boolean;\n prLabels: string[];\n prReviewUsers: string[];\n prTitle: string;\n prToken?: string;\n syncAuth?: string;\n syncPath: string;", "score": 5.476590886659147 }, { "filename": "src/config.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": 5.476590886659147 }, { "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": 4.879271981877299 } ]
typescript
body: config.prBody, head: config.commitBranch, maintainer_can_modify: true, title: config.prTitle, });
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": 25.83416559877766 }, { "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": 22.992028605873408 }, { "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": 18.13328116040747 }, { "filename": "src/lib/post-helpers.ts", "retrieved_chunk": " }\n async init () {\n if (this.isCustom()) {\n if (this.postPrompt.debug) {\n console.log(`Use template : ${this.postPrompt.templateFile}`)\n }\n this.postPrompt.templateContent = await this.readTemplate()\n this.postPrompt.prompts = extractPrompts(this.postPrompt.templateContent)\n }\n const systemMessage = this.isCustom() ? getCustomSystemPrompt(this.postPrompt) : getAutoSystemPrompt(this.postPrompt)", "score": 16.747704943253066 }, { "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": 16.155261492750917 } ]
typescript
replaceAllPrompts(this.helper.getPrompt().templateContent, promptContents) const seoInfo = await oraPromise( this.helper.generateSeoInfo(), {
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": " 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": 23.57892236802666 }, { "filename": "src/lib/extractor.ts", "retrieved_chunk": "}\nexport function extractAudienceIntentInfo (text : string) : AudienceIntentInfo {\n return JSON5.parse(extractCodeBlock(text))\n}", "score": 22.59126410225047 }, { "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": 19.701435676976132 }, { "filename": "src/lib/prompts.ts", "retrieved_chunk": "// ------------------------------------------------------\nexport function getAutoSystemPrompt (postPrompt : PostPrompt) {\n 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 + '\".' +\n 'Do not add a paragraph summarizing your response/explanation at the end of your answers.'\n}\nexport function getPromptForIntentAudience (postPrompt : PostPrompt) {\n return 'For a post based on the topic : ' + postPrompt.topic + ', describe the ideal audience and intent for this topic.' +\n 'Write maximum 3 statements for the audience and also 3 statements for the intent.' +\n 'Your response should be only the following object in json format : ' +\n '{\"audience\" : \"\", \"intent\": \"\"}'", "score": 18.058435187802907 }, { "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": 16.568590948069026 } ]
typescript
extractCodeBlock(response.text) }
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": " },\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": 70.75201502116735 }, { "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": 64.16640234883718 }, { "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": 63.63179572390188 }, { "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": 53.03040560232239 }, { "filename": "src/api/payload-crowdin-sync/translations.ts", "retrieved_chunk": " doc = await this.payload.findGlobal({\n slug: collection,\n locale: this.sourceLocale,\n });\n } else {\n doc = await this.payload.findByID({\n collection: collection,\n id: documentId,\n locale: this.sourceLocale,\n });", "score": 45.84317763928882 } ]
typescript
await this.deleteFile(file);
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": " ...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": 16.287972326316215 }, { "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": 15.51447491469556 }, { "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": 11.349054374116736 }, { "filename": "src/index.ts", "retrieved_chunk": "import * as core from \"@actions/core\";\nimport {\n configureRepository,\n cloneRepository,\n commitChanges,\n createPr,\n} from \"./git\";\nimport { getConfig } from \"./config\";\nimport { templateFiles } from \"./templates\";\nimport { runScripts } from \"./scripts\";", "score": 11.29230929609856 }, { "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": 9.309615067988092 } ]
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": 27.693929143306484 }, { "filename": "src/lib/errors.ts", "retrieved_chunk": "export class NoApiKeyError extends Error {\n constructor () {\n super()\n this.name = 'NoApiKeyError'\n }\n}", "score": 23.49441530430423 }, { "filename": "src/lib/extractor.ts", "retrieved_chunk": "import JSON5 from 'json5'\nimport { validate } from 'jsonschema'\nimport { AudienceIntentInfo, PostOutline, SeoInfo } from '../types'\nexport class PostOutlineValidationError extends Error {\n constructor (message: string, public readonly errors: any[]) {\n super(message)\n }\n}\nconst schemaValidiation = {\n $schema: 'http://json-schema.org/draft-07/schema#',", "score": 19.863576354119388 }, { "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": 17.079281320166157 }, { "filename": "src/lib/post-helpers.ts", "retrieved_chunk": " private completionParams : CompletionParams\n private totalTokens : TotalTokens = {\n promptTokens: 0,\n completionTokens: 0,\n total: 0\n }\n // -----------------------------------------------\n // CONSTRUCTOR AND INITIALIZATION\n // -----------------------------------------------\n public constructor (postPrompt : PostPrompt) {", "score": 15.736961707696898 } ]
typescript
(new ChatGptHelper(postPrompt)) }
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": 72.19228915390592 }, { "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": 41.773154756091856 }, { "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": 38.188887462973895 }, { "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": 23.59934588881646 }, { "filename": "src/api/connection.ts", "retrieved_chunk": "import crowdin from \"@crowdin/crowdin-api-client\";\nexport const { uploadStorageApi, sourceFilesApi } = new crowdin({\n token: process.env.CROWDIN_API_TOKEN as string,\n});", "score": 20.662675099495686 } ]
typescript
localizedFields: Field[] = getLocalizedFields({
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": " postData.meta = {\n yoast_wpseo_title: post.seoTitle,\n yoast_wpseo_metadesc: post.seoDescription\n }\n return await axios.post(`${getApiUrl(domain)}/posts`, postData, authenticate(username, password))\n}\nexport async function updatePost (wp : Wordpress, slug: string, newContent : Post, publishDate : string) {\n const { domain, username, password } = wp\n const apiUrl = getApiUrl(domain)\n const response = await axios.get(`${apiUrl}/posts?slug=${slug}`, authenticate(username, password))", "score": 34.889455019968715 }, { "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": 34.150227871542334 }, { "filename": "src/lib/store/types.ts", "retrieved_chunk": "export type Wordpress = {\n domain : string,\n username: string,\n password: string\n}", "score": 34.07000135120545 }, { "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": 29.009454101563414 }, { "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": 28.421050733454997 } ]
typescript
password : ${domainFound.password}\n`) } else {
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": " 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": 31.369425957049422 }, { "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": 30.885719906760684 }, { "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": 30.733088247793717 }, { "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": 26.491187962631535 }, { "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": 24.945259281258675 } ]
typescript
sourceLocale: PluginOptions["sourceLocale"];
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": 68.82283463822614 }, { "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": 49.401608988342296 }, { "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": 37.685577601357046 }, { "filename": "src/lib/post-helpers.ts", "retrieved_chunk": " frequency_penalty: this.postPrompt.frequencyPenalty ?? 0,\n presence_penalty: this.postPrompt.presencePenalty ?? 1\n }\n if (this.postPrompt.logitBias) {\n const mainKwWords = await this.generateMainKeyword()\n // set the logit bias in order to force the model to minimize the usage of the main keyword\n const logitBiais: Record<number, number> = {}\n mainKwWords.forEach((kw) => {\n const encoded = encode(kw)\n encoded.forEach((element) => {", "score": 35.3385229316729 }, { "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": 34.66743392765959 } ]
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/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": 10.044552052280292 }, { "filename": "src/templates.test.ts", "retrieved_chunk": " const data = await readFile(path, \"utf8\");\n expect(data).toEqual(\n `{\\n \"keyOne\": true,\\n \"keyTwo\": \"valueTwo\",\\n \"keyThree\": \"valueThree\"\\n}\\n`,\n );\n });\n});", "score": 7.411970606089005 }, { "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": 5.773394127108711 }, { "filename": "src/templates.test.ts", "retrieved_chunk": " path: string;\n prAssignee?: string;\n prBody: string;\n prEnabled: boolean;\n prLabels: string[];\n prReviewUsers: string[];\n prTitle: string;\n prToken?: string;\n syncAuth?: string;\n syncPath: string;", "score": 5.476590886659147 }, { "filename": "src/config.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": 5.476590886659147 } ]
typescript
reviewers: config.prReviewUsers, });
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": " 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": 36.0105770211592 }, { "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": 32.885673900677695 }, { "filename": "src/api/payload-crowdin-sync/files.ts", "retrieved_chunk": " await this.deleteFile(file);\n }\n await this.deleteArticleDirectory(documentId);\n }\n async deleteArticleDirectory(documentId: string) {\n const crowdinPayloadArticleDirectory = await this.getArticleDirectory(\n documentId\n );\n await this.sourceFilesApi.deleteDirectory(\n this.projectId,", "score": 30.984699933642403 }, { "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": 27.80291538375058 }, { "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": 27.31526564413526 } ]
typescript
= await this.filesApi.getArticleDirectory( documentId );
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/utils/messages.ts", "retrieved_chunk": "export const ListNotFound = (listId: string) =>\n `List not found!, make sure this '${listId}' id exists!`;", "score": 18.129877689856716 }, { "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": 11.589943122515042 }, { "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": 11.093235948827635 }, { "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": 8.905331455064239 }, { "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": 8.170024328953547 } ]
typescript
.appService.RemoveList(listId);
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": 94.00798499973267 }, { "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": 52.47828689430215 }, { "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": 51.44687914845274 }, { "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": 41.58488157947414 }, { "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": 37.849093991234 } ]
typescript
(mockCrowdinClient(pluginOptions) as any) : translationsApi;
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": 27.693929143306484 }, { "filename": "src/lib/errors.ts", "retrieved_chunk": "export class NoApiKeyError extends Error {\n constructor () {\n super()\n this.name = 'NoApiKeyError'\n }\n}", "score": 23.49441530430423 }, { "filename": "src/lib/extractor.ts", "retrieved_chunk": "import JSON5 from 'json5'\nimport { validate } from 'jsonschema'\nimport { AudienceIntentInfo, PostOutline, SeoInfo } from '../types'\nexport class PostOutlineValidationError extends Error {\n constructor (message: string, public readonly errors: any[]) {\n super(message)\n }\n}\nconst schemaValidiation = {\n $schema: 'http://json-schema.org/draft-07/schema#',", "score": 19.863576354119388 }, { "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": 17.079281320166157 }, { "filename": "src/lib/post-helpers.ts", "retrieved_chunk": " private completionParams : CompletionParams\n private totalTokens : TotalTokens = {\n promptTokens: 0,\n completionTokens: 0,\n total: 0\n }\n // -----------------------------------------------\n // CONSTRUCTOR AND INITIALIZATION\n // -----------------------------------------------\n public constructor (postPrompt : PostPrompt) {", "score": 15.736961707696898 } ]
typescript
super(new ChatGptHelper(postPrompt)) }
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": 33.82013874598445 }, { "filename": "src/post.ts", "retrieved_chunk": " */\nexport class PostGenerator {\n private helper : GeneratorHelperInterface\n public constructor (helper : GeneratorHelperInterface) {\n this.helper = helper\n }\n public async generate () : Promise<Post> {\n return this.helper.isCustom() ? await this.customGenerate() : await this.autoGenerate()\n }\n /**", "score": 32.031181537463304 }, { "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": 28.496099101499194 }, { "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": 28.242187978755062 }, { "filename": "src/lib/prompts.ts", "retrieved_chunk": "// ------------------------------------------------------\nexport function getAutoSystemPrompt (postPrompt : PostPrompt) {\n 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 + '\".' +\n 'Do not add a paragraph summarizing your response/explanation at the end of your answers.'\n}\nexport function getPromptForIntentAudience (postPrompt : PostPrompt) {\n return 'For a post based on the topic : ' + postPrompt.topic + ', describe the ideal audience and intent for this topic.' +\n 'Write maximum 3 statements for the audience and also 3 statements for the intent.' +\n 'Your response should be only the following object in json format : ' +\n '{\"audience\" : \"\", \"intent\": \"\"}'", "score": 26.5130079894993 } ]
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/utils/messages.ts", "retrieved_chunk": "export const ListNotFound = (listId: string) =>\n `List not found!, make sure this '${listId}' id exists!`;", "score": 17.255678844922667 }, { "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": 15.768627293013365 }, { "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": 15.160284225229983 }, { "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": 13.055162339518875 }, { "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": 8.170024328953547 } ]
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/utils/messages.ts", "retrieved_chunk": "export const ListNotFound = (listId: string) =>\n `List not found!, make sure this '${listId}' id exists!`;", "score": 9.325102671384002 }, { "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": 8.53251940037979 }, { "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": 7.5897749958834995 }, { "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": 5.844646434862972 }, { "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": 4.474200427021551 } ]
typescript
appService.UpdateListName(listId, newName);
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": 22.98916841453483 }, { "filename": "src/bin/question/questions.ts", "retrieved_chunk": " default: 1\n }\n]\nexport async function askQuestions () {\n return inquirer.prompt(questions)\n}\nexport async function askCustomQuestions () {\n return inquirer.prompt(customQuestions)\n}", "score": 22.09133393676744 }, { "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": 20.604441316078407 }, { "filename": "src/lib/post-helpers.ts", "retrieved_chunk": " }\n return extractPostOutlineFromCodeBlock(this.chatParentMessage.text)\n }\n async generateAudienceIntent () {\n const prompt = getPromptForAudienceIntent(this.postPrompt)\n if (this.postPrompt.debug) {\n console.log('---------- PROMPT AUDIENCE INTENT ----------')\n console.log(prompt)\n }\n const response = await this.sendRequest(prompt)", "score": 19.261501125477096 }, { "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": 18.084749271700876 } ]
typescript
!postPrompt.tone) || postPrompt.tone === 'informative' ? INFORMATIVE_INTRO_PROMPT : CAPTIVATING_INTO_PROMPT }
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": 18.875812404448652 }, { "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": 14.695062223356196 }, { "filename": "src/bin/command/wp.ts", "retrieved_chunk": " console.log(`\\nContent has been updated on https://${domainFound.domain}${slug}\\n\\n`)\n })\n}\nasync function getAllWp () {\n const wpSites = await getAllWordpress()\n if (wpSites.length === 0) {\n console.log('\\nNo Wordpress site found\\n')\n return\n }\n console.log('\\nWordpress sites :\\n')", "score": 14.202879903564504 }, { "filename": "src/lib/post-helpers.ts", "retrieved_chunk": " }\n return extractPostOutlineFromCodeBlock(this.chatParentMessage.text)\n }\n async generateAudienceIntent () {\n const prompt = getPromptForAudienceIntent(this.postPrompt)\n if (this.postPrompt.debug) {\n console.log('---------- PROMPT AUDIENCE INTENT ----------')\n console.log(prompt)\n }\n const response = await this.sendRequest(prompt)", "score": 13.136170638839385 }, { "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": 12.635591738116098 } ]
typescript
string) : PostOutline {
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": " const requiredFieldSlugs = getFieldSlugs(\n getLocalizedRequiredFields(collectionConfig)\n );\n if (requiredFieldSlugs.length > 0) {\n const currentTranslations = await this.getCurrentDocumentTranslation({\n doc: doc,\n collection: collection,\n locale: locale,\n global,\n });", "score": 42.92515206186775 }, { "filename": "src/api/payload-crowdin-sync/translations.ts", "retrieved_chunk": " });\n report[locale].changed = !deepEqual(\n report[locale].currentTranslations,\n report[locale].latestTranslations\n );\n if (report[locale].changed && !dryRun) {\n if (global) {\n try {\n await this.payload.updateGlobal({\n slug: collection,", "score": 38.11944723407458 }, { "filename": "src/api/payload-crowdin-sync/translations.ts", "retrieved_chunk": " }\n const report: { [key: string]: any } = {};\n for (const locale of Object.keys(this.localeMap)) {\n if (excludeLocales.includes(locale)) {\n continue;\n }\n report[locale] = {};\n report[locale].currentTranslations =\n await this.getCurrentDocumentTranslation({\n doc: doc,", "score": 36.984242916481904 }, { "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": 35.78036087787366 }, { "filename": "src/api/payload-crowdin-sync/translations.ts", "retrieved_chunk": " collection: collection,\n locale: locale,\n global,\n });\n report[locale].latestTranslations =\n await this.getLatestDocumentTranslation({\n collection: collection,\n doc: doc,\n locale: locale,\n global,", "score": 35.234389413428794 } ]
typescript
(!req.locale || req.locale !== pluginOptions.sourceLocale) {
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": 36.43616029812196 }, { "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": 22.67871517404388 }, { "filename": "src/engine/ref.ts", "retrieved_chunk": " };\n}\nexport function getRefContentRange(subpath: RefSubpath, metadata: CachedMetadata): RefRange | null {\n const range: RefRange = {\n start: 0,\n startLineOffset: 0,\n end: undefined,\n };\n const { start, end } = subpath;\n if (start.type === \"begin\") {", "score": 19.93319818330546 }, { "filename": "src/engine/workspace.ts", "retrieved_chunk": " const { dir: vaultDir } = parsePath(sourcePath);\n const vault = this.findVaultByParentPath(vaultDir);\n if (!vault) return null;\n const { path, subpath } = parseLinktext(link);\n const target = this.app.metadataCache.getFirstLinkpathDest(path, sourcePath);\n if (target && target.extension !== \"md\")\n return {\n type: \"file\",\n file: target,\n };", "score": 18.09732400662699 }, { "filename": "src/engine/workspace.ts", "retrieved_chunk": " const vault = this.vaultList.find(({ config }) => config.name === vaultName);\n return {\n type: \"maybe-note\",\n vaultName: vaultName ?? \"\",\n vault,\n note: path ? vault?.tree?.getFromFileName(path) : undefined,\n path: path ?? \"\",\n subpath: subpath ? parseRefSubpath(subpath) : undefined,\n };\n }", "score": 18.023227642753973 } ]
typescript
: anchorToLinkSubpath( this.ref.subpath.start, this.app.metadataCache.getFileCache(this.file)?.headings ), };
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/custom-resolver/link-ref-clickbale.ts", "retrieved_chunk": "import { EditorView, PluginValue } from \"@codemirror/view\";\nimport { Editor, editorInfoField } from \"obsidian\";\ntype GetClickableTokenType = Required<Editor>[\"getClickableTokenAt\"];\nexport class LinkRefClickbale implements PluginValue {\n static createClickableTokenAtWrapper(original: GetClickableTokenType): GetClickableTokenType {\n return function (this: Editor, ...args) {\n const result: ReturnType<GetClickableTokenType> = original.call(this, ...args);\n if (result && result.type === \"internal-link\") {\n const raw = this.getRange(result.start, result.end);\n const split = raw.split(\"|\", 2);", "score": 58.072810087885095 }, { "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": 56.376180738963924 }, { "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": 56.1073933734548 }, { "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": 54.90611751367281 }, { "filename": "src/custom-resolver/link-ref-clickbale.ts", "retrieved_chunk": " if (split.length === 2) {\n result.text = split[1];\n }\n }\n return result;\n };\n }\n getClickableTokenAtOrig: Editor[\"getClickableTokenAt\"];\n constructor(private view: EditorView) {\n const editor = view.state.field(editorInfoField).editor;", "score": 50.32795344566671 } ]
typescript
const titleText = renderLinkTitle(app, workspace, href, title, ctx.sourcePath);
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/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": 25.25552083214094 }, { "filename": "src/custom-resolver/link-hover.ts", "retrieved_chunk": "import { App, HoverPopover, PagePreviewPlugin, PopoverState } from \"obsidian\";\nimport { DendronWorkspace } from \"src/engine/workspace\";\nimport { NoteRefRenderChild, createRefRenderer } from \"./ref-render\";\nexport function createLinkHoverHandler(\n app: App,\n workspace: DendronWorkspace,\n originalBoundedFunction: PagePreviewPlugin[\"onLinkHover\"]\n): PagePreviewPlugin[\"onLinkHover\"] {\n return (parent, targetEl, link, sourcePath, state) => {\n const ref = workspace.resolveRef(sourcePath, link);", "score": 24.770741944861072 }, { "filename": "src/settings.ts", "retrieved_chunk": " ],\n autoGenerateFrontmatter: true,\n autoReveal: true,\n customResolver: false,\n};\nexport class DendronTreeSettingTab extends PluginSettingTab {\n plugin: DendronTreePlugin;\n constructor(app: App, plugin: DendronTreePlugin) {\n super(app, plugin);\n this.plugin = plugin;", "score": 24.149029865181454 }, { "filename": "src/settings.ts", "retrieved_chunk": " btn.setButtonText(\"Remove\").onClick(async () => {\n this.plugin.settings.vaultList.remove(vault);\n await this.plugin.saveSettings();\n this.display();\n });\n });\n }\n new Setting(containerEl).addButton((btn) => {\n btn.setButtonText(\"Add Vault\").onClick(() => {\n new AddVaultModal(this.app, (config) => {", "score": 19.374068888358405 }, { "filename": "src/settings.ts", "retrieved_chunk": " this.plugin.settings.autoGenerateFrontmatter = value;\n await this.plugin.saveSettings();\n });\n });\n new Setting(containerEl)\n .setName(\"Auto Reveal\")\n .setDesc(\"Automatically reveal active file in Dendron Tree\")\n .addToggle((toggle) => {\n toggle.setValue(this.plugin.settings.autoReveal).onChange(async (value) => {\n this.plugin.settings.autoReveal = value;", "score": 18.490723073011697 } ]
typescript
onLinkHover = createLinkHoverHandler( this.plugin.app, this.workspace, this.originalLinkHover.bind(this.pagePreviewPlugin) );
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": " /**\n * Initialize Crowdin client sourceFilesApi\n */\n const filesApi = new payloadCrowdinSyncFilesApi(pluginOptions, req.payload);\n await filesApi.deleteFilesAndDirectory(`${id}`);\n };", "score": 67.65711642958844 }, { "filename": "src/utilities/getLocalizedFields.spec.ts", "retrieved_chunk": " },\n {\n name: \"crowdinArticleDirectory\",\n type: \"relationship\",\n relationTo: \"crowdin-article-directories\",\n hasMany: false,\n label: \"Crowdin Article Directory\",\n hooks: {},\n access: {},\n admin: {},", "score": 29.744761650473045 }, { "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": 23.891535376671293 }, { "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": 23.799281581560468 }, { "filename": "src/api/payload-crowdin-sync/files.ts", "retrieved_chunk": " // Update not possible. Article name needs to be updated manually on Crowdin.\n // The name of the directory is Crowdin specific helper text to give\n // context to translators.\n // See https://developer.crowdin.com/api/v2/#operation/api.projects.directories.getMany\n crowdinPayloadArticleDirectory = await this.payload.findByID({\n collection: \"crowdin-article-directories\",\n id:\n document.crowdinArticleDirectory.id ||\n document.crowdinArticleDirectory,\n });", "score": 23.33243963352909 } ]
typescript
await filesApi.findOrCreateArticleDirectory({
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": 39.9320619718889 }, { "filename": "src/main.ts", "retrieved_chunk": " menu.addItem((item) => {\n item\n .setIcon(dendronActivityBarName)\n .setTitle(\"Reveal in Dendron Tree\")\n .onClick(() => this.revealFile(file));\n });\n };\n onResolveMetadata = (file: TFile) => {\n const vault = this.workspace.findVaultByParent(file.parent);\n if (vault && vault.onMetadataChanged(file)) {", "score": 34.67175886622742 }, { "filename": "src/main.ts", "retrieved_chunk": " leaf.view.component.focusTo(vault, note);\n }\n }\n async activateView() {\n const leafs = this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON);\n if (leafs.length == 0) {\n const leaf = this.app.workspace.getLeftLeaf(false);\n await leaf.setViewState({\n type: VIEW_TYPE_DENDRON,\n active: true,", "score": 30.75565884029141 }, { "filename": "src/engine/workspace.ts", "retrieved_chunk": " this.vaultList = vaultList.map((config) => {\n return (\n this.vaultList.find(\n (vault) => vault.config.name === config.name && vault.config.path === config.path\n ) ?? new DendronVault(this.app, config)\n );\n });\n for (const vault of this.vaultList) {\n vault.init();\n }", "score": 29.900637097421406 }, { "filename": "src/modal/select-vault.ts", "retrieved_chunk": "import { App, SuggestModal } from \"obsidian\";\nimport { DendronVault } from \"../engine/vault\";\nimport { DendronWorkspace } from \"../engine/workspace\";\nexport class SelectVaultModal extends SuggestModal<DendronVault> {\n constructor(\n app: App,\n private workspace: DendronWorkspace,\n private onSelected: (item: DendronVault) => void\n ) {\n super(app);", "score": 28.912795089507703 } ]
typescript
SelectVaultModal(this.app, this.workspace, doCreate).open();
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/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": 23.493000863017386 }, { "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": 22.375950177897874 }, { "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": 22.310566869686717 }, { "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": 22.036126513580193 }, { "filename": "src/endpoints/globals/reviewFields.ts", "retrieved_chunk": " method: \"get\",\n handler: async (req, res, next) => {\n const articleDirectory = await req.payload.findByID({\n id: req.params.id,\n collection: req.collection?.config.slug as string,\n });\n const global =\n articleDirectory.crowdinCollectionDirectory.collectionSlug === \"globals\";\n const translationsApi = new payloadCrowdinSyncTranslationsApi(\n pluginOptions,", "score": 21.927168678493906 } ]
typescript
filesApi.createOrUpdateFile({
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/modal/lookup.ts", "retrieved_chunk": " return;\n }\n const path = item ? item.note.getPath() : this.inputEl.value;\n const doCreate = async (vault: DendronVault) => {\n const file = await vault.createNote(path);\n return openFile(vault.app, file);\n };\n if (item?.vault) {\n await doCreate(item.vault);\n } else if (this.workspace.vaultList.length == 1) {", "score": 35.97912181021921 }, { "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": 32.67338898168039 }, { "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": 32.411954016408174 }, { "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": 28.519799360349825 }, { "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": 28.28635662337133 } ]
typescript
if (!fronmatter.id) fronmatter.id = generateUUID();
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": 71.77868266225427 }, { "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": 59.97013098357142 }, { "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": 44.7069767849397 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " builder.add(\n link.start,\n link.end,\n Decoration.widget({\n widget,\n })\n );\n }\n this.widgets = currentWidgets;\n return builder.finish();", "score": 41.752858095511016 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": " const links = this.getLinks(view);\n if (links.length === 0) return Decoration.none;\n this.configureLinkVisibility(links, view);\n const builder = new RangeSetBuilder<Decoration>();\n const currentWidgets: LinkWidget[] = [];\n const sourcePath = view.state.field(editorInfoField).file?.path ?? \"\";\n for (const link of links) {\n if (link.showSource) continue;\n const widget = this.getWidget(link, sourcePath);\n currentWidgets.push(widget);", "score": 41.12150766365952 } ]
typescript
NoteRefRenderChild) renderer.loadFile();
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/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": 25.70243011768231 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " this.tree.addFile(file, true).syncMetadata(this.resolveMetadata(file));\n return true;\n }\n onMetadataChanged(file: TFile): boolean {\n if (!this.isNote(file.extension)) return false;\n const note = this.tree.getFromFileName(file.basename);\n if (!note) return false;\n note.syncMetadata(this.resolveMetadata(file));\n return true;\n }", "score": 22.602675597483323 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " const filePath = `${this.config.path}/${baseName}.md`;\n return await this.app.vault.create(filePath, \"\");\n }\n async generateFronmatter(file: TFile) {\n if (!this.isNote(file.extension)) return;\n const note = this.tree.getFromFileName(file.basename);\n if (!note) return false;\n return await this.app.fileManager.processFrontMatter(file, (fronmatter) => {\n if (!fronmatter.id) fronmatter.id = generateUUID();\n if (!fronmatter.title) fronmatter.title = note.title;", "score": 22.51375014699305 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " onFileDeleted(parsed: ParsedPath): boolean {\n if (!this.isNote(parsed.extension)) return false;\n const note = this.tree.deleteByFileName(parsed.basename);\n if (note?.parent) {\n note.syncMetadata(undefined);\n }\n return true;\n }\n}", "score": 20.973582942143615 }, { "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": 19.799349615689767 } ]
typescript
basename, name, extension } = parsePath(path);
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/translations.ts", "retrieved_chunk": " (col: GlobalConfig) => col.slug === collection\n );\n } else {\n collectionConfig = this.payload.config.collections.find(\n (col: CollectionConfig) => col.slug === collection\n );\n }\n if (!collectionConfig)\n throw new Error(`Collection ${collection} not found in payload config`);\n return collectionConfig;", "score": 28.281494104899224 }, { "filename": "src/utilities/tests/inline-snapshots/collections/shared/heroField.ts", "retrieved_chunk": " options.image && {\n name: \"image\",\n type: \"upload\",\n relationTo: \"media\",\n },\n ].filter(Boolean),\n };\n return config;\n};", "score": 19.31761521785078 }, { "filename": "src/api/payload-crowdin-sync/translations.ts", "retrieved_chunk": " getCollectionConfig(\n collection: string,\n global: boolean\n ): CollectionConfig | GlobalConfig {\n let collectionConfig:\n | SanitizedGlobalConfig\n | SanitizedCollectionConfig\n | undefined;\n if (global) {\n collectionConfig = this.payload.config.globals.find(", "score": 15.887492084636147 }, { "filename": "src/utilities/index.ts", "retrieved_chunk": " const description = get(field, \"admin.description\", \"\");\n if (description.includes(\"Not sent to Crowdin. Localize in the CMS.\")) {\n return true;\n }\n return false;\n};\nexport const containsLocalizedFields = ({\n fields,\n type,\n localizedParent,", "score": 12.406238239491337 }, { "filename": "src/utilities/tests/inline-snapshots/collections/shared/heroField.ts", "retrieved_chunk": "interface IHeroFieldOptions {\n image?: boolean;\n badge?: boolean;\n}\nconst defaultOptions = { image: false, badge: false };\nexport const heroField = (options: IHeroFieldOptions = {}): any => {\n options = { ...defaultOptions, ...options };\n const config = {\n name: \"hero\",\n type: \"group\",", "score": 11.638805986060355 } ]
typescript
(containsLocalizedFields({ fields: existingCollection.fields })) {
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/ref-live.ts", "retrieved_chunk": " children: Component[];\n containerEl: HTMLElement;\n hacked?: boolean;\n initDOM(): HTMLElement;\n addChild(c: Component): void;\n applyTitle(container: HTMLElement, title: string): void;\n}\nexport class RefLivePlugin implements PluginValue {\n constructor(public app: App, public workspace: DendronWorkspace) {}\n update(update: ViewUpdate) {", "score": 27.73825268629095 }, { "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": 25.85037128732247 }, { "filename": "src/custom-resolver/link-live.ts", "retrieved_chunk": "import { editorInfoField, App } from \"obsidian\";\nimport { editorLivePreviewField } from \"obsidian\";\nimport { RefTarget } from \"../engine/ref\";\nimport { DendronWorkspace } from \"../engine/workspace\";\nimport { renderLinkTitle } from \"./link-render\";\nclass LinkWidget extends WidgetType {\n containerEl: HTMLSpanElement;\n ref: RefTarget | null;\n constructor(\n public app: App,", "score": 24.191018376501557 }, { "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": 23.222066826262722 }, { "filename": "src/modal/add-vault.ts", "retrieved_chunk": "import { App, Modal, Notice, PopoverSuggest, Setting, TFolder, TextComponent } from \"obsidian\";\nimport { VaultConfig } from \"src/engine/vault\";\nclass FolderSuggester extends PopoverSuggest<TFolder> {\n constructor(\n public app: App,\n public inputEl: HTMLInputElement,\n public onSelected: (folder: TFolder) => void\n ) {\n super(app);\n inputEl.addEventListener(\"input\", this.onInputChange);", "score": 21.136609989781313 } ]
typescript
: MaybeNoteRef ) {
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/CrowdinArticleDirectories.ts", "retrieved_chunk": " type: \"number\",\n },\n {\n name: \"directoryId\",\n type: \"number\",\n },\n ],\n};\nexport default CrowdinArticleDirectories;", "score": 15.315333157203327 }, { "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": 11.974771501203046 }, { "filename": "src/collections/CrowdinFiles.ts", "retrieved_chunk": " ],\n },\n ],\n};\nexport default CrowdinFiles;", "score": 9.40719570347037 }, { "filename": "src/collections/CrowdinCollectionDirectories.ts", "retrieved_chunk": " name: \"projectId\",\n type: \"number\",\n },\n {\n name: \"directoryId\",\n type: \"number\",\n },\n ],\n};\nexport default CrowdinCollectionDirectories;", "score": 7.210659179790572 }, { "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": 5.581570639939699 } ]
typescript
...(CrowdinArticleDirectories.fields || []), {
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 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": 28.646491786711945 }, { "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": 27.511361169499303 }, { "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": 26.940410353122275 }, { "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": 24.45739691084053 }, { "filename": "src/engine/note.ts", "retrieved_chunk": " const note = this.getFromFileName(name);\n if (!note) return;\n note.file = undefined;\n if (note.children.length == 0) {\n let currentNote: Note | undefined = note;\n while (\n currentNote &&\n currentNote.parent &&\n !currentNote.file &&\n currentNote.children.length == 0", "score": 22.253942982408937 } ]
typescript
onFileDeleted(parsed: ParsedPath): boolean {
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/collections/CrowdinFiles.ts", "retrieved_chunk": " },\n fields: [\n /* Crowdin field */\n {\n name: \"title\",\n type: \"text\",\n },\n /* Internal fields */\n {\n name: \"field\",", "score": 26.678817417741342 }, { "filename": "src/utilities/tests/buildHtmlCrowdinObject/fixtures/array-field-type.fixture.ts", "retrieved_chunk": "import { Field } from \"payload/types\";\nexport const field: Field = {\n name: \"arrayField\",\n type: \"array\",\n fields: [\n {\n name: \"title\",\n type: \"richText\",\n localized: true,\n },", "score": 26.118231656400905 }, { "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": 25.892758466747907 }, { "filename": "src/utilities/tests/fixtures/blocks-field-type.fixture.ts", "retrieved_chunk": " ...basicLocalizedFields,\n {\n name: \"richTextField\",\n type: \"richText\",\n localized: true,\n },\n ],\n};\nexport const field: Field = {\n name: \"blocksField\",", "score": 25.582996715902134 }, { "filename": "src/utilities/tests/buildJsonCrowdinObject/array-field-type.spec.ts", "retrieved_chunk": "import { CollectionConfig, Field } from \"payload/types\";\nimport { buildCrowdinJsonObject, getLocalizedFields } from \"../..\";\nimport { FieldWithName } from \"../../../types\";\ndescribe(\"fn: buildCrowdinJsonObject: array field type\", () => {\n it(\"do not include non-localized fields nested in an array\", () => {\n const doc = {\n id: \"638641358b1a140462752076\",\n title: \"Test Policy created with title\",\n arrayField: [\n {", "score": 24.51876904734331 } ]
typescript
field.name);
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": 43.3889416376779 }, { "filename": "src/utilities/getLocalizedFields.spec.ts", "retrieved_chunk": " ];\n expect(getLocalizedFields({ fields: global.fields, type: \"html\" })).toEqual(\n expected\n );\n });\n it(\"returns nested json fields in a group inside an array\", () => {\n const linkField: Field = {\n name: \"link\",\n type: \"group\",\n fields: [", "score": 27.10270150181112 }, { "filename": "src/utilities/containsLocalizedFields.spec.ts", "retrieved_chunk": " },\n ];\n expect(containsLocalizedFields({ fields })).toEqual(true);\n });\n it(\"returns nested json fields in a group inside an array\", () => {\n const linkField: Field = {\n name: \"link\",\n type: \"group\",\n fields: [\n {", "score": 24.77534718459266 }, { "filename": "src/utilities/containsLocalizedFields.spec.ts", "retrieved_chunk": " },\n ];\n expect(containsLocalizedFields({ fields })).toEqual(false);\n });\n it(\"returns nested json fields in a group inside an array\", () => {\n const linkField: Field = {\n name: \"link\",\n type: \"group\",\n fields: [\n {", "score": 24.77534718459266 }, { "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": 23.89349530330869 } ]
typescript
getLocalizedFields({ fields: Promos.fields, type: "json" }), }) ).toEqual(expected);
import { App, TFolder, parseLinktext } from "obsidian"; import { DendronVault, VaultConfig } from "./vault"; import { getFolderFile } from "../utils"; import { RefTarget, parseRefSubpath } from "./ref"; import { parsePath } from "../path"; const DENDRON_URI_START = "dendron://"; export class DendronWorkspace { vaultList: DendronVault[] = []; constructor(public app: App) {} changeVault(vaultList: VaultConfig[]) { this.vaultList = vaultList.map((config) => { return ( this.vaultList.find( (vault) => vault.config.name === config.name && vault.config.path === config.path ) ?? new DendronVault(this.app, config) ); }); for (const vault of this.vaultList) { vault.init(); } } findVaultByParent(parent: TFolder | null): DendronVault | undefined { return this.vaultList.find((vault) => vault.folder === parent); } findVaultByParentPath(path: string): DendronVault | undefined { const file = getFolderFile(this.app.vault, path); return file instanceof TFolder ? this.findVaultByParent(file) : undefined; } resolveRef(sourcePath: string, link: string): RefTarget | null { if (link.startsWith(DENDRON_URI_START)) { const [vaultName, rest] = link.slice(DENDRON_URI_START.length).split("/", 2) as ( | string | undefined )[]; const { path, subpath } = rest ? parseLinktext(rest) : { path: undefined, subpath: undefined, }; const vault = this.vaultList.find(({ config }) => config.name === vaultName); return { type: "maybe-note", vaultName: vaultName ?? "", vault, note: path ? vault?.tree?.getFromFileName(path) : undefined, path: path ?? "", subpath: subpath ? parseRefSubpath(subpath) : undefined, }; } const { dir: vaultDir
} = parsePath(sourcePath);
const vault = this.findVaultByParentPath(vaultDir); if (!vault) return null; const { path, subpath } = parseLinktext(link); const target = this.app.metadataCache.getFirstLinkpathDest(path, sourcePath); if (target && target.extension !== "md") return { type: "file", file: target, }; const note = vault.tree.getFromFileName(path); return { type: "maybe-note", vaultName: vault.config.name, vault: vault, note, path, subpath: parseRefSubpath(subpath.slice(1) ?? ""), }; } }
src/engine/workspace.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/engine/ref.ts", "retrieved_chunk": "import { CachedMetadata, HeadingCache, TFile } from \"obsidian\";\nimport { Note } from \"./note\";\nimport { DendronVault } from \"./vault\";\nimport GithubSlugger from \"github-slugger\";\nexport interface MaybeNoteRef {\n type: \"maybe-note\";\n vaultName: string;\n vault?: DendronVault;\n note?: Note;\n path: string;", "score": 28.466112861783106 }, { "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": 26.63633555157762 }, { "filename": "src/custom-resolver/link-open.ts", "retrieved_chunk": " return originalBoundedFunction(linktext, sourcePath, newLeaf, openViewState);\n let file = target.note?.file;\n if (!file) {\n if (target.vaultName === \"\") {\n new Notice(\"Vault name is unspecified in link.\");\n return;\n } else if (!target.vault) {\n new Notice(`Vault ${target.vaultName} is not found.`);\n return;\n } else if (target.path === \"\") {", "score": 23.11687839671327 }, { "filename": "src/engine/ref.ts", "retrieved_chunk": " };\n}\nexport function getRefContentRange(subpath: RefSubpath, metadata: CachedMetadata): RefRange | null {\n const range: RefRange = {\n start: 0,\n startLineOffset: 0,\n end: undefined,\n };\n const { start, end } = subpath;\n if (start.type === \"begin\") {", "score": 22.161956990153534 }, { "filename": "src/custom-resolver/ref-render.ts", "retrieved_chunk": " if (vaultName === \"\") {\n content.setText(\"Vault name are unspecified in link.\");\n return;\n } else if (!vault) {\n content.setText(`Vault ${vaultName} are not found.`);\n return;\n } else if (path === \"\") {\n content.setText(\"Note path are unspecified in link.\");\n return;\n }", "score": 21.985752221015748 } ]
typescript
} = parsePath(sourcePath);
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": 34.35055073551857 }, { "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": 29.297536289250242 }, { "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": 27.7626030609109 }, { "filename": "src/utilities/tests/buildJsonCrowdinObject/array-field-type.spec.ts", "retrieved_chunk": " localized: true,\n options: [\"one\", \"two\"],\n },\n ],\n },\n ];\n const localizedFields = getLocalizedFields({ fields });\n const expected = {\n title: \"Test Policy created with title\",\n arrayField: {", "score": 26.420999059910983 }, { "filename": "src/utilities/tests/buildJsonCrowdinObject/group-field-type.spec.ts", "retrieved_chunk": " 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 nested in a group with a localization setting on the group field\", () => {\n const doc = {\n id: \"638641358b1a140462752076\",", "score": 26.121184771092327 } ]
typescript
expect(buildCrowdinJsonObject({ doc, fields })).toEqual(expected);
import { Menu, Plugin, TAbstractFile, TFile, addIcon } from "obsidian"; import { DendronView, VIEW_TYPE_DENDRON } from "./view"; import { activeFile, dendronVaultList } from "./store"; import { LookupModal } from "./modal/lookup"; import { dendronActivityBarIcon, dendronActivityBarName } from "./icons"; import { DEFAULT_SETTINGS, DendronTreePluginSettings, DendronTreeSettingTab } from "./settings"; import { parsePath } from "./path"; import { DendronWorkspace } from "./engine/workspace"; import { CustomResolver } from "./custom-resolver"; export default class DendronTreePlugin extends Plugin { settings: DendronTreePluginSettings; workspace: DendronWorkspace = new DendronWorkspace(this.app); customResolver?: CustomResolver; async onload() { await this.loadSettings(); await this.migrateSettings(); addIcon(dendronActivityBarName, dendronActivityBarIcon); this.addCommand({ id: "dendron-lookup", name: "Lookup Note", callback: () => { new LookupModal(this.app, this.workspace).open(); }, }); this.addSettingTab(new DendronTreeSettingTab(this.app, this)); this.registerView(VIEW_TYPE_DENDRON, (leaf) => new DendronView(leaf, this)); this.addRibbonIcon(dendronActivityBarName, "Open Dendron Tree", () => { this.activateView(); }); this.app.workspace.onLayoutReady(() => { this.onRootFolderChanged(); this.registerEvent(this.app.vault.on("create", this.onCreateFile)); this.registerEvent(this.app.vault.on("delete", this.onDeleteFile)); this.registerEvent(this.app.vault.on("rename", this.onRenameFile)); this.registerEvent(this.app.metadataCache.on("resolve", this.onResolveMetadata)); this.registerEvent(this.app.workspace.on("file-open", this.onOpenFile, this)); this.registerEvent(this.app.workspace.on("file-menu", this.onFileMenu)); }); this.configureCustomResolver(); } async migrateSettings() { function pathToVaultConfig(path: string) { const { name } = parsePath(path); if (name.length === 0) return { name: "root", path: "/", }; let processed = path; if (processed.endsWith("/")) processed = processed.slice(0, -1); if (processed.startsWith("/") && processed.length > 1) processed = processed.slice(1); return { name, path: processed, }; } if (this.settings.vaultPath) { this.settings.vaultList = [pathToVaultConfig(this.settings.vaultPath)]; this.settings.vaultPath = undefined; await this.saveSettings(); } if (this.settings.vaultList.length > 0 && typeof this.settings.vaultList[0] === "string") { this.settings.vaultList = (this.settings.vaultList as unknown as string[]).map((path) => pathToVaultConfig(path) ); await this.saveSettings(); } } onunload() {} onRootFolderChanged() { this.workspace.changeVault(this.settings.vaultList); this.updateNoteStore(); } configureCustomResolver() { if (this.settings.customResolver && !this.customResolver) { this.customResolver = new CustomResolver(this, this.workspace); this.addChild(this.customResolver); } else if (!this.settings.customResolver && this.customResolver) { this.removeChild(this.customResolver); this.customResolver = undefined; } } updateNoteStore() { dendronVaultList.set(this.workspace.vaultList); } onCreateFile = async (file: TAbstractFile) => { const vault = this.workspace.findVaultByParent(file.parent); if (vault && vault.onFileCreated(file)) { if (this.settings.autoGenerateFrontmatter && file instanceof TFile && file.stat.size === 0) await vault.generateFronmatter(file); this.updateNoteStore(); } }; onDeleteFile = (file: TAbstractFile) => { // file.parent is null when file is deleted const parsed = parsePath(file.path); const vault = this.workspace.findVaultByParentPath(parsed.dir); if (vault && vault.onFileDeleted(parsed)) { this.updateNoteStore(); } }; onRenameFile = (file: TAbstractFile, oldPath: string) => { const oldParsed = parsePath(oldPath); const oldVault = this.workspace.findVaultByParentPath(oldParsed.dir); let update = false; if (oldVault) { update = oldVault.onFileDeleted(oldParsed); } const newVault = this.workspace.findVaultByParent(file.parent); if (newVault) { update = newVault.onFileCreated(file) || update; } if (update) this.updateNoteStore(); }; onOpenFile(file: TFile | null) { activeFile.set(file); if (file && this.settings.autoReveal) this.revealFile(file); } onFileMenu = (menu: Menu, file: TAbstractFile) => { if (!(file instanceof TFile)) return; menu.addItem((item) => { item .setIcon(dendronActivityBarName) .setTitle("Reveal in Dendron Tree") .onClick(() => this.revealFile(file)); }); }; onResolveMetadata = (file: TFile) => { const vault = this.workspace.findVaultByParent(file.parent); if (vault && vault.onMetadataChanged(file)) { this.updateNoteStore(); } }; revealFile(file: TFile) { const vault = this.workspace.findVaultByParent(file.parent); if (!vault) return; const note = vault.tree.getFromFileName(file.basename); if (!note) return; for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON)) { if (!(leaf.view instanceof DendronView)) continue; leaf
.view.component.focusTo(vault, note);
} } async activateView() { const leafs = this.app.workspace.getLeavesOfType(VIEW_TYPE_DENDRON); if (leafs.length == 0) { const leaf = this.app.workspace.getLeftLeaf(false); await leaf.setViewState({ type: VIEW_TYPE_DENDRON, active: true, }); this.app.workspace.revealLeaf(leaf); } else { leafs.forEach((leaf) => this.app.workspace.revealLeaf(leaf)); } } async loadSettings() { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); } async saveSettings() { await this.saveData(this.settings); } }
src/main.ts
levirs565-obsidian-dendron-tree-b11ea1e
[ { "filename": "src/utils.ts", "retrieved_chunk": " if (!file || !(file instanceof TFile)) return;\n const leaf = app.workspace.getLeaf();\n return leaf.openFile(file, openState);\n}\nconst alphanumericLowercase = \"0123456789abcdefghijklmnopqrstuvwxyz\";\nexport const generateUUID = nanoid(alphanumericLowercase, 23);", "score": 45.474186911381516 }, { "filename": "src/engine/workspace.ts", "retrieved_chunk": " }\n findVaultByParent(parent: TFolder | null): DendronVault | undefined {\n return this.vaultList.find((vault) => vault.folder === parent);\n }\n findVaultByParentPath(path: string): DendronVault | undefined {\n const file = getFolderFile(this.app.vault, path);\n return file instanceof TFolder ? this.findVaultByParent(file) : undefined;\n }\n resolveRef(sourcePath: string, link: string): RefTarget | null {\n if (link.startsWith(DENDRON_URI_START)) {", "score": 34.70239033875105 }, { "filename": "src/engine/vault.ts", "retrieved_chunk": " const filePath = `${this.config.path}/${baseName}.md`;\n return await this.app.vault.create(filePath, \"\");\n }\n async generateFronmatter(file: TFile) {\n if (!this.isNote(file.extension)) return;\n const note = this.tree.getFromFileName(file.basename);\n if (!note) return false;\n return await this.app.fileManager.processFrontMatter(file, (fronmatter) => {\n if (!fronmatter.id) fronmatter.id = generateUUID();\n if (!fronmatter.title) fronmatter.title = note.title;", "score": 34.12876424420649 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " }\n getSuggestions(query: string): (LookupItem | null)[] {\n const queryLowercase = query.toLowerCase();\n const result: (LookupItem | null)[] = [];\n let foundExact = true;\n for (const vault of this.workspace.vaultList) {\n let currentFoundExact = false;\n for (const note of vault.tree.flatten()) {\n const path = note.getPath();\n const item: LookupItem = {", "score": 33.8011076714801 }, { "filename": "src/modal/lookup.ts", "retrieved_chunk": " return;\n }\n const path = item ? item.note.getPath() : this.inputEl.value;\n const doCreate = async (vault: DendronVault) => {\n const file = await vault.createNote(path);\n return openFile(vault.app, file);\n };\n if (item?.vault) {\n await doCreate(item.vault);\n } else if (this.workspace.vaultList.length == 1) {", "score": 33.683005450555434 } ]
typescript
.view.component.focusTo(vault, note);