Skip to content

Latest commit

 

History

History
308 lines (241 loc) · 8.85 KB

File metadata and controls

308 lines (241 loc) · 8.85 KB

Instructions for Coding Agents

This is a Glide JS Code Sandbox environment. Follow these instructions when writing code in this repository.

⚠️ CRITICAL SECURITY REQUIREMENT - READ THIS FIRST ⚠️

NEVER HARDCODE SECRETS IN CODE - EVER!

THIS IS THE MOST IMPORTANT RULE. VIOLATING THIS RULE IS UNACCEPTABLE.

  • NEVER write API keys, tokens, passwords, or any secrets directly in code.js
  • NEVER write secrets as string literals in your code
  • ALWAYS use environment variables via process.env for ALL secrets
  • ALWAYS create/update .env.example to document required environment variables

❌ ABSOLUTELY FORBIDDEN - YOU MUST NEVER DO THIS:

// DANGER! NEVER write secrets like this!
const apiKey = 'sk-1234567890abcdef';           // ❌ NEVER!
const password = 'mySecretPassword';            // ❌ NEVER!
const token = 'ghp_xxxxxxxxxxxxxxxxxxxx';       // ❌ NEVER!
const secret = input.apiKey || 'default-key';   // ❌ NEVER!

✅ REQUIRED - YOU MUST ALWAYS DO THIS:

// Correct! Always use process.env for secrets
const apiKey = process.env.API_KEY;             // ✅ ALWAYS!
const password = process.env.PASSWORD;          // ✅ ALWAYS!
const token = process.env.GITHUB_TOKEN;         // ✅ ALWAYS!

// Always validate that required secrets exist
if (!apiKey) {
  return { error: 'API_KEY environment variable is required' };
}

When a user requests functionality requiring secrets:

  1. Use process.env.VARIABLE_NAME in your code
  2. Document the required variable in .env.example
  3. NEVER ask the user for the secret value in code
  4. NEVER hardcode any default or fallback secret values

This is a SECURITY requirement. Code with hardcoded secrets is REJECTED.


Core Requirements

The run Function

  • Edit ONLY code.js to implement your logic
  • The file MUST export a function named run
  • The function can be async or synchronous
  • The function takes exactly ONE parameter: a JSON object
  • The function MUST return a JSON-serializable object
  • All code logic must be in code.js - no other code files can be imported

Available Packages

You can ONLY import these packages:

  • lodash - Full lodash utility library
  • date-fns - Date manipulation and formatting
  • ms - Convert time strings to milliseconds (e.g., "2 days" -> 172800000)
  • uuid - Generate UUIDs
  • fast-deep-equal - Deep equality comparison

Import syntax:

import _ from 'lodash';
import { format, addDays } from 'date-fns';
import ms from 'ms';
import { v4 as uuidv4 } from 'uuid';
import equal from 'fast-deep-equal';

Restrictions

  • NO HARDCODED SECRETS - EVER! Use process.env for ALL secrets!
  • NO other npm packages can be added or used
  • NO other local files can be imported
  • NO file system operations
  • Input and output must be JSON-serializable (no functions, undefined, symbols, etc.)

Testing Your Code

Running Code

Use this command to test your implementation:

npm start -- '{ "your": "input" }'

The JSON input must be properly quoted and escaped for the shell.

Running Tests

npm test

Writing Tests

Add tests to code.test.js using Node's built-in test runner:

import { test, describe } from 'node:test';
import assert from 'node:assert';
import { run } from './code.js';

describe('feature name', () => {
  test('should do something', async () => {
    const result = await run({ input: 'value' });
    assert.strictEqual(result.expected, 'value');
  });
});

Available Assertions

  • assert.strictEqual(actual, expected) - Strict equality (===)
  • assert.deepStrictEqual(actual, expected) - Deep equality
  • assert.ok(value) - Truthy check
  • assert.notStrictEqual(actual, expected) - Not equal
  • assert.throws(() => code) - Expect error

Development Workflow

  1. Understand the requirements - Read what the user wants the function to do
  2. Plan the implementation - Think about which packages to use
  3. Write the code - Edit code.js with the run function
  4. Write tests - Add tests to code.test.js
  5. Run tests - Execute npm test to verify
  6. Test with real input - Use npm start with example JSON
  7. Iterate - Fix any issues and re-test

Example Implementation

import _ from 'lodash';
import { format } from 'date-fns';
import { v4 as uuidv4 } from 'uuid';

export async function run(input) {
  // Process input
  const processed = _.mapValues(input, (value) => {
    if (typeof value === 'string') {
      return _.upperCase(value);
    }
    return value;
  });

  // Return JSON output
  return {
    id: uuidv4(),
    timestamp: format(new Date(), 'yyyy-MM-dd HH:mm:ss'),
    originalInput: input,
    processedData: processed
  };
}

Common Patterns

Working with dates

import { format, addDays, subDays, differenceInDays } from 'date-fns';

const now = new Date();
const future = addDays(now, 7);
const formatted = format(future, 'yyyy-MM-dd');

Working with lodash

import _ from 'lodash';

const grouped = _.groupBy(items, 'category');
const unique = _.uniq(array);
const sorted = _.sortBy(items, ['date', 'name']);

Generating IDs

import { v4 as uuidv4 } from 'uuid';

const id = uuidv4(); // '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

Time conversions

import ms from 'ms';

const milliseconds = ms('2 days'); // 172800000
const str = ms(60000); // "1m"

Deep equality

import equal from 'fast-deep-equal';

if (equal(obj1, obj2)) {
  // Objects are deeply equal
}

Using environment variables and secrets

🔒 MANDATORY: ALL secrets MUST use environment variables - NO EXCEPTIONS! 🔒

NEVER write secrets in code. ALWAYS use process.env:

export async function run(input) {
  // ✅ CORRECT: Access environment variables for ALL secrets
  const apiKey = process.env.API_KEY;
  const dbUrl = process.env.DATABASE_URL;

  // ✅ CORRECT: Always validate that required secrets exist
  if (!apiKey) {
    return { error: 'API_KEY environment variable is required' };
  }

  // Use the secrets in your logic
  return {
    authenticated: true,
    // ... your logic here
  };
}

❌ NEVER DO THIS:

// WRONG! NEVER hardcode secrets!
const apiKey = 'sk-abc123';  // ❌ FORBIDDEN!
const apiKey = input.secret || 'default';  // ❌ FORBIDDEN!

Setting up environment variables:

  1. Create/update .env.example to document which variables are needed (NO actual values!)
  2. User creates a .env file in the project root
  3. User adds their secrets (e.g., API_KEY=their_actual_key_here)
  4. Access them in code ONLY via process.env.VARIABLE_NAME

CRITICAL RULES:

  • .env file is in .gitignore - secrets are NEVER committed
  • Environment variables are automatically loaded via dotenv
  • When users ask for functionality requiring API keys, you MUST use environment variables
  • ALWAYS create/update .env.example to document required variables
  • NEVER EVER write actual secret values in code files

Debugging

Use console.log() in your code - output will appear when running:

npm start -- '{ "debug": true }'

Error Handling and Exceptions

Throw exceptions to signal errors - Glide handles retries!

When your code throws an exception, Glide will automatically retry the operation.

This means you should simply throw exceptions when something goes wrong, and let Glide handle the retry logic.

Example:

export async function run(input) {
  const response = await fetch(`https://api.example.com/data`);

  // Simply throw an exception if something goes wrong
  if (!response.ok) {
    throw new Error(`API request failed: ${response.status} ${response.statusText}`);
  }

  const data = await response.json();
  return { success: true, data };
}

Key Rules:

  1. Throw exceptions to signal errors
  2. DO NOT implement retry logic - Glide handles retries automatically
  3. DO NOT catch and suppress errors unless you have a specific reason
  4. The dev environment will catch exceptions and display them clearly

Before Committing

Always run both commands to ensure everything works:

npm test && npm start -- '{ "test": "input" }'

Key Reminders

MOST IMPORTANT:

  • 🚨 NEVER HARDCODE SECRETS! ALWAYS use process.env for API keys, tokens, passwords!
  • 🚨 Update .env.example when your code needs new environment variables

Required:

  • ✅ Export a function named run from code.js
  • ✅ Take one JSON object parameter
  • ✅ Return a JSON-serializable object
  • ✅ Only use allowed packages
  • ✅ Write tests in code.test.js
  • ✅ Use process.env for ALL secrets and sensitive data

Forbidden:

  • NEVER write secrets as string literals in code
  • ❌ Don't modify runner.js or package.json
  • ❌ Don't import other local files
  • ❌ Don't add new packages
  • ❌ Don't use the file system