import { Request as Request$1, Response, NextFunction } from 'express'; export { NextFunction, Response } from 'express'; import { Auth } from 'googleapis'; import * as _google_cloud_datastore_build_src_request from '@google-cloud/datastore/build/src/request'; import { Datastore } from '@google-cloud/datastore'; import { Operator } from '@google-cloud/datastore/build/src/query'; import { entity } from '@google-cloud/datastore/build/src/entity'; import nunjucks from 'nunjucks'; import * as yaml from 'js-yaml'; /** * Request-aware context, e.g. for identifying the current user. */ declare class RequestContext { readonly pod: Pod; readonly req: Request$1; readonly cache: Map; private cachedUser?; private logger; private logEntries; constructor(pod: Pod, req: Request$1); /** * Returns the current user's email address, if logged in. * * NOTE: this is intentionally marked as `async` since we may want to verify * the JWT assertion in the future. See: * https://cloud.google.com/nodejs/getting-started/authenticate-users */ user(): Promise; /** Returns an OAuth2 refresh token for the logged in user. */ getOAuthToken(): Promise<{ refreshToken: string; } | null>; /** Resets the OAuth2 token for the logged in user. */ resetOAuthToken(): Promise; getOAuthLoginUrl(): Promise; getOAuthClient(): Promise; authorizeOAuthToken(code: string): Promise; private getOAuthRedirectUrl; isCron(): boolean; log(data: any): void; isAuthorized(email: string | null): boolean; writeLogs(): Promise; } /** * A provider provides some data to a template. */ interface Provider { pod: Pod; get(ctx: RequestContext, options: any): Promise; } /** * TemplateInjector are a way to inject data into a templates. Useful for, for * example, injecting other documents or for document list pages. */ interface TemplateInjector { id: string; provider: string; options: any; } interface Field { id: string; type: string; label?: string; help?: string; variant?: string; types?: string[]; repeated?: boolean; previewField?: string | string[]; fields?: Field[]; options?: Array<{ value: string; label?: string; }>; } interface Schema { fields: Field[]; types?: Record; template?: string; inject?: TemplateInjector[]; hidden?: boolean; experimentalLayout?: any; orderBy?: string; } declare type DefineSchemaType = Schema | ((pod: Pod) => Schema); declare function defineSchema(config: DefineSchemaType): DefineSchemaType; declare function loadSchema(pod: Pod, podPath: string): Schema; declare type CustomRouteHandler = (ctx: RequestContext, req: Request$1, res: Response) => Promise | void; /** * Base class for route objects. */ declare class Route { locale: string; setLocale(locale: string): void; } /** * A route that contains a redirect. */ declare class RedirectRoute extends Route { private readonly redirectUrlWithParams; private readonly code; constructor(code: number, redirectUrlWithParams: string); getRedirect(params: Record): [number, string]; } /** * A route to a static file. */ declare class StaticRoute extends Route { private readonly staticPathWithParams; constructor(staticPathWithParams: string); getStaticPath(params: Record): string; } /** * A route mapped to a collection. */ declare class CollectionRoute extends Route { readonly collectionId: string; constructor(collectionId: string); } /** * A route mapped to a document. */ declare class DocumentRoute extends Route { readonly docId: string; constructor(docId: string); } /** * A route mapped to a {@link YamlPage}. */ declare class YamlPageRoute extends Route { readonly yamlPathWithParams: string; constructor(yamlPath: string); getYamlPath(params: Record): string; } /** * A trie data structure that stores routes. The trie supports `:param` and * `*wildcard` values. */ declare class RouteTrie { private children; private paramChild?; private wildcardChild?; private route?; /** * Adds a route to the trie. */ add(path: string, route: Route): void; /** * Returns a route mapped to the given path and any parameter values from the * URL. */ get(path: string): [Route | undefined, Record]; /** * Walks the route trie and calls a callback function for each route. */ walk(cb: (path: string, route: Route) => void): void; private getRoute; /** * Normalizes a path for inclusion into the route trie. */ private normalizePath; /** * Splits the parent directory from its children, e.g.: * * splitPath("foo/bar/baz") -> ["foo", "bar/baz"] */ private splitPath; } /** * Schema for data stored in OakDB. */ interface DBEntity { [key: string]: any; path: string; dir: string; subdirs: string[]; value: any; modifiedAt: string; modifiedBy: string; docId?: string; collectionId?: string; locales?: string[]; draft?: boolean; draftOrPublished?: boolean; publishedAt?: string; publishedOrModifiedAt?: string; scheduled?: boolean; scheduledDeployAt?: string; } /** * Schema for OakDB versioning. */ interface VersionEntity { [key: string]: any; path: string; value: any; modifiedAt: string; modifiedBy: string; } /** * Filter type for filtering the DB entries. Example filters should look * something like: * * ['myfield', 'somevalue'] * ['myfield', '=', 'somevalue'] * ['somedate', '>', '2020-01-01T00:00'] */ declare type ListFilter = [string, any] | [string, Operator, any]; /** * Options for {@link OakDB.list()}. */ interface ListOptions { recursive?: boolean; filters?: ListFilter[]; offset?: number; limit?: number; orderBy?: string; locale?: string; } /** * Interface for a hook to subscribe to events in {@link OakDB}. */ interface OakDBHook { prePutHook?: (ent: DBEntity) => void; postPutHook?: (ent: DBEntity) => void; deleteHook?: (key: string) => void; } /** * OakDB is a key-value storage system for Oak. Keys are stored in a folder-like * way and values are simply stored as JSON data. */ declare class OakDB { readonly datastore: Datastore; private readonly pod; private readonly hooks; constructor(pod: Pod); /** * Retrieves the underlying entity for a key, which contains its stored JSON * value as well as metadata such as the username that modified it and when * it was modified. */ getEntity(ctx: RequestContext, key: string): Promise; /** * Returns the JSON value stored at a given key. */ get(ctx: RequestContext, key: string): Promise; /** * Sets a JSON value for a key. */ set(ctx: RequestContext, key: string, value: any, options?: { metadata: any; }): Promise; /** * Lists the keys in a folder. */ list(ctx: RequestContext, dirname: string | string[], options?: ListOptions): Promise; /** * Deletes the value stored at a given key. */ delete(ctx: RequestContext, key: string): Promise; /** * Batch delete keys. */ deleteMulti(ctx: RequestContext, keys: string[]): Promise; /** * Returns all the intermediate dirs for a path, e.g.: * * subdirs("foo/bar/baz") -> ["foo", "foo/bar"] */ subdirs(key: string): string[]; /** * Adds a hook that individual projects can use to add additional * functionality (such as filter data) to entities as they are written. */ addHook(hook: OakDBHook): void; /** * Adds a version of a DB entry. Multiple consecutive writes are batched into * a single version. */ addVersion(ent: DBEntity): Promise<_google_cloud_datastore_build_src_request.CommitResponse>; /** * Retrieves a particular version of an entry. */ getVersion(path: string, versionId: string | number | entity.Int): Promise; /** * Retrieves the latest versions for a given DB path. */ listVersions(path: string, options?: { limit?: number; }): Promise; datastoreKey(key: string, ...childPaths: Array): entity.Key; } interface YamlPageYaml { template: string; fields: any; inject?: TemplateInjector[]; locales: string[]; } interface PageRenderOptions { locale: string; locales: string[]; env: string; } /** * YamlPage is a page that can be rendered via yaml file. */ declare class YamlPage { readonly pod: Pod; readonly yamlPath: string; readonly yaml: YamlPageYaml; constructor(pod: Pod, yamlPath: string); get fields(): any; get locales(): string[]; get slug(): string; get template(): string; /** * Renders the yaml page. */ render(ctx: RequestContext, options: PageRenderOptions): Promise; /** * Returns the canonical URL for the yaml page or null if the page is not * mapped to any paths. */ getUrl(locale?: string): string | null; /** * An alias for {@link getUrl}. */ getLocalizedUrl(locale: string): string | null; } /** The YAML structure for oakspec.yaml. */ interface Podspec { [key: string]: unknown; name?: string; gcpProject: string; routes: PodspecRoute[]; localization: PodspecLocalization; timezone: string; gciBackend?: string; auth?: PodspecAuth; trailingSlash?: 'always' | 'never'; collectionsPath?: string; } interface PodspecAuth { orgs: string[]; } interface PodspecRoute { [key: string]: unknown; path: string; doc?: string; collection?: string; yaml?: string; redirect?: string; code?: number; staticPath?: string; localized?: boolean; } interface PodspecLocalization { [key: string]: unknown; path: string; locales: string[]; defaultLocale?: string; fallbacks?: Record; mode?: 'inherit'; } interface PodOptions { mode?: 'dev' | 'prod'; oakspecPath?: string; } interface ScheduledDeploy { docId: string; scheduledDeployAt: string; data: any; } interface OAuth2Settings { clientId: string; clientSecret: string; } /** * The pod centralizes all operations related to the project, including * configurations, getting collections and documents, storing routes, etc. */ declare class Pod { readonly root: string; readonly podspec: Podspec; readonly routes: RouteTrie; readonly options: PodOptions; private oakDB?; private readonly engines; private readonly providers; constructor(root: string, options?: PodOptions); get mode(): 'dev' | 'prod'; get oakspecPath(): string; get collectionsPath(): string; initOakConfig(): void; getGcpProject(): string; /** * Returns a {@link Document} from the pod. */ doc(docId: string): Document; /** * Returns a {@link Collection} from the pod. */ collection(collectionId: string): Collection; /** * Alias for {@link readJson}. */ json(podPath: string): any; /** * Alias for {@link readJson}. */ readJson(podPath: string): any; /** * Writes JSON to a pod path. */ writeJson(podPath: string, data: any): void; /** * Returns a {@link YamlPage} from the pod. */ yamlPage(yamlPath: string): YamlPage; /** * Alias for {@link readYaml()}. */ yaml(podPath: string): any; /** * Reads a yaml file from the pod. */ readYaml(podPath: string): any; /** * Reads a file on a given pod path. */ readFile(podPath: string): string; /** * Writes a file to a pod path. */ writeFile(podPath: string, content: string, options?: { encoding?: 'utf8' | 'utf-8' | 'binary'; }): void; partial(partialId: string): { id: string; fields: Field[]; types: Record; }; /** * Returns the path for a file in the pod. */ getFilePath(podPath: string): string; /** * Returns true if the file exists in the pod. */ fileExists(podPath: string): boolean; /** * Adds a custom route to the route trie. */ addCustomRoute(path: string, handler: CustomRouteHandler): void; /** * Adds an engine to the pod. */ addEngine(name: string, engine: any): void; /** * Returns an engine. */ getEngine(name: string): any | null; /** * Returns an OakDB object. */ db(): OakDB; listCollections(): string[]; listDocs(ctx: RequestContext, collectionId: string, options?: { filters?: ListFilter[]; offset?: number; limit?: number; orderBy?: string; locale?: string; }): Promise; collectionScheduledDeploys(ctx: RequestContext, collectionId: string): Promise; publishScheduledDeploys(ctx: RequestContext): Promise; private publishScheduledDeploy; getDefaultLocale(): string; getLocales(): string[]; normalizeLocale(localeStr: string): string; getLocaleFallbacks(locale: string): string[]; loadTranslations(locale: string): Promise<{ [key: string]: string; }>; timezone(): string; getIsoTime(): string; /** * Adds a provider, which can be used to inject data into a template. */ addProvider(id: string, provider: Provider): void; /** * Returns a provider. */ getProvider(id: string): Provider | undefined; /** * Initializes routes in the route trie. */ private initRoutes; /** * Returns the localized version of a path based on the `localization.path` * property in `oakspec.yaml`. */ localizePath(path: string, locale: string): string; getOAuth2Settings(ctx: RequestContext): Promise; setOAuth2Settings(ctx: RequestContext, settings: OAuth2Settings): Promise; getL10nSettings(ctx: RequestContext): Promise; setL10nSettings(ctx: RequestContext, settings: any): Promise; } /** The configuration object for a collection. */ declare type CollectionConfig = Schema; /** * A Collection is a grouping of documents that conform to some shared type. All * documents within a collection have the same schema and are rendered by the * same template. * * Collections are defined by yaml files in the `/content/collections/` folder. */ declare class Collection { /** The project's pod. */ readonly pod: Pod; /** The name of the collection, taken from `/content/collections/{CollectionId}.yaml` */ readonly id: string; /** The collection's parsed YAML config. */ config: CollectionConfig; constructor(pod: Pod, id: string); get hidden(): boolean; /** @deprecated Use .config instead. */ get yaml(): CollectionConfig; private loadConfig; /** Returns the collection's schema definition. */ getSchema(): Schema; } interface ToArrayOptions { includeHeaders?: boolean; } /** * KeyedCsvData is a utility class for handling CSV data where rows are keyed by * a column called "key". Useful for syncing rows to a Google Sheet. * * The fields "key" and "type" are considered special column headers. The "type" * is used for converting between a cell's string value to a JavaScript type. */ declare class KeyedCsvData { private rows; private headers; constructor(); /** * Adds a row of data to the instance. */ addRow(row: any): void; /** * Returns the header row. */ getHeaders(): string[]; /** * Adds a header column. */ addHeader(header: string): void; /** * Returns the rows of data as an array of key-value pairs. */ getRows(): any[]; /** * Guesses the type of value the row is. Either "number", "string", or * "boolean". */ guessType(row: any): string; /** * Sorts the data using some compare function. */ sort(compareFn: (a: any, b: any) => number): void; /** * Returns the CSV data as an array of arrays. */ toArray(options?: ToArrayOptions): any[][]; /** * Returns a nested object representation of the CSV data. */ toNestedObject(): any; /** * Adds rows from another instance to this one. */ extend(other: KeyedCsvData): void; /** * Creates an instance of KeyedCsvData from an array of data. The input value * should be the same as what's returned from {@link KeyedCsvData.toArray}. */ static fromArray(arr: any): KeyedCsvData; /** * Creates an instance of KeyedCsvData from a nested object, e.g. document * data. * * This allows us to convert something like: * * { * en: {foo: {bar: 'en value', baz: 1}}, * de: {foo: {bar: 'de value', baz: 2}}, * } * * To a CSV like: * * [ * ['key', 'type', 'en', 'de'], * ['foo.bar', 'string', 'en value', 'de value'], * ['foo.baz', 'number', 1, 2], * ] */ static fromNestedObject(obj: any): KeyedCsvData; } /** Options for {@link Document.render}. */ interface DocumentRenderOptions { env?: 'staging' | 'prod'; locale?: string; locales?: string[]; warp?: string; } /** Options for {@link Document.publish}. */ interface DocumentPublishOptions { type: 'immediate' | 'scheduled'; scheduledDeployAt?: string; } /** Options for {@link Document.exportToCsv}. */ interface DocumentExportToCsvOptions { locales?: string[]; translateOnly?: boolean; } /** Options for {@link Document.importFromCsv}. */ interface DocumentImportFromCsvOptions { locales?: string[]; } /** The return type for {@link Document.getStatus}. */ interface DocumentStatus { publishedAt?: string; scheduledDeployAt?: string; draftModifiedAt?: string; } /** * A document hosted in Oak CMS. * * An Oak document belongs to a collection and can contain data in two different * states: draft and published. Draft data is generally rendered on staging and * requires login by end users. Published data is generally what is served live * to a public audience. * * Under the covers, a document's data is stored within {@link OakDB} under the * following keys: * * * `docs/draft/{docId}`: Draft data. * * `docs/published/{docId}`: Published data. * * `docs/scheduled/{docId}`: Scheduled data to be published some time * in the future. * * Within the body of a document, data is stored keyed by their locale values, * for example: * * { * "en": {...}, * "es": {...} * } */ declare class Document { /** The project's pod. */ readonly pod: Pod; /** The full id of the document, e.g. `BlogPost/foo`. */ readonly id: string; /** The document's collection id. */ readonly collectionId: string; /** The document's collection object. */ readonly collection: Collection; /** The document's slug identifier. */ readonly slug: string; constructor(pod: Pod, id: string); /** Saves draft data for all locales. */ save(ctx: RequestContext, data: any): Promise; /** Saves draft data for a single locale. */ saveLocale(ctx: RequestContext, locale: string, localeData: any): Promise; saveDataForLocales(ctx: RequestContext, locales: Record, enabledLocales: string[]): Promise; /** Publishes a document. */ publish(ctx: RequestContext, options?: DocumentPublishOptions): Promise; /** Deletes the document's `published` data. */ unpublish(ctx: RequestContext): Promise; /** Unschedules the document from timed deployment. */ unschedule(ctx: RequestContext): Promise; /** Deletes the document's draft data. */ revertDraft(ctx: RequestContext): Promise; /** Retrieves the document's draft data. */ getDraftData(ctx: RequestContext): Promise; /** Retrieves the document's published data. */ getPublishedData(ctx: RequestContext): Promise; /** Retrieves the document's scheduled data. */ getScheduledData(ctx: RequestContext, warp?: string): Promise; /** Deletes the document. */ delete(ctx: RequestContext): Promise; /** Deletes a locale from the document's draft data. */ deleteLocale(ctx: RequestContext, locale: string): Promise; copyTo(ctx: RequestContext, docOrId: string | Document): Promise; /** Returns the document's {@link DocumentStatus}. */ getStatus(ctx: RequestContext): Promise; /** Returns the document's schema definition from its {@link Collection}. */ getSchema(): Schema; getDataForOptions(ctx: RequestContext, options: DocumentRenderOptions): Promise; getTranslationsForOptions(ctx: RequestContext, options: DocumentRenderOptions, locale: string): Promise<{ [x: string]: string; }>; /** Renders a document. */ render(ctx: RequestContext, options: DocumentRenderOptions): Promise; /** * Returns a representation of the document that can be used in a template * context object. */ toTemplateObject(ctx: RequestContext, options: DocumentRenderOptions): Promise<{ id: string; slug: string; collection: Collection; fields: any; locale: string; locales: string[]; status: DocumentStatus; url: string | null; getLocalizedUrl: (locale: string) => string | null; }>; /** * Returns a CSV representation of the document's draft data. * * If the document doesn't have any draft data associated to it, a `null` * value is returned. */ exportToCsv(ctx: RequestContext, options?: DocumentExportToCsvOptions): Promise; getDraftTranslations(ctx: RequestContext): Promise>>; getPublishedTranslations(ctx: RequestContext): Promise>>; private translationsFromArrayMap; exportTranslations(ctx: RequestContext): Promise; /** Returns a map of {string: {locale: translation}}. */ private getGlobalStrings; /** * Converts {locale: {string: translation}} to * {string: {locale: translation}}. */ private remapTranslations; private isTranslateableField; /** * Returns the meta data for a field given a key. * * E.g.: * * getFieldData('foo.bar[0].title') * => * {"type": "string", "label": "Title"} */ private getFieldData; /** * Imports data from CSV. */ importFromCsv(ctx: RequestContext, csvData: KeyedCsvData, options?: DocumentImportFromCsvOptions): Promise; /** * Imports translations from Google Sheets. */ importTranslations(ctx: RequestContext, csvData: KeyedCsvData, options?: { locales?: string[]; overwrite?: boolean; }): Promise; /** * Imports translations from the linked Google Sheet. */ importTranslationsFromSheet(ctx: RequestContext): Promise; /** * Saves translations to draft state. The translations object should be a map * of locales to an array of source string to translated string, e.g.: * * { * "de": { * "Lorem ipsum": "DE Lorem ipsum", * } * } * * Note: The data format stored on datastore is actually a map of locale to * an array of {key: , value: string}, in order to work * around datastore limits. */ saveTranslations(ctx: RequestContext, translations: Record>): Promise; /** * Converts the following: * * {locale: {source: translation}} * * To: * * {locale: [ {key: source, value: translation} ]} * * This is used to work around issues with the way datastore indexes * properties and values. * * https://stackoverflow.com/questions/44373051/google-datastore-1500-byte-property-limit-for-embedded-entities */ private translationsToArrayMap; /** * Publishes translations to production. */ publishTranslations(ctx: RequestContext): Promise; /** * Links a spreadsheet to the document. Used for localization. */ linkSheet(ctx: RequestContext, spreadsheetId: string, gid: number): Promise; /** * Returns the linked sheet id used for localization. */ getLinkedSheet(ctx: RequestContext): Promise<{ spreadsheetId: string; gid: number; } | null>; /** * Unlinks the document from its localization sheet. */ unlinkSheet(ctx: RequestContext): Promise; /** * Returns the canonical URL for the document or null if the document is not * mapped to any paths. */ getUrl(locale?: string): string | null; /** * An alias for {@link getUrl}. */ getLocalizedUrl(locale: string): string | null; } /** @internal */ declare class NotFoundError extends Error { name: string; } declare class Template { private readonly pod; readonly id: string; readonly filePath: string; private source; private schema; constructor(pod: Pod, id: string); getSource(): string; getSchema(): Schema; } declare type Request = Request$1 & { pod: Pod; ctx: RequestContext; }; declare type RequestHandler = (req: Request, res: Response, next: NextFunction) => void | Promise; declare class ExpressEngine { readonly pod: Pod; middlewares: RequestHandler[]; constructor(pod: Pod); /** * Adds middleware to the engine. The name of this method is meant to mimic * express.use(). */ use(middleware: RequestHandler): this; } /** * Engine for rendering nunjucks files. * * Custom functionality can be added to nunjucks by adding an oak.js file to the * project root and doing something like: * * module.exports = function(pod) { * const nunjucks = pod.getEngine('nunjucks'); * nunjucks.addGlobal('customfn', () => { * // Insert functionality here. * }); * }; */ declare class NunjucksEngine { readonly pod: Pod; readonly env: nunjucks.Environment; /** A function to use for minifying rendered HTML. */ private minifier; constructor(pod: Pod); /** * Adds a filter to the environment. */ addFilter(name: string, fn: (...args: any[]) => any, async?: boolean): NunjucksEngine; /** * Adds a global to the environment. */ addGlobal(name: string, value: any): NunjucksEngine; /** * Asynchronously renders a template. */ render(template: string, context: any): Promise; /** * Sets a function to use for minifying rendered HTML. */ setHtmlMinifier(minifier: (content: string) => string | Promise): void; /** * Returns an Oak template object. */ getTemplate(template: string): Template; } /** * Engine for parsing YAML files. */ declare class YamlEngine { readonly pod: Pod; schema: yaml.Schema; constructor(pod: Pod); addType(yamlType: yaml.Type): void; addYamlType(tag: string, opts?: yaml.TypeConstructorOptions): void; load(content: string, opts?: yaml.LoadOptions): any; private getDefaultTypes; } declare function getNativeName(langCode: string): string; export { CollectionRoute, CustomRouteHandler, Document, DocumentRoute, ExpressEngine, ListFilter, NotFoundError, NunjucksEngine, OakDB, OakDBHook, Pod, Provider, RedirectRoute, Request, RequestContext, RequestHandler, Route, RouteTrie, Schema, StaticRoute, Template, YamlEngine, YamlPageRoute, defineSchema, getNativeName, loadSchema };