npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

spotter-eng-utils

v1.105.0

Published

Spotter Utils

Downloads

27

Readme

Setting up in Vercel

  1. Choose a template or copy code from the next/example section
  2. Make sure vercel cli is installed - https://vercel.com/docs/cli
  3. Run vercel login
  4. Run vercel init
  5. Setup your environment variables https://vercel.com/spotter/{yourapp}/settings/environment-variables
    • Environment variables must have NEXT_PUBLIC_ prefix to be available on client and server sides
    • If you omit the NEXT_PUBLIC_, it will only be accessible on the server side
  6. To access your secrets for development, add this to your package.json or simply copy what's in the next/example: vercel pull && cp .vercel/.env.development.local .env

Setup NextJS App using this module -

All of these code snippets are found under nextjs/example

If you have conflicts with AWS Code Artifact, you may have to reset your npm registry: npm config set registry https://registry.npmjs.org/

  1. Replace _app.js contents with:
import { store } from '@/store';
import '@/styles/globals.css';
import { Provider } from 'react-redux';
import { appGetInitialProps, MyAppSetup } from 'spotter-eng-utils/nextjs/authentication/bootstrapApp';
import { toTitleCase } from 'spotter-eng-utils/nextjs/utils';
const { name } = require('../package.json');

const ExtraHeaderComponent = () => {
  // Extra header components here
  return <></>;
};

function MyApp({ Component, pageProps, startupProps }) {
  const headerData = {
    title: 'SpotterLabs',
    subTitle: toTitleCase(name, true),
    component: <ExtraHeaderComponent />,
  };
  return <Provider store={store}>{MyAppSetup(Component, pageProps, startupProps, headerData, store)}</Provider>;
}

MyApp.getInitialProps = async appContext => {
  return await appGetInitialProps(appContext);
};

export default MyApp;
  1. Create a file called login.js at the same level as _app.js and paste:
import SpotterLogin from 'spotter-eng-utils/nextjs/authentication/googleLogin/login';

const Login = props => {
  const { serverUrl } = props;

  return (
    <SpotterLogin
      title={'Your Login title goes here'}
      serverUrl={serverUrl}
      clientId={'Your Google Client ID goes here'}
      authServerURI={`${backendAuthDomainGoesHere}/api/login/google`}
    />
  );
};

export default Login;

Page Property Overrides

| Property | Description | Options | | -------- | ---------------------------------------------------------------------------------------------------------------------- | ----------------------- | | noAuth | Will allow the page to be public. Otherwise it will redirect user to login if not authenticated. | true (default)false | | Layout | This will allow you to create & set a custom layout for the current page. While running needed code behind the scenes. | |

Example:

const Home = () => {
  return <div>Open unauthenticated Landing Page</div>;
};

Home.noAuth = true;
export default Home;

REST Calls

REST calls should be setup in this structure. Please see the sample code in next/example

project
│   README.md
│   ...
└───pages
│    ...
│
└───services
    │───client
    │   * index.js - This should setup your axios instances
    │   * users.js - This could get your userProfile or updateProfile
    │───server
    │   * index.js - This should setup your axios instances
    │   * users.js - This could get your userProfile

Example Client Side Call

useEffect(() => {
  const [clientSideUserProfile, setClientSideUserProfile] = useState(null);
  const getProfile = async () => {
    const profile = await UserClientSideService.portal.getProfile();
    setClientSideUserProfile(profile);
  };
  getProfile().catch(console.error);
}, []);

Example Server Side Call

const Home = ({ serverSideUserProfile }) => {
  return (
    <div>
      <pre>{JSON.stringify(clientSideUserProfile, null, 2)}</pre>
    </div>
  );
};
export const getServerSideProps = async context => {
  const profile = await UserServerSideService.portal.getProfile(context);
  return {
    props: { serverSideUserProfile: profile },
  };
};

Streaming AI Calls via Polling - (Depends on backend implementation)

Component:

import { useAICallPoller } from 'spotter-eng-utils/nextjs/streaming/aiCalls';
import { GPTModelContext } from 'spotter-eng-utils/nextjs/context';

const Home = ({ user }) => {
  const dispatch = useDispatch();
  const [userInput, setUserInput] = useState({
    title: '',
    summary: '',
  });

  // Current gptModel dropdown selection
  const { gptModel } = useContext(GPTModelContext);

  // Create record reducer
  const createdTitle = useSelector(state => state.createdTitle);
  // Fetch record reducer
  const titleResults = useSelector(state => state.titleResults);

  // Poller - kicks off when the create record dispatch is triggered
  // polling is true/false so you can conditionally render elements.
  const polling = useAICallPoller({
    createReducerName: 'createdTitle', // name variable in create slice
    pollingReducerName: 'titleResults', // name variable in fetch slice
    intervalRate: 1000, // How often do you want to poll - time is in milliseconds
    pollingSlice: getTitle, // asyncThunk in fetch slice
  });

  const executeAICall = () => {
    dispatch(createTitle({ ...userInput, gptModel: gptModel.key }));
  };

  return <button onClick={executeAICall}>Stream My results</button>;
};

Create Object Slice

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { UserClientSideService } from '../../../services/client/calls';

const name = 'createTitle';

export const createTitle = createAsyncThunk(
  name,
  async (data, { dispatch, getState, rejectWithValue, fulfillWithValue }) => {
    dispatch({ type: 'getTitle/reset' }); // Reset the fetch - need this so the polling terminator fn won't read last slice's values
    try {
      return await UserClientSideService.rnd.explode({
        title: data.title,
        title_summary: data.summary,
      });
    } catch (err) {
      console.error(err);
      dispatch({ type: 'bannerMessage/errored', payload: 'Custom Failure message.' });
      rejectWithValue(err);
    }
  },
);

export const title = createSlice({
  name: name,
  initialState: {
    data: {},
    loading: false,
    errored: false,
    fulfilled: false,
  },
  reducers: {},
  extraReducers: builder => {
    builder.addCase(createTitle.pending, state => {
      state.loading = true;
      state.errored = false;
      state.fulfilled = false;
      state.data = {};
    });
    builder.addCase(createTitle.rejected, state => {
      state.loading = false;
      state.errored = true;
      state.data = {};
    });
    builder.addCase(createTitle.fulfilled, (state, action) => {
      state.loading = false;
      state.errored = false;
      state.fulfilled = true;
      state.data = action.payload;
    });
  },
});

export default title.reducer;

Fetch Item Slice - This is the slice that will be polled

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { UserClientSideService } from '../../../services/client/calls';

const name = 'getTitle';

export const getTitle = createAsyncThunk(
  name,
  async (id, { dispatch, getState, rejectWithValue, fulfillWithValue }) => {
    try {
      return await UserClientSideService.rnd.getTitle(id);
    } catch (err) {
      console.error(err);
      dispatch({ type: 'bannerMessage/errored', payload: 'Failed to fetch title.' });
      rejectWithValue(err);
    }
  },
);

export const currentTitle = createSlice({
  name: name,
  initialState: {
    data: {},
    loading: false,
    errored: false,
    fulfilled: false,
  },
  reducers: {
    // Called from the create object's createAsyncThunk so you can do subsequent polling
    reset: (state, action) => {
      state.data = {};
      state.loading = false;
      state.errored = false;
      state.fulfilled = false;
    },
  },
  extraReducers: builder => {
    builder.addCase(getTitle.pending, state => {
      state.loading = true;
      state.errored = false;
      state.fulfilled = false;
    });
    builder.addCase(getTitle.rejected, state => {
      state.loading = false;
      state.errored = true;
    });
    builder.addCase(getTitle.fulfilled, (state, action) => {
      state.loading = false;
      state.errored = false;
      state.fulfilled = true;
      state.data = action.payload;
    });
  },
});

export default currentTitle.reducer;

Setup Vercel

Choose https://vercel.com/docs/cli

next.config ->

/\*_ @type {import('next').NextConfig} _/;

const nextConfig = {
  // reactStrictMode: true,
  transpilePackages: ['spotter-eng-utils', '@types/google.accounts'],
};

module.exports = nextConfig;

Debugging

Go to the Debug panel (Ctrl+Shift+D on Windows/Linux, ⇧+⌘+D on macOS), select a launch configuration, then press F5 or select Debug: Start Debugging from the Command Palette to start your debugging session.

Tracking

GoogleAnalytics

  • You can update and extend this component in nextjs/components/tracking/googleAnalytics

HotJar

  • You can update and extend this component in nextjs/components/tracking/hotjar