') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); Merge staging to master by aman19K · Pull Request #53 · contentstack/contentstack-cli-tsgen · GitHub
Skip to content
This repository was archived by the owner on Aug 21, 2026. It is now read-only.
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
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
{
"name": "contentstack-cli-tsgen",
"description": "Generate TypeScript typings from a Stack.",
"version": "2.1.7",
"version": "2.1.8",
"author": "Michael Davis",
"bugs": "https://github.com/Contentstack-Solutions/contentstack-cli-tsgen/issues",
"dependencies": {
Expand Down
8 changes: 7 additions & 1 deletion src/commands/tsgen.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -51,6 +51,11 @@ export default class TypeScriptCodeGeneratorCommand extends Command {
hidden: false,
multiple: false,
}),

'include-system-fields': flags.boolean({
description: 'include system fields in generated types',
default: false,
}),
};

async run() {
Expand All@@ -62,6 +67,7 @@ export default class TypeScriptCodeGeneratorCommand extends Command {
const includeDocumentation = flags.doc
const outputPath = flags.output
const branch = flags.branch
const includeSystemFields = flags['include-system-fields']

if (token.type !== 'delivery') {
this.warn('Possibly using a management token. You may not be able to connect to your Stack. Please use a delivery token.')
Expand DownExpand Up@@ -91,7 +97,7 @@ export default class TypeScriptCodeGeneratorCommand extends Command {
}))
}
schemas = schemas.concat(client.types)
const result = await tsgenRunner(outputPath, schemas, prefix, includeDocumentation)
const result = await tsgenRunner(outputPath, schemas, prefix, includeDocumentation, includeSystemFields)
this.log(`Wrote ${result.definitions} Content Types to '${result.outputPath}'.`)
} else {
this.log('No Content Types exist in the Stack.')
Expand Down
72 changes: 47 additions & 25 deletions src/lib/stack/builtins.ts
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,52 @@
// File and Link fields are additional, non-scalar, data types within a stack.
export const defaultInterfaces = (prefix = '') => [
`export interface ${prefix}File {
uid: string;
created_at: string;
updated_at: string;
created_by: string;
updated_by: string;
content_type: string;
file_size: string;
tags: string[];
filename: string;
url: string;
ACL: any[];
is_dir: boolean;
parent_uid: string;
_version: number;
title: string;
publish_details: {
export const defaultInterfaces = (prefix = '', systemFields = false) => {
const defaultInterfaces = [
`export interface ${prefix}PublishDetails {
environment: string;
locale: string;
time: string;
user: string;
};
}`,
`export interface ${prefix}Link {
title: string;
href: string;
}`,
]
}`,
`export interface ${prefix}File {
uid: string;
created_at: string;
updated_at: string;
created_by: string;
updated_by: string;
content_type: string;
file_size: string;
tags: string[];
filename: string;
url: string;
ACL: any[];
is_dir: boolean;
parent_uid: string;
_version: number;
title: string;
publish_details: ${prefix}PublishDetails;
}`,
`export interface ${prefix}Link {
title: string;
href: string;
}`
]
if (systemFields) {
defaultInterfaces.push(
`export interface ${prefix}SystemFields {
uid?: string;
created_at?: string;
updated_at?: string;
created_by?: string;
updated_by?: string;
_content_type_uid?: string;
tags?: string[];
ACL?: any[];
_version?: number;
_in_progress?: boolean;
locale?: string;
publish_details?: ${prefix}PublishDetails[];
title?: string;
}`)
}
return defaultInterfaces;
}
8 changes: 7 additions & 1 deletion src/lib/stack/schema.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@ export type Block = {
export type GlobalField = {
reference_to: string;
schema: Schema;
schema_type?: string;
_version?: number
} & FieldOptions;

Expand All@@ -50,7 +51,8 @@ export type Field = GlobalField &
ReferenceField &
GroupField &
EnumField &
BlockField;
BlockField &
{ field_metadata: FieldMetaData };
export type Schema = Array<Field>;

export type ContentType = {
Expand All@@ -61,3 +63,7 @@ export type ContentType = {
data_type?: string;
schema_type?: string;
} & Identifier;

export type FieldMetaData = {
ref_multiple?: boolean;
}
15 changes: 11 additions & 4 deletions src/lib/tsgen/factory.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,7 @@ export type TSGenOptions = {
naming?: {
prefix: string;
};
systemFields?: boolean;
};

export type TSGenResult = {
Expand DownExpand Up@@ -54,6 +55,7 @@ const defaultOptions: TSGenOptions = {
naming: {
prefix: '',
},
systemFields: false
}

export default function (userOptions: TSGenOptions) {
Expand DownExpand Up@@ -115,9 +117,14 @@ export default function (userOptions: TSGenOptions) {
}

function define_interface(
contentType: ContentstackTypes.ContentType | ContentstackTypes.GlobalField
contentType: ContentstackTypes.ContentType | ContentstackTypes.GlobalField,
systemFields = false
) {
return ['export interface', name_type(contentType.data_type === 'global_field' ? (contentType.reference_to as string) : contentType.uid)].join(' ')
const interface_declaration = ['export interface', name_type(contentType.data_type === 'global_field' ? (contentType.reference_to as string) : contentType.uid)]
if (systemFields && contentType.schema_type !== "global_field") {
interface_declaration.push('extends', name_type('SystemFields'))
}
return interface_declaration.join(' ')
}

function op_array(type: string, field: ContentstackTypes.Field) {
Expand DownExpand Up@@ -226,7 +233,7 @@ export default function (userOptions: TSGenOptions) {
) {
return [
options.docgen.interface(contentType.description),
define_interface(contentType),
define_interface(contentType, options.systemFields),
'{',
['/**', "Version", '*/'].join(' '),
[`version: `,contentType._version,';'].join(' '),
Expand DownExpand Up@@ -302,7 +309,7 @@ export default function (userOptions: TSGenOptions) {
references.push(name_type(field.reference_to))
}

return ['(', references.join(' | '), ')', '[]'].join('')
return ['(', references.join(' | '), ')', field.field_metadata?.ref_multiple ? '[]' : ''].join('')
}

return function (contentType: ContentstackTypes.ContentType): TSGenResult|any {
Expand Down
5 changes: 3 additions & 2 deletions src/lib/tsgen/runner.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ function createOutputPath(outputFile: string) {
return outputPath
}

export default async function tsgenRunner(outputFile: string, contentTypes: any[], prefix = '', includeDocumentation = true) {
export default async function tsgenRunner(outputFile: string, contentTypes: any[], prefix = '', includeDocumentation = true, systemFields = false) {
const docgen: DocumentationGenerator = includeDocumentation ? new JSDocumentationGenerator() : new NullDocumentationGenerator()

const outputPath = createOutputPath(outputFile)
Expand All@@ -38,6 +38,7 @@ export default async function tsgenRunner(outputFile: string, contentTypes: any[
naming: {
prefix,
},
systemFields
})

for (const contentType of contentTypes) {
Expand All@@ -56,7 +57,7 @@ export default async function tsgenRunner(outputFile: string, contentTypes: any[

const output = await format(
[
defaultInterfaces(prefix).join('\n\n'),
defaultInterfaces(prefix, systemFields).join('\n\n'),
[...globalFields].join('\n\n'),
definitions.join('\n\n'),
].join('\n\n')
Expand Down
34 changes: 17 additions & 17 deletions tests/tsgen/references.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,37 @@
const testData = require('./references.ct')
const testData = require("./references.ct");

import NullDocumentationGenerator from '../../src/lib/tsgen/docgen/nulldoc'
import tsgenFactory from '../../src/lib/tsgen/factory'
import NullDocumentationGenerator from "../../src/lib/tsgen/docgen/nulldoc";
import tsgenFactory from "../../src/lib/tsgen/factory";

const tsgen = tsgenFactory({
docgen: new NullDocumentationGenerator(),
naming: {
prefix: 'I',
prefix: "I",
},
})
});

describe('references', () => {
const result = tsgen(testData.references)
describe("references", () => {
const result = tsgen(testData.references);

test('metadata', () => {
const contentTypes = [...result.metadata.dependencies.contentTypes]
test("metadata", () => {
const contentTypes = [...result.metadata.dependencies.contentTypes];

expect(contentTypes).toEqual(
expect.arrayContaining(['IReferenceChild', 'IBoolean', 'IBuiltinExample'])
)
})
expect.arrayContaining(["IReferenceChild", "IBoolean", "IBuiltinExample"])
);
});

test('definition', () => {
test("definition", () => {
expect(result.definition).toMatchInlineSnapshot(`
"export interface IReferenceParent
{
/** Version */
version: 5 ;
title: string;
url: string;
single_reference: (IReferenceChild)[];
single_reference: (IReferenceChild);
multiple_reference?: (IReferenceChild | IBoolean | IBuiltinExample)[];
}"
`)
})
})
`);
});
});