Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: migrate everything to ESM #5345

Merged
merged 7 commits into from
Jan 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/netlify-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,11 +304,11 @@ to do it for you.
**Writing your own Function Templates**

Function templates can specify `addons` that they rely on as well as execute arbitrary code after installation in an
`onComplete` hook, if a special `.netlify-function-template.js` file exists in the directory:
`onComplete` hook, if a special `.netlify-function-template.mjs` file exists in the directory:

```js
// .netlify-function-template.js
module.exports = {
// .netlify-function-template.mjs
export default {
addons: [
{
addonName: 'fauna',
Expand Down
2 changes: 1 addition & 1 deletion src/commands/deploy/deploy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { getBuildOptions, runBuild } from '../../lib/build.mjs'
import { featureFlags as edgeFunctionsFeatureFlags } from '../../lib/edge-functions/consts.mjs'
import { normalizeFunctionsConfig } from '../../lib/functions/config.mjs'
import { getLogMessage } from '../../lib/log.mjs'
import { startSpinner, stopSpinner } from '../../lib/spinner.cjs'
import { startSpinner, stopSpinner } from '../../lib/spinner.mjs'
import {
chalk,
error,
Expand Down
2 changes: 1 addition & 1 deletion src/commands/dev/dev.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import {
getNetlifyGraphConfig,
readGraphQLOperationsSourceFile,
} from '../../lib/one-graph/cli-netlify-graph.mjs'
import { startSpinner, stopSpinner } from '../../lib/spinner.cjs'
import { startSpinner, stopSpinner } from '../../lib/spinner.mjs'
import {
BANG,
chalk,
Expand Down
60 changes: 35 additions & 25 deletions src/commands/functions/functions-create.mjs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
// @ts-check
import cp from 'child_process'
import fs from 'fs'
import { mkdir } from 'fs/promises'
import { mkdir, readdir, unlink } from 'fs/promises'
import { createRequire } from 'module'
import path, { dirname } from 'path'
import process from 'process'
import { fileURLToPath } from 'url'
import { fileURLToPath, pathToFileURL } from 'url'
import { promisify } from 'util'

import copyTemplateDirOriginal from 'copy-template-dir'
Expand All @@ -16,6 +16,7 @@ import inquirerAutocompletePrompt from 'inquirer-autocomplete-prompt'
import fetch from 'node-fetch'
import ora from 'ora'

import { fileExistsAsync } from '../../lib/fs.mjs'
import { getAddons, getCurrentAddon, getSiteData } from '../../utils/addons/prepare.mjs'
import { NETLIFYDEVERR, NETLIFYDEVLOG, NETLIFYDEVWARN, chalk, error, log } from '../../utils/command-helpers.mjs'
import { injectEnvVariables } from '../../utils/dev.mjs'
Expand Down Expand Up @@ -90,19 +91,26 @@ const filterRegistry = function (registry, input) {
})
}

const formatRegistryArrayForInquirer = function (lang, funcType) {
const folderNames = fs.readdirSync(path.join(templatesDir, lang))
const registry = folderNames
// filter out markdown files
.filter((folderName) => !folderName.endsWith('.md'))
const formatRegistryArrayForInquirer = async function (lang, funcType) {
const folderNames = await readdir(path.join(templatesDir, lang))

.map((folderName) =>
// eslint-disable-next-line import/no-dynamic-require
require(path.join(templatesDir, lang, folderName, '.netlify-function-template.cjs')),
)
.filter((folderName) => folderName.functionType === funcType)
.sort((folderNameA, folderNameB) => {
const priorityDiff = (folderNameA.priority || DEFAULT_PRIORITY) - (folderNameB.priority || DEFAULT_PRIORITY)
const imports = await Promise.all(
folderNames
// filter out markdown files
.filter((folderName) => !folderName.endsWith('.md'))
.map(async (folderName) => {
const templatePath = path.join(templatesDir, lang, folderName, '.netlify-function-template.mjs')
// eslint-disable-next-line import/no-dynamic-require
const template = await import(pathToFileURL(templatePath))

return template.default
}),
)

const registry = imports
.filter((template) => template.functionType === funcType)
.sort((templateA, templateB) => {
const priorityDiff = (templateA.priority || DEFAULT_PRIORITY) - (templateB.priority || DEFAULT_PRIORITY)

if (priorityDiff !== 0) {
return priorityDiff
Expand All @@ -112,7 +120,7 @@ const formatRegistryArrayForInquirer = function (lang, funcType) {
// until Node 11, so the original sorting order from `fs.readdirSync`
// was not respected. We can simplify this once we drop support for
// Node 10.
return folderNameA - folderNameB
return templateA - templateB
})
.map((t) => {
t.lang = lang
Expand Down Expand Up @@ -170,7 +178,7 @@ const pickTemplate = async function ({ language: languageFromFlag }, funcType) {
let templatesForLanguage

try {
templatesForLanguage = formatRegistryArrayForInquirer(language, funcType)
templatesForLanguage = await formatRegistryArrayForInquirer(language, funcType)
} catch {
throw error(`Invalid language: ${language}`)
}
Expand Down Expand Up @@ -292,14 +300,14 @@ const ensureFunctionDirExists = async function (command) {
}
}

if (!fs.existsSync(functionsDirHolder)) {
if (!(await fileExistsAsync(functionsDirHolder))) {
log(
`${NETLIFYDEVLOG} functions directory ${chalk.magenta.inverse(
functionsDirHolder,
)} does not exist yet, creating it...`,
)

fs.mkdirSync(functionsDirHolder, { recursive: true })
await mkdir(functionsDirHolder, { recursive: true })

log(`${NETLIFYDEVLOG} functions directory ${chalk.magenta.inverse(functionsDirHolder)} created`)
}
Expand Down Expand Up @@ -350,15 +358,17 @@ const downloadFromURL = async function (command, options, argumentName, function
})

// read, execute, and delete function template file if exists
const fnTemplateFile = path.join(fnFolder, '.netlify-function-template.cjs')
if (fs.existsSync(fnTemplateFile)) {
// eslint-disable-next-line import/no-dynamic-require
const { onComplete, addons = [] } = require(fnTemplateFile)
const fnTemplateFile = path.join(fnFolder, '.netlify-function-template.mjs')
if (await fileExistsAsync(fnTemplateFile)) {
const {
default: { onComplete, addons = [] },
// eslint-disable-next-line import/no-dynamic-require
} = await import(pathToFileURL(fnTemplateFile).href)

await installAddons(command, addons, path.resolve(fnFolder))
await handleOnComplete({ command, onComplete })
// delete
fs.unlinkSync(fnTemplateFile)
await unlink(fnTemplateFile)
}
}

Expand Down Expand Up @@ -471,7 +481,7 @@ const scaffoldFromTemplate = async function (command, options, argumentName, fun

// These files will not be part of the log message because they'll likely
// be removed before the command finishes.
const omittedFromOutput = new Set(['.netlify-function-template.cjs', 'package.json', 'package-lock.json'])
const omittedFromOutput = new Set(['.netlify-function-template.mjs', 'package.json', 'package-lock.json'])
const createdFiles = await copyTemplateDir(pathToTemplate, functionPath, vars)
createdFiles.forEach((filePath) => {
const filename = path.basename(filePath)
Expand All @@ -487,7 +497,7 @@ const scaffoldFromTemplate = async function (command, options, argumentName, fun
})

// delete function template file that was copied over by copydir
fs.unlinkSync(path.join(functionPath, '.netlify-function-template.cjs'))
await unlink(path.join(functionPath, '.netlify-function-template.mjs'))

// npm install
if (functionPackageJson !== undefined) {
Expand Down
2 changes: 1 addition & 1 deletion src/commands/sites/sites-list.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @ts-check
import { listSites } from '../../lib/api.mjs'
import { startSpinner, stopSpinner } from '../../lib/spinner.cjs'
import { startSpinner, stopSpinner } from '../../lib/spinner.mjs'
import { chalk, log, logJson } from '../../utils/command-helpers.mjs'

/**
Expand Down
2 changes: 1 addition & 1 deletion src/commands/watch/watch.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import pWaitFor from 'p-wait-for'
import prettyjson from 'prettyjson'

import { startSpinner, stopSpinner } from '../../lib/spinner.cjs'
import { startSpinner, stopSpinner } from '../../lib/spinner.mjs'
import { chalk, error, log } from '../../utils/command-helpers.mjs'
import { init } from '../init/index.mjs'

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'hello-world',
priority: 1,
description: 'Basic function that shows how to create a handler and return a response',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'apollo-graphql-rest',
description: 'GraphQL function to wrap REST API using apollo-server-lambda and apollo-datasource-rest!',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'apollo-graphql',
description: 'GraphQL function using Apollo-Server-Lambda!',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'auth-fetch',
description: 'Use `node-fetch` library and Netlify Identity to access APIs',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'create-user',
description: 'Programmatically create a Netlify Identity user by invoking a function',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const execa = require('execa')
module.exports = {
import execa from 'execa'

export default {
name: 'fauna-crud',
description: 'CRUD function using Fauna DB',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const execa = require('execa')
module.exports = {
import execa from 'execa'

export default {
name: 'fauna-graphql',
description: 'GraphQL Backend using Fauna DB',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'google-analytics',
description: 'Google Analytics: proxy for GA on your domain to avoid adblock',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'graphql-gateway',
description: 'Apollo Server Lambda Gateway stitching schemas from other GraphQL Functions!',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'hasura-event-triggered',
description: 'Hasura Cleaning: process a Hasura event and fire off a GraphQL mutation with processed text data',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'hello-world',
priority: 1,
description: 'Basic function that shows async/await usage, and response formatting',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'hello',
description: 'Basic function that shows async/await usage, and response formatting',
functionType: 'edge',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'identity-signup',
description: 'Identity Signup: Triggered when a new Netlify Identity user confirms. Assigns roles and extra metadata',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'image-external',
description: 'Fetches and serves an image from an external site',
functionType: 'edge',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'localized-content',
description: 'Uses geolocation data to serve localized countent according to country code',
functionType: 'edge',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'node-fetch',
description: 'Fetch function: uses node-fetch to hit an external API without CORS issues',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'oauth-passport',
description: 'oauth-passport: template for Oauth workflow using Passport + Express.js',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'protected-function',
description: 'Function protected Netlify Identity authentication',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'sanity-create',
description: 'Create documents in Sanity.io',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'sanity-groq',
description: 'Query a Sanity.io dataset with GROQ',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'scheduled-function',
priority: 1,
description: 'Basic implementation of a scheduled function in JavaScript.',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'send-email',
description: "Send Email: Send email with no SMTP server via 'sendmail' pkg",
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'serverless-ssr',
description: 'Dynamic serverside rendering via functions',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'set-cookie',
description: 'Set a cookie alongside your function',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'set-cookies',
description: 'Create and manage HTTP cookies',
functionType: 'edge',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'set-req-header',
description: 'Adds a custom HTTP header to HTTP request.',
functionType: 'edge',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'set-res-header',
description: 'Adds a custom HTTP header to HTTP response.',
functionType: 'edge',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'slack-rate-limit',
description: 'Slack Rate-limit: post to Slack, at most once an hour, using Netlify Identity metadata',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const chalk = require('chalk')
import chalk from 'chalk'

module.exports = {
export default {
name: 'stripe-charge',
description: 'Stripe Charge: Charge a user with Stripe',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const chalk = require('chalk')
import chalk from 'chalk'

module.exports = {
export default {
name: 'stripe-subscription',
description: 'Stripe subscription: Create a subscription with Stripe',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'submission-created',
description: 'submission-created: template for event triggered function when a new Netlify Form is submitted',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const chalk = require('chalk')
import chalk from 'chalk'

module.exports = {
export default {
name: 'token-hider',
description: 'Token Hider: access APIs without exposing your API keys',
functionType: 'serverless',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
export default {
name: 'transform-response',
description: 'Transform the content of an HTTP response',
functionType: 'edge',
Expand Down
Loading