How to use nanoid - 10 common examples

To help you get started, we’ve selected a few nanoid examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DevExpress / testcafe-hammerhead / src / utils / generate-unique-id.ts View on Github external
// @ts-ignore
import nanoIdGenerate from 'nanoid/generate';
// @ts-ignore
import nanoIdAlphabet from 'nanoid/url';

const UNIQUE_ID_ALPHABET: string = nanoIdAlphabet.replace(/-|~/g, '');

const DEFAULT_ID_LENGTH = 9;

export default function (length?: number): string {
    return nanoIdGenerate(UNIQUE_ID_ALPHABET, length || DEFAULT_ID_LENGTH);
}
github shesek / spark-wallet / src / auth.js View on Github external
module.exports = (app, cookieFile, login) => {
  let username, password, accessKey

  const hasFile = cookieFile && fs.existsSync(cookieFile)

  if (login) { // provided via --login (or LOGIN)
    ;[ username, password, accessKey ] = login.split(':', 3)
    assert(password, `Invalid login format, expecting "username:pwd"`)
  } else if (hasFile) {
    console.log(`Loading login credentials from ${cookieFile}`)
    ;[ username, password, accessKey ] = fs.readFileSync(cookieFile).toString('utf-8').trim().split(':')
    assert(password, `Invalid login file at ${cookieFile}, expecting "username:pwd[:access-key]"`)
  } else { // generate random
    username = nanogen('abcdefghijklmnopqrstuvwxyz', 5)
    password = nanoid(15)
    accessKey = hmacStr(`${username}:${password}`, 'access-key')
    console.log(`No LOGIN or --login specified, picked username "${username}" with password "${password}"`)

    if (cookieFile) {
      console.log(`Writing login credentials to ${cookieFile}`)
      !fs.existsSync(path.dirname(cookieFile)) && mkdirp.sync(path.dirname(cookieFile))
      fs.writeFileSync(cookieFile, [ username, password, accessKey ].join(':'))
    }
  }

  // HMAC derive the access key from the user/pwd combo, if not explicitly defined
  accessKey || (accessKey = hmacStr(`${username}:${password}`, 'access-key'))

  const manifestKey = hmacStr(accessKey, 'manifest-key').substr(0, 10)
      , manifestRe  = new RegExp(`^/manifest-${manifestKey}/`)
github andywer / puppet-run / src / bundle.ts View on Github external
export async function createBundle (entry: Entrypoint, cache: TemporaryFileCache): Promise {
  // TODO: Use persistent cache

  const servePath = (entry.servePath || `${path.basename(entry.sourcePath)}-${nanoid(6)}`).replace(/\.(jsx?|tsx?)/i, ".js")
  const bundleFilePath = path.join(cache, servePath)
  const extensions = ["", ".js", ".jsx", ".ts", ".tsx", ".json"]

  mkdirp.sync(path.dirname(bundleFilePath))

  await new Promise(resolve => {
    const stream = browserify({
      debug: true,    // enables inline sourcemaps
      entries: [entry.sourcePath],
      extensions
    })
    .transform(babelify.configure({
      cwd: __dirname,
      extensions,
      presets: [
        "@babel/preset-typescript",
github nuxt-community / auth-module / lib / schemes / oauth2.js View on Github external
// https://auth0.com/docs/protocols/oauth2/oauth-state
      state: state || nanoid(),
      ...params
    }

    if (this.options.audience) {
      opts.audience = this.options.audience
    }

    // Set Nonce Value if response_type contains id_token to mitigate Replay Attacks
    // More Info: https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes
    // More Info: https://tools.ietf.org/html/draft-ietf-oauth-v2-threatmodel-06#section-4.6.2
    if (opts.response_type.includes('id_token')) {
      // nanoid auto-generates an URL Friendly, unique Cryptographic string
      // Recommended by Auth0 on https://auth0.com/docs/api-auth/tutorials/nonce
      opts.nonce = nonce || nanoid()
    }

    this.$auth.$storage.setUniversal(this.name + '.state', opts.state)

    const url = this.options.authorization_endpoint + '?' + encodeQuery(opts)

    window.location = url
  }
github getholo / dashboard / src / types / apps.ts View on Github external
Cat extends Category,
  Variables extends { [key: string]: string },
  Functions extends {
    [key: string]: (arg: any) => MaybePromise
  },
  Dest extends string,
  > {
  constructor(public config: Config) {
    // who the f needs a constructor anyways?
  }

  public functions = this.config.functions;
  public postInstall: (app: this) => any

  public readonly id: appName | string = process.env.NODE_ENV === 'test'
    ? `${this.config.name}-${nanoid('0123456789abcdefghijklmnopqrstuvwxyz', 20)}`
    : this.config.name

  public category = this.config.category;
  public name = this.config.name;
  public variables = new VariablesBackend(this.id, this.config.variables)

  private appdataToPath() {
    // removed linux platform as /opt/appdata requires extra permissions
    return join(homedir(), '.getholo', 'dashboard', 'containers', this.id);
  }

  public paths: Path[] = this.config.paths.map(
    path => ({
      dest: path.dest,
      src: path.src === 'appdata' ? this.appdataToPath() : path.src,
      readOnly: path.readOnly,
github pieterbeulque / anonymous-analytics / index.js View on Github external
const getClientId = () => {
	const existing = store.get(ANONYMOUS_ANALYTICS_CLIENT_ID);

	if (existing) {
		return existing;
	}

	try {
		return nanoid();
	} catch (error) {
		// The Web Crypto API is probably not supported
		// Return a LEGACY-TIMESTAMP id
		return `LEGACY-${(new Date()).getTime()}`;
	}
};
github zeit / next.js / examples / with-aws-amplify / pages / index.js View on Github external
const createToDo = async (dispatch, currentToDo) => {
  const todo = {
    id: nanoid(),
    name: currentToDo,
    createdAt: `${Date.now()}`,
    completed: false,
    todoTodoListId: 'global',
    userId: MY_ID,
  }
  dispatch({ type: 'add-todo', payload: todo })
  dispatch({ type: 'reset-current' })
  try {
    await API.graphql(graphqlOperation(createTodo, { input: todo }))
  } catch (err) {
    dispatch({ type: 'set-current', payload: todo.name })
    console.warn('Error adding to do ', err)
  }
}
const deleteToDo = async (dispatch, id) => {
github bs-community / blessing-skin-server / resources / assets / src / scripts / toast.tsx View on Github external
success(message: string) {
    emitter.emit(TOAST_EVENT, { id: nanoid(4), type: 'success', message })
  }
github bs-community / blessing-skin-server / resources / assets / src / scripts / toast.tsx View on Github external
warning(message: string) {
    emitter.emit(TOAST_EVENT, { id: nanoid(4), type: 'warning', message })
  }
github bs-community / blessing-skin-server / resources / assets / src / scripts / toast.tsx View on Github external
info(message: string) {
    emitter.emit(TOAST_EVENT, { id: nanoid(4), type: 'info', message })
  }

nanoid

A tiny (116 bytes), secure URL-friendly unique string ID generator

MIT
Latest version published 12 days ago

Package Health Score

88 / 100
Full package analysis