Skip to content

Commit

Permalink
Merge branch 'main' into fix/video-length
Browse files Browse the repository at this point in the history
  • Loading branch information
killij authored Nov 15, 2023
2 parents c5b73c1 + 59581c3 commit fe8939b
Show file tree
Hide file tree
Showing 9 changed files with 7,299 additions and 494 deletions.
1 change: 1 addition & 0 deletions Contentful-Schema/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**\dist
7,464 changes: 6,972 additions & 492 deletions Contentful-Schema/package-lock.json

Large diffs are not rendered by default.

14 changes: 12 additions & 2 deletions Contentful-Schema/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,19 @@
"author": "",
"license": "ISC",
"dependencies": {
"boxen": "^7.1.1",
"chalk": "^5.3.0",
"contentful-cli": "^3.1.14",
"contentful-management": "^11.5.1",
"inquirer": "^9.2.12"
"inquirer": "^9.2.12",
"listr2": "^7.0.2",
"yargs": "^17.7.2"
},
"type": "module"
"type": "module",
"devDependencies": {
"@types/inquirer": "^9.0.7",
"@types/node": "^20.9.0",
"@types/yargs": "^17.0.31",
"typescript": "^5.2.2"
}
}
99 changes: 99 additions & 0 deletions Contentful-Schema/src/scripts/resyncEditorInterface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { Listr } from "listr2"
import boxen from "boxen"
import yargs from "yargs"
import { hideBin } from "yargs/helpers"

import { ContentfulContext } from '../tasks/contentfulSetupTask.js'
import { contentfulSetupTask } from '../tasks/contentfulSetupTask.js'
import chalk from "chalk"
import { ContentType } from "contentful-management"
import { getMismatchedContentTypesTask } from "../tasks/getMismatchedContentTypesTask.js"
import { fixMismatchedContentTypesTask } from "../tasks/fixMismatchedContentTypesTask.js"

console.log(boxen(chalk.whiteBright("Resynchronise an EditorInterface Controls with the order of its the Content Types Fields"), {padding: 1}));

const argv = await yargs(hideBin(process.argv))
.usage('Usage: $0 [options]')
.describe("t", "Contentful management API token")
.alias("t", "management-token")
.describe("s", "ID of the destination space ")
.alias("s", "space")
.describe("e", "ID the environment in the destination space")
.alias("e", "environment")
.describe("o", "Change the output format")
.alias("o", "output-format")
.choices('o', ["default", "simple"])
.default("o", "default")
.help(false)
.version(false)
.demandOption(["t", "s", "e"])
.argv;

// const argv = {
// t: process.env.CONTENTFUL_MANAGEMENT_ACCESS_TOKEN,
// s: process.env.CPD_SPACE_ID,
// e: "dev",
// o: "default",
// }

interface MainContext {
contentfulCtx: ContentfulContext
contentTypes: ContentType[]
}

console.log(chalk.whiteBright(`Space is ${chalk.yellowBright(argv.s)}`))
console.log(chalk.whiteBright(`Environment is ${chalk.yellowBright(argv.e)}`))

const ctx: MainContext = {
contentfulCtx: {
params: {
managementToken: argv.t as string,
space: argv.s as string,
environment: argv.e as string
}
},
contentTypes: []
}


const tasks = new Listr<MainContext>(
[
{
task: (ctx, task): Listr => {
return task.newListr<ContentfulContext>(
[ contentfulSetupTask ],
{ ctx : ctx.contentfulCtx}
)
}
},
{
task: (ctx, task): Listr => {
return task.newListr<MainContext>(
[ getMismatchedContentTypesTask ],
{ ctx }
)
},
exitOnError: false
},
{
skip: (ctx): boolean => ctx.contentTypes.length === 0,
task: (ctx, task): Listr => {
return task.newListr<MainContext>(
[ fixMismatchedContentTypesTask ],
{ ctx }
)
}
}
],
{
concurrent: false,
ctx,
renderer: argv.o as string
}
)

try {
await tasks.run()
} catch (e) {
console.error(e)
}
28 changes: 28 additions & 0 deletions Contentful-Schema/src/tasks/contentfulSetupTask.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import contentful, { ClientAPI, Environment, Space } from 'contentful-management'

export interface ContentfulParams {
managementToken: string
space: string
environment: string
}

export interface ContentfulContext {
params: ContentfulParams
client?: ClientAPI
space?: Space
environment?: Environment
}

export const contentfulSetupTask = {
title: "Initiating Contentful",
task: async (ctx: ContentfulContext, task: any): Promise<void> => {
task.output = "Create Contentful client"
ctx.client = contentful.createClient({ accessToken: ctx.params.managementToken })

task.output = "Fetching space"
ctx.space = await ctx.client.getSpace(ctx.params.space)

task.output = "Fetching environment"
ctx.environment = await ctx.space.getEnvironment(ctx.params.environment)
}
}
35 changes: 35 additions & 0 deletions Contentful-Schema/src/tasks/fixMismatchedContentTypesTask.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { ContentType } from 'contentful-management'
import { delay } from 'listr2'
import { ContentfulContext } from './contentfulSetupTask.js'
import chalk from 'chalk'

interface ResyncContext {
contentfulCtx : ContentfulContext
contentTypes : ContentType[]
}

export const fixMismatchedContentTypesTask = {
title: "Resyncing Content Types EditorInterface Controls to Fields",
task: async (ctx: ResyncContext, task: any): Promise<void> => {
for (const contentType of ctx.contentTypes) {
const fields = contentType.fields
const editorInterface = await contentType.getEditorInterface()
const controls = editorInterface.controls!;

task.output = `Fixing ${chalk.yellowBright(contentType.sys.id)} (${contentType.name})`
let newControls = []

for (let index=0; index<fields.length; index++) {
var field = fields[index]
var control = controls.find(x => x.fieldId === field.id)
if (!control) {
throw new Error(`${chalk.redBright("Error:")} could not find control for field ${chalk.yellowBright(field.id)}`)
}
newControls.push(control)
}
editorInterface.controls = newControls;
await editorInterface.update()
await delay(200)
}
}
}
43 changes: 43 additions & 0 deletions Contentful-Schema/src/tasks/getMismatchedContentTypesTask.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { ContentType } from 'contentful-management'
import { delay } from 'listr2'
import { ContentfulContext } from './contentfulSetupTask.js'
import chalk from 'chalk'

interface ResyncContext {
contentfulCtx : ContentfulContext
contentTypes : ContentType[]
}

export const getMismatchedContentTypesTask = {
title: "Verifying Content Model EditorInterface Controls order matches that of the Fields ",
task: async (ctx: ResyncContext, task: any): Promise<void> => {
const contentTypes = await ctx.contentfulCtx.environment!.getContentTypes()
for (const contentType of contentTypes.items) {
task.output = `Checking ${chalk.yellowBright(contentType.sys.id)} (${contentType.name})`

const fields = contentType.fields;
const editorInterface = await contentType.getEditorInterface()
const controls = editorInterface.controls

if (fields.length != controls?.length) {
throw new Error(`${chalk.redBright("Error:")} Content Type ${chalk.yellowBright(contentType.sys.id)} has a mismatchc between the number of fields and number of editor controls`)
}

for (let index=0; index<fields.length; index++) {
const field = fields[index]
const control = controls[index]

if (field.id !== control.fieldId) {
ctx.contentTypes.push(contentType)
break;
}
}

await delay(200)
}

if (ctx.contentTypes.length > 0) {
throw new Error(chalk.redBright("Mismatched Content Types detected"))
}
}
}
109 changes: 109 additions & 0 deletions Contentful-Schema/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */

/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */

/* Language and Environment */
"target": "ES2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */

/* Modules */
"module": "NodeNext", /* Specify what module code is generated. */
"rootDir": "./src", /* Specify the root folder within your source files. */
"moduleResolution": "NodeNext", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
//"sourceMap": true, /* Create source map files for emitted JavaScript files. */
"inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */

/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */

/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}

0 comments on commit fe8939b

Please sign in to comment.