From 2cadd26279c56cceee60acd0ffa0f6b97433c5a4 Mon Sep 17 00:00:00 2001 From: Subhajit Ghosh <99127578+subhajit20@users.noreply.github.com> Date: Mon, 4 Sep 2023 13:28:40 +0000 Subject: [PATCH 1/5] Addred strict ts to manager-api tsconfig file --- code/lib/manager-api/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/lib/manager-api/tsconfig.json b/code/lib/manager-api/tsconfig.json index a6f65038a17b..1dc5a72190bd 100644 --- a/code/lib/manager-api/tsconfig.json +++ b/code/lib/manager-api/tsconfig.json @@ -2,7 +2,7 @@ "extends": "../../tsconfig.json", "compilerOptions": { "skipLibCheck": true, - "strict": false + "strict": true }, "include": ["src/**/*"] } From 7da257dba5e3b850a6982abf941f97d83c4d31a2 Mon Sep 17 00:00:00 2001 From: Subhajit Ghosh <99127578+subhajit20@users.noreply.github.com> Date: Mon, 4 Sep 2023 15:09:00 +0000 Subject: [PATCH 2/5] Added strict ts to manager-api tsconfig file --- code/lib/manager-api/src/lib/addons.ts | 2 +- code/lib/manager-api/src/lib/events.ts | 4 ++-- code/lib/manager-api/src/lib/shortcut.ts | 2 +- code/lib/manager-api/src/lib/stories.ts | 3 ++- code/lib/manager-api/src/tests/stories.test.ts | 4 ++-- 5 files changed, 8 insertions(+), 7 deletions(-) diff --git a/code/lib/manager-api/src/lib/addons.ts b/code/lib/manager-api/src/lib/addons.ts index 1145ab1826f5..a1c9b3dfda85 100644 --- a/code/lib/manager-api/src/lib/addons.ts +++ b/code/lib/manager-api/src/lib/addons.ts @@ -64,7 +64,7 @@ export class AddonStore { this.setChannel(mockChannel()); } - return this.channel; + return this.channel!; }; /** diff --git a/code/lib/manager-api/src/lib/events.ts b/code/lib/manager-api/src/lib/events.ts index 34038585f3ba..9ad62a485f24 100644 --- a/code/lib/manager-api/src/lib/events.ts +++ b/code/lib/manager-api/src/lib/events.ts @@ -17,10 +17,10 @@ interface Meta { export const getEventMetadata = (context: Meta, fullAPI: API) => { const { source, refId, type } = context; - const [sourceType, sourceLocation] = getSourceType(source, refId); + const [sourceType, sourceLocation] = getSourceType(source!, refId); const ref = - refId && fullAPI.getRefs()[refId] ? fullAPI.getRefs()[refId] : fullAPI.findRef(sourceLocation); + refId && fullAPI.getRefs()[refId] ? fullAPI.getRefs()[refId] : fullAPI.findRef(sourceLocation!); const meta = { source, diff --git a/code/lib/manager-api/src/lib/shortcut.ts b/code/lib/manager-api/src/lib/shortcut.ts index dab77ec28543..9ca5b2d7afe5 100644 --- a/code/lib/manager-api/src/lib/shortcut.ts +++ b/code/lib/manager-api/src/lib/shortcut.ts @@ -92,7 +92,7 @@ export const eventMatchesShortcut = ( e: KeyboardEventLike, shortcut: API_KeyCollection ): boolean => { - return shortcutMatchesShortcut(eventToShortcut(e), shortcut); + return shortcutMatchesShortcut(eventToShortcut(e)!, shortcut); }; export const keyToSymbol = (key: string): string => { diff --git a/code/lib/manager-api/src/lib/stories.ts b/code/lib/manager-api/src/lib/stories.ts index b48cbd51b877..7c9a806ef4d5 100644 --- a/code/lib/manager-api/src/lib/stories.ts +++ b/code/lib/manager-api/src/lib/stories.ts @@ -21,6 +21,7 @@ import type { API_HashEntry, SetStoriesPayload, StoryIndexV2, + Renderer, } from '@storybook/types'; // eslint-disable-next-line import/no-cycle import { type API, combineParameters, type State } from '../index'; @@ -185,7 +186,7 @@ export const transformStoryIndexToStoriesHash = ( // Now create a "path" or sub id for each name const paths = names.reduce((list, name, idx) => { const parent = idx > 0 && list[idx - 1]; - const id = sanitize(parent ? `${parent}-${name}` : name); + const id = sanitize(parent ? `${parent}-${name}` : name!); if (parent === id) { throw new Error( diff --git a/code/lib/manager-api/src/tests/stories.test.ts b/code/lib/manager-api/src/tests/stories.test.ts index a93cd1df9a99..80ddc1335572 100644 --- a/code/lib/manager-api/src/tests/stories.test.ts +++ b/code/lib/manager-api/src/tests/stories.test.ts @@ -110,12 +110,12 @@ describe('stories API', () => { 'component-b', 'component-b--story-3', ]); - expect(index['component-a']).toMatchObject({ + expect(index!['component-a']).toMatchObject({ type: 'component', id: 'component-a', children: ['component-a--docs', 'component-a--story-1', 'component-a--story-2'], }); - expect(index['component-a--docs']).toMatchObject({ + expect(index!['component-a--docs']).toMatchObject({ type: 'docs', id: 'component-a--docs', parent: 'component-a', From e0cdf02606a0dcf84378ade183d898d2eddacce8 Mon Sep 17 00:00:00 2001 From: Subhajit Ghosh <99127578+subhajit20@users.noreply.github.com> Date: Wed, 6 Sep 2023 15:23:35 +0000 Subject: [PATCH 3/5] Migrate @storybook/manager-api to strict TS --- code/lib/manager-api/src/index.tsx | 22 +- code/lib/manager-api/src/lib/addons.ts | 5 +- code/lib/manager-api/src/lib/stories.ts | 24 +- code/lib/manager-api/src/modules/addons.ts | 8 +- code/lib/manager-api/src/modules/globals.ts | 8 +- code/lib/manager-api/src/modules/refs.ts | 20 +- code/lib/manager-api/src/modules/settings.ts | 2 +- code/lib/manager-api/src/modules/shortcuts.ts | 6 +- code/lib/manager-api/src/modules/stories.ts | 165 +++--- code/lib/manager-api/src/modules/url.ts | 2 +- code/lib/manager-api/src/modules/versions.ts | 2 +- code/lib/manager-api/src/modules/whatsnew.ts | 2 +- code/lib/manager-api/src/tests/refs.test.ts | 8 +- .../lib/manager-api/src/tests/stories.test.ts | 108 ++-- node_modules/.package-lock.json | 27 + .../@storybook/core-events/jest.config.js | 7 + .../@storybook/core-events/package.json | 98 ++++ node_modules/ts-dedent/HISTORY.md | 55 ++ node_modules/ts-dedent/README.md | 107 ++++ node_modules/ts-dedent/esm/index.d.ts | 2 + node_modules/ts-dedent/esm/index.js | 38 ++ node_modules/ts-dedent/esm/index.js.map | 1 + node_modules/ts-dedent/package.json | 68 +++ .../ts-dedent/src/__tests__/index.spec.ts | 554 ++++++++++++++++++ .../ts-dedent/src/__tests__/issue-21.spec.ts | 88 +++ node_modules/ts-dedent/src/index.ts | 58 ++ yarn.lock | 22 +- 27 files changed, 1315 insertions(+), 192 deletions(-) create mode 100644 node_modules/.package-lock.json create mode 100644 node_modules/@storybook/core-events/jest.config.js create mode 100644 node_modules/@storybook/core-events/package.json create mode 100644 node_modules/ts-dedent/HISTORY.md create mode 100644 node_modules/ts-dedent/README.md create mode 100644 node_modules/ts-dedent/esm/index.d.ts create mode 100644 node_modules/ts-dedent/esm/index.js create mode 100644 node_modules/ts-dedent/esm/index.js.map create mode 100644 node_modules/ts-dedent/package.json create mode 100644 node_modules/ts-dedent/src/__tests__/index.spec.ts create mode 100644 node_modules/ts-dedent/src/__tests__/issue-21.spec.ts create mode 100644 node_modules/ts-dedent/src/index.ts diff --git a/code/lib/manager-api/src/index.tsx b/code/lib/manager-api/src/index.tsx index ab247114e440..144edd3be99b 100644 --- a/code/lib/manager-api/src/index.tsx +++ b/code/lib/manager-api/src/index.tsx @@ -75,7 +75,7 @@ export { default as merge } from './lib/merge'; export type { Options as StoreOptions, Listener as ChannelListener }; export { ActiveTabs }; -export const ManagerContext = createContext({ api: undefined, state: getInitialState({}) }); +export const ManagerContext = createContext({ api: undefined!, state: getInitialState({}!) }); export type State = layout.SubState & stories.SubState & @@ -167,7 +167,7 @@ class ManagerProvider extends Component { const store = new Store({ getState: () => this.state, - setState: (stateChange: Partial, callback) => this.setState(stateChange, callback), + setState: (stateChange: Partial, callback) => this.setState(stateChange, callback)!, }); const routeData = { location, path, viewMode, singleStory, storyId, refId }; @@ -200,7 +200,7 @@ class ManagerProvider extends Component { ); // Create our initial state by combining the initial state of all modules, then overlaying any saved state - const state = getInitialState(this.state, ...this.modules.map((m) => m.state)); + const state = getInitialState(this.state, ...this.modules.map((m) => m.state!)); // Get our API by combining the APIs exported by each module const api: API = Object.assign(this.api, { navigate }, ...this.modules.map((m) => m.api)); @@ -217,10 +217,10 @@ class ManagerProvider extends Component { path: props.path, refId: props.refId, viewMode: props.viewMode, - storyId: props.storyId, + storyId: props.storyId!, }; } - return null; + return null!; } shouldComponentUpdate(nextProps: ManagerProviderProps, nextState: State): boolean { @@ -239,7 +239,7 @@ class ManagerProvider extends Component { initModules = () => { // Now every module has had a chance to set its API, call init on each module which gives it // a chance to do things that call other modules' APIs. - this.modules.forEach((module) => { + this.modules.forEach((module: any) => { if ('init' in module) { module.init(); } @@ -299,11 +299,11 @@ function ManagerConsumer

({ const data = filterer.current(c); const l = useMemo(() => { - return [...Object.entries(data).reduce((acc, keyval) => acc.concat(keyval), [])]; + return [...Object.entries(data!).reduce((acc, keyval: any) => acc.concat(keyval), [])]; }, [c.state]); return useMemo(() => { - const Child = renderer.current as FC

; + const Child: any = renderer.current as FC

; return ; }, l); @@ -375,14 +375,14 @@ export const useChannel = (eventMap: API_EventMap, deps: any[] = []) => { export function useStoryPrepared(storyId?: StoryId) { const api = useStorybookApi(); - return api.isPrepared(storyId); + return api.isPrepared(storyId!); } export function useParameter(parameterKey: string, defaultValue?: S) { const api = useStorybookApi(); const result = api.getCurrentParameter(parameterKey); - return orDefault(result, defaultValue); + return orDefault(result, defaultValue!); } // cache for taking care of HMR @@ -478,7 +478,7 @@ export function useArgs(): [Args, (newArgs: Args) => void, (argNames?: string[]) [data, resetStoryArgs] ); - return [args, updateArgs, resetArgs]; + return [args!, updateArgs, resetArgs]; } export function useGlobals(): [Args, (newGlobals: Args) => void] { diff --git a/code/lib/manager-api/src/lib/addons.ts b/code/lib/manager-api/src/lib/addons.ts index a1c9b3dfda85..bbcffff46494 100644 --- a/code/lib/manager-api/src/lib/addons.ts +++ b/code/lib/manager-api/src/lib/addons.ts @@ -105,11 +105,10 @@ export class AddonStore { | Addon_TypesEnum.experimental_PAGE | Addon_TypesEnum.experimental_SIDEBAR_BOTTOM | Addon_TypesEnum.experimental_SIDEBAR_TOP - >(type: T): Addon_Collection { + >(type: T): Addon_Collection | any { if (!this.elements[type]) { this.elements[type] = {}; } - // @ts-expect-error (Kaspar told me to do this) return this.elements[type]; } @@ -185,7 +184,7 @@ export class AddonStore { }; loadAddons = (api: any) => { - Object.values(this.loaders).forEach((value) => value(api)); + Object.values(this.loaders).forEach((value: any) => value(api)); }; } diff --git a/code/lib/manager-api/src/lib/stories.ts b/code/lib/manager-api/src/lib/stories.ts index 7c9a806ef4d5..4a533bcfbeb9 100644 --- a/code/lib/manager-api/src/lib/stories.ts +++ b/code/lib/manager-api/src/lib/stories.ts @@ -72,7 +72,7 @@ const transformSetStoriesStoryDataToPreparedStoryIndex = ( ...base, }; } else { - const { argTypes, args, initialArgs } = story; + const { argTypes, args, initialArgs }: any = story; acc[id] = { type: 'story', ...base, @@ -110,7 +110,7 @@ export const transformStoryIndexV3toV4 = (index: StoryIndexV3): API_PreparedStor const countByTitle = countBy(Object.values(index.stories), 'title'); return { v: 4, - entries: Object.values(index.stories).reduce((acc, entry) => { + entries: Object.values(index.stories).reduce((acc, entry: any) => { let type: IndexEntry['type'] = 'story'; if ( entry.parameters?.docsOnly || @@ -144,7 +144,7 @@ type ToStoriesHashOptions = { export const transformStoryIndexToStoriesHash = ( input: API_PreparedStoryIndex | StoryIndexV2 | StoryIndexV3, { provider, docsOptions, filters, status }: ToStoriesHashOptions -): API_IndexHash => { +): API_IndexHash | any => { if (!input.v) { throw new Error('Composition: Missing stories.json version'); } @@ -154,10 +154,10 @@ export const transformStoryIndexToStoriesHash = ( index = index.v === 3 ? transformStoryIndexV3toV4(index as any) : index; index = index as API_PreparedStoryIndex; - const entryValues = Object.values(index.entries).filter((entry) => { + const entryValues = Object.values(index.entries).filter((entry: any) => { let result = true; - Object.values(filters).forEach((filter) => { + Object.values(filters).forEach((filter: any) => { if (result === false) { return; } @@ -168,11 +168,11 @@ export const transformStoryIndexToStoriesHash = ( }); const { sidebar = {} } = provider.getConfig(); - const { showRoots, collapsedRoots = [], renderLabel } = sidebar; + const { showRoots, collapsedRoots = [], renderLabel }: any = sidebar; const setShowRoots = typeof showRoots !== 'undefined'; - const storiesHashOutOfOrder = entryValues.reduce((acc, item) => { + const storiesHashOutOfOrder = entryValues.reduce((acc: any, item: any) => { if (docsOptions.docsMode && item.type !== 'docs') { return acc; } @@ -202,7 +202,7 @@ export const transformStoryIndexToStoriesHash = ( }, [] as string[]); // Now, let's add an entry to the hash for each path/name pair - paths.forEach((id, idx) => { + paths.forEach((id: any, idx: any) => { // The child is the next path, OR the story/docs entry itself const childId = paths[idx + 1] || item.id; @@ -285,7 +285,7 @@ export const transformStoryIndexToStoriesHash = ( }, {} as API_IndexHash); // This function adds a "root" or "orphan" and all of its descendents to the hash. - function addItem(acc: API_IndexHash, item: API_HashEntry) { + function addItem(acc: API_IndexHash | any, item: API_HashEntry | any) { // If we were already inserted as part of a group, that's great. if (acc[item.id]) { return acc; @@ -294,18 +294,18 @@ export const transformStoryIndexToStoriesHash = ( acc[item.id] = item; // Ensure we add the children depth-first *before* inserting any other entries if (item.type === 'root' || item.type === 'group' || item.type === 'component') { - item.children.forEach((childId) => addItem(acc, storiesHashOutOfOrder[childId])); + item.children.forEach((childId: any) => addItem(acc, storiesHashOutOfOrder[childId])); } return acc; } // We'll do two passes over the data, adding all the orphans, then all the roots const orphanHash = Object.values(storiesHashOutOfOrder) - .filter((i) => i.type !== 'root' && !i.parent) + .filter((i: any) => i.type !== 'root' && !i.parent) .reduce(addItem, {}); return Object.values(storiesHashOutOfOrder) - .filter((i) => i.type === 'root') + .filter((i: any) => i.type === 'root') .reduce(addItem, orphanHash); }; diff --git a/code/lib/manager-api/src/modules/addons.ts b/code/lib/manager-api/src/modules/addons.ts index 0e1d69ca39e5..dc2a42494e4e 100644 --- a/code/lib/manager-api/src/modules/addons.ts +++ b/code/lib/manager-api/src/modules/addons.ts @@ -85,7 +85,7 @@ export interface SubAPI { export function ensurePanel(panels: API_Panels, selectedPanel?: string, currentPanel?: string) { const keys = Object.keys(panels); - if (keys.indexOf(selectedPanel) >= 0) { + if (keys.indexOf(selectedPanel!) >= 0) { return selectedPanel; } @@ -95,7 +95,7 @@ export function ensurePanel(panels: API_Panels, selectedPanel?: string, currentP return currentPanel; } -export const init: ModuleFn = ({ provider, store, fullAPI }) => { +export const init: ModuleFn = ({ provider, store, fullAPI }): any => { const api: SubAPI = { getElements: (type) => provider.getElements(type), getPanels: () => api.getElements(Addon_TypesEnum.PANEL), @@ -112,7 +112,7 @@ export const init: ModuleFn = ({ provider, store, fullAPI }) = const filteredPanels: Addon_Collection = {}; Object.entries(allPanels).forEach(([id, panel]) => { - const { paramKey } = panel; + const { paramKey }: any = panel; if (paramKey && parameters && parameters[paramKey] && parameters[paramKey].disable) { return; } @@ -121,7 +121,7 @@ export const init: ModuleFn = ({ provider, store, fullAPI }) = return filteredPanels; }, - getSelectedPanel: () => { + getSelectedPanel: (): any => { const { selectedPanel } = store.getState(); return ensurePanel(api.getElements(Addon_TypesEnum.PANEL), selectedPanel, selectedPanel); }, diff --git a/code/lib/manager-api/src/modules/globals.ts b/code/lib/manager-api/src/modules/globals.ts index 393deb58c4a2..17c35bbb7224 100644 --- a/code/lib/manager-api/src/modules/globals.ts +++ b/code/lib/manager-api/src/modules/globals.ts @@ -64,8 +64,8 @@ export const init: ModuleFn = ({ store, fullAPI, provider }) = provider.channel.on( GLOBALS_UPDATED, - function handleGlobalsUpdated({ globals }: { globals: Globals }) { - const { ref } = getEventMetadata(this, fullAPI); + function handleGlobalsUpdated(this: any, { globals }: { globals: Globals }) { + const { ref } = getEventMetadata(this, fullAPI)!; if (!ref) { updateGlobals(globals); @@ -80,8 +80,8 @@ export const init: ModuleFn = ({ store, fullAPI, provider }) = // Emitted by the preview on initialization provider.channel.on( SET_GLOBALS, - function handleSetStories({ globals, globalTypes }: SetGlobalsPayload) { - const { ref } = getEventMetadata(this, fullAPI); + function handleSetStories(this: any, { globals, globalTypes }: SetGlobalsPayload) { + const { ref } = getEventMetadata(this, fullAPI)!; const currentGlobals = store.getState()?.globals; if (!ref) { diff --git a/code/lib/manager-api/src/modules/refs.ts b/code/lib/manager-api/src/modules/refs.ts index 02884665cf5a..c08146259d76 100644 --- a/code/lib/manager-api/src/modules/refs.ts +++ b/code/lib/manager-api/src/modules/refs.ts @@ -87,13 +87,13 @@ export const getSourceType = (source: string, refId?: string) => { return [null, null]; }; -export const defaultStoryMapper: API_StoryMapper = (b, a) => { +export const defaultStoryMapper: API_StoryMapper = (b: any, a: any) => { return { ...a, kind: a.kind.replace('|', '/') }; }; const addRefIds = (input: API_IndexHash, ref: API_ComposedRef): API_IndexHash => { return Object.entries(input).reduce((acc, [id, item]) => { - return { ...acc, [id]: { ...item, refId: ref.id } }; + return { ...acc, [id]: { ...item!, refId: ref.id } }; }, {} as API_IndexHash); }; @@ -114,7 +114,7 @@ async function handleRequest( } return json as API_SetRefData; - } catch (err) { + } catch (err: any) { return { indexError: err }; } } @@ -159,10 +159,10 @@ export const init: ModuleFn = ( { runCheck = true } = {} ) => { const api: SubAPI = { - findRef: (source) => { + findRef: (source): any => { const refs = api.getRefs(); - return Object.values(refs).find(({ url }) => url.match(source)); + return Object.values(refs).find(({ url }: any) => url.match(source)); }, changeRefVersion: (id, url) => { const { versions, title } = api.getRefs()[id]; @@ -199,7 +199,7 @@ export const init: ModuleFn = ( const loadedData: API_SetRefData = {}; const query = version ? `?version=${version}` : ''; const credentials = isPublic ? 'omit' : 'include'; - const urlParseResult = parseUrl(url); + const urlParseResult = parseUrl(url!); const headers: HeadersInit = { Accept: 'application/json', @@ -257,7 +257,7 @@ export const init: ModuleFn = ( const versions = ref.versions && Object.keys(ref.versions).length ? ref.versions : loadedData.versions; - await api.setRef(id, { + await api.setRef(id!, { id, url: urlParseResult.url, ...loadedData, @@ -293,9 +293,9 @@ export const init: ModuleFn = ( status: {}, }); } - if (index) index = addRefIds(index, ref); + if (index!) index = addRefIds(index, ref); - api.updateRef(id, { index, ...rest }); + api.updateRef(id, { index: undefined, ...rest }); }, updateRef: (id, data) => { @@ -322,7 +322,7 @@ export const init: ModuleFn = ( if (runCheck) { Object.entries(refs).forEach(([id, ref]) => { - api.checkRef({ ...ref, stories: {} } as API_SetRefData); + api.checkRef({ ...ref!, stories: {} } as API_SetRefData); }); } diff --git a/code/lib/manager-api/src/modules/settings.ts b/code/lib/manager-api/src/modules/settings.ts index 4c850f9aca1a..aa4924474cd2 100644 --- a/code/lib/manager-api/src/modules/settings.ts +++ b/code/lib/manager-api/src/modules/settings.ts @@ -32,7 +32,7 @@ export interface SubState { settings: API_Settings; } -export const init: ModuleFn = ({ store, navigate, fullAPI }) => { +export const init: ModuleFn = ({ store, navigate, fullAPI }): any => { const isSettingsScreenActive = () => { const { path } = fullAPI.getUrlState(); return !!(path || '').match(/^\/settings/); diff --git a/code/lib/manager-api/src/modules/shortcuts.ts b/code/lib/manager-api/src/modules/shortcuts.ts index 6d1dc4814c43..6aca1d9a0f5c 100644 --- a/code/lib/manager-api/src/modules/shortcuts.ts +++ b/code/lib/manager-api/src/modules/shortcuts.ts @@ -15,7 +15,7 @@ export const isMacLike = () => export const controlOrMetaKey = () => (isMacLike() ? 'meta' : 'control'); export function keys(o: O) { - return Object.keys(o) as (keyof O)[]; + return Object.keys(o!) as (keyof O)[]; } export interface SubState { @@ -216,7 +216,7 @@ export const init: ModuleFn = ({ store, fullAPI, provider }) => { const shortcuts = api.getShortcutKeys(); const actions = keys(shortcuts); const matchedFeature = actions.find((feature: API_Action) => - shortcutMatchesShortcut(shortcut, shortcuts[feature]) + shortcutMatchesShortcut(shortcut!, shortcuts[feature]) ); if (matchedFeature) { api.handleShortcutFeature(matchedFeature, event); @@ -276,7 +276,7 @@ export const init: ModuleFn = ({ store, fullAPI, provider }) => { if (element) { try { // should be like a channel message and all that, but yolo for now - element.contentWindow.focus(); + element.contentWindow!.focus(); } catch (e) { // } diff --git a/code/lib/manager-api/src/modules/stories.ts b/code/lib/manager-api/src/modules/stories.ts index aff85aabcea3..89c152ca36f2 100644 --- a/code/lib/manager-api/src/modules/stories.ts +++ b/code/lib/manager-api/src/modules/stories.ts @@ -281,7 +281,7 @@ const removedOptions = ['enableShortcuts', 'theme', 'showRoots']; function removeRemovedOptions = Record>(options?: T): T { if (!options || typeof options === 'string') { - return options; + return options!; } const result: T = { ...options } as T; @@ -305,7 +305,7 @@ export const init: ModuleFn = ({ }) => { const api: SubAPI = { storyId: toId, - getData: (storyId, refId) => { + getData: (storyId, refId): any => { const result = api.resolveStory(storyId, refId); if (result?.type === 'story' || result?.type === 'docs') { return result; @@ -429,7 +429,7 @@ export const init: ModuleFn = ({ // Support legacy API with component permalinks, where kind is `x/y` but permalink is 'z' const entry = hash[sanitize(titleOrId)]; if (entry?.type === 'component') { - const foundId = entry.children.find((childId) => hash[childId].name === name); + const foundId = entry.children.find((childId: any) => hash[childId].name === name); if (foundId) { api.selectStory(foundId, undefined, options); } @@ -449,7 +449,7 @@ export const init: ModuleFn = ({ findLeafStoryId(index, storyId) { return api.findLeafEntry(index, storyId)?.id; }, - findSiblingStoryId(storyId, index, direction, toSiblingGroup) { + findSiblingStoryId(storyId, index, direction, toSiblingGroup): any { if (toSiblingGroup) { const lookupList = getComponentLookupList(index); const position = lookupList.findIndex((i) => i.includes(storyId)); @@ -546,7 +546,7 @@ export const init: ModuleFn = ({ } as API_StoryEntry; await store.setState({ index }); } else { - const { id: refId, index } = ref; + const { id: refId, index }: any = ref; index[storyId] = { ...index[storyId], ...update, @@ -567,7 +567,7 @@ export const init: ModuleFn = ({ } as API_DocsEntry; await store.setState({ index }); } else { - const { id: refId, index } = ref; + const { id: refId, index }: any = ref; index[docsId] = { ...index[docsId], ...update, @@ -621,15 +621,18 @@ export const init: ModuleFn = ({ // and emit STORY_SPECIFIED with the id. We need to ensure we respond to this change. provider.channel.on( STORY_SPECIFIED, - function handler({ - storyId, - viewMode, - }: { - storyId: string; - viewMode: API_ViewMode; - [k: string]: any; - }) { - const { sourceType } = getEventMetadata(this, fullAPI); + function handler( + this: any, + { + storyId, + viewMode, + }: { + storyId: string; + viewMode: API_ViewMode; + [k: string]: any; + } + ) { + const { sourceType } = getEventMetadata(this, fullAPI)!; if (sourceType === 'local') { const state = store.getState(); @@ -664,13 +667,13 @@ export const init: ModuleFn = ({ // Until the ref has a selection, it will not render anything (e.g. while waiting for // the preview.js file or the index to load). Once it has a selection, it will render its own // preparing spinner. - provider.channel.on(CURRENT_STORY_WAS_SET, function handler() { - const { ref } = getEventMetadata(this, fullAPI); + provider.channel.on(CURRENT_STORY_WAS_SET, function handler(this: any) { + const { ref } = getEventMetadata(this, fullAPI)!; api.setPreviewInitialized(ref); }); - provider.channel.on(STORY_CHANGED, function handler() { - const { sourceType } = getEventMetadata(this, fullAPI); + provider.channel.on(STORY_CHANGED, function handler(this: any) { + const { sourceType } = getEventMetadata(this, fullAPI)!; if (sourceType === 'local') { const options = api.getCurrentParameter('options'); @@ -681,56 +684,62 @@ export const init: ModuleFn = ({ } }); - provider.channel.on(STORY_PREPARED, function handler({ id, ...update }: StoryPreparedPayload) { - const { ref, sourceType } = getEventMetadata(this, fullAPI); - api.updateStory(id, { ...update, prepared: true }, ref); + provider.channel.on( + STORY_PREPARED, + function handler(this: any, { id, ...update }: StoryPreparedPayload) { + const { ref, sourceType } = getEventMetadata(this, fullAPI)!; + api.updateStory(id, { ...update, prepared: true }, ref); - if (!ref) { - if (!store.getState().hasCalledSetOptions) { - const { options } = update.parameters; - fullAPI.setOptions(removeRemovedOptions(options)); - store.setState({ hasCalledSetOptions: true }); + if (!ref) { + if (!store.getState().hasCalledSetOptions) { + const { options } = update.parameters; + fullAPI.setOptions(removeRemovedOptions(options)); + store.setState({ hasCalledSetOptions: true }); + } } - } - if (sourceType === 'local') { - const { storyId, index, refId } = store.getState(); - - // create a list of related stories to be preloaded - const toBePreloaded = Array.from( - new Set([ - api.findSiblingStoryId(storyId, index, 1, true), - api.findSiblingStoryId(storyId, index, -1, true), - ]) - ).filter(Boolean); - - provider.channel.emit(PRELOAD_ENTRIES, { - ids: toBePreloaded, - options: { target: refId }, - }); + if (sourceType === 'local') { + const { storyId, index, refId } = store.getState(); + + // create a list of related stories to be preloaded + const toBePreloaded = Array.from( + new Set([ + api.findSiblingStoryId(storyId, index, 1, true), + api.findSiblingStoryId(storyId, index, -1, true), + ]) + ).filter(Boolean); + + provider.channel.emit(PRELOAD_ENTRIES, { + ids: toBePreloaded, + options: { target: refId }, + }); + } } - }); + ); - provider.channel.on(DOCS_PREPARED, function handler({ id, ...update }: DocsPreparedPayload) { - const { ref } = getEventMetadata(this, fullAPI); - api.updateStory(id, { ...update, prepared: true }, ref); - }); + provider.channel.on( + DOCS_PREPARED, + function handler(this: any, { id, ...update }: DocsPreparedPayload) { + const { ref } = getEventMetadata(this, fullAPI)!; + api.updateStory(id, { ...update, prepared: true }, ref); + } + ); - provider.channel.on(SET_INDEX, function handler(index: API_PreparedStoryIndex) { - const { ref } = getEventMetadata(this, fullAPI); + provider.channel.on(SET_INDEX, function handler(this: any, index: API_PreparedStoryIndex) { + const { ref } = getEventMetadata(this, fullAPI)!; if (!ref) { api.setIndex(index); const options = api.getCurrentParameter('options'); - fullAPI.setOptions(removeRemovedOptions(options)); + fullAPI.setOptions(removeRemovedOptions(options!)); } else { fullAPI.setRef(ref.id, { ...ref, storyIndex: index }, true); } }); // For composition back-compatibilty - provider.channel.on(SET_STORIES, function handler(data: SetStoriesPayload) { - const { ref } = getEventMetadata(this, fullAPI); + provider.channel.on(SET_STORIES, function handler(this: any, data: SetStoriesPayload) { + const { ref } = getEventMetadata(this, fullAPI)!; const setStoriesData = data.v ? denormalizeStoryParameters(data) : data.stories; if (!ref) { @@ -742,22 +751,25 @@ export const init: ModuleFn = ({ provider.channel.on( SELECT_STORY, - function handler({ - kind, - title = kind, - story, - name = story, - storyId, - ...rest - }: { - kind?: StoryKind; - title?: ComponentTitle; - story?: StoryName; - name?: StoryName; - storyId: string; - viewMode: API_ViewMode; - }) { - const { ref } = getEventMetadata(this, fullAPI); + function handler( + this: any, + { + kind, + title = kind, + story, + name = story, + storyId, + ...rest + }: { + kind?: StoryKind; + title?: ComponentTitle; + story?: StoryName; + name?: StoryName; + storyId: string; + viewMode: API_ViewMode; + } + ) { + const { ref } = getEventMetadata(this, fullAPI)!; if (!ref) { fullAPI.selectStory(storyId || title, name, rest); @@ -769,20 +781,23 @@ export const init: ModuleFn = ({ provider.channel.on( STORY_ARGS_UPDATED, - function handleStoryArgsUpdated({ storyId, args }: { storyId: StoryId; args: Args }) { - const { ref } = getEventMetadata(this, fullAPI); + function handleStoryArgsUpdated( + this: any, + { storyId, args }: { storyId: StoryId; args: Args } + ) { + const { ref } = getEventMetadata(this, fullAPI)!; api.updateStory(storyId, { args }, ref); } ); // When there's a preview error, we don't show it in the manager, but simply - provider.channel.on(CONFIG_ERROR, function handleConfigError(err) { - const { ref } = getEventMetadata(this, fullAPI); + provider.channel.on(CONFIG_ERROR, function handleConfigError(this: any, err: any) { + const { ref } = getEventMetadata(this, fullAPI)!; api.setPreviewInitialized(ref); }); - provider.channel.on(STORY_MISSING, function handleConfigError(err) { - const { ref } = getEventMetadata(this, fullAPI); + provider.channel.on(STORY_MISSING, function handleConfigError(this: any, err: any) { + const { ref } = getEventMetadata(this, fullAPI)!; api.setPreviewInitialized(ref); }); diff --git a/code/lib/manager-api/src/modules/url.ts b/code/lib/manager-api/src/modules/url.ts index c6cfc5abbd80..cbe10872742f 100644 --- a/code/lib/manager-api/src/modules/url.ts +++ b/code/lib/manager-api/src/modules/url.ts @@ -192,7 +192,7 @@ export const init: ModuleFn = (moduleArgs) => { } }); - provider.channel.on(GLOBALS_UPDATED, ({ globals, initialGlobals }) => { + provider.channel.on(GLOBALS_UPDATED, ({ globals, initialGlobals }: any) => { const { path, queryParams } = api.getUrlState(); const globalsString = buildArgsParam(initialGlobals, globals); navigateTo(path, { ...queryParams, globals: globalsString }, { replace: true }); diff --git a/code/lib/manager-api/src/modules/versions.ts b/code/lib/manager-api/src/modules/versions.ts index 2d90a14fcd69..15a8a724e651 100644 --- a/code/lib/manager-api/src/modules/versions.ts +++ b/code/lib/manager-api/src/modules/versions.ts @@ -96,7 +96,7 @@ export const init: ModuleFn = ({ store }) => { const diff = semver.diff(actualCurrent, latest.version); return ( - semver.gt(latest.version, actualCurrent) && diff !== 'patch' && !diff.includes('pre') + semver.gt(latest.version, actualCurrent) && diff !== 'patch' && !diff!.includes('pre') ); } return false; diff --git a/code/lib/manager-api/src/modules/whatsnew.ts b/code/lib/manager-api/src/modules/whatsnew.ts index 6ee90558bc7c..27488f702d2e 100644 --- a/code/lib/manager-api/src/modules/whatsnew.ts +++ b/code/lib/manager-api/src/modules/whatsnew.ts @@ -95,7 +95,7 @@ export const init: ModuleFn = ({ fullAPI, store, provider }) => { subHeadline: "Click to learn what's new in Storybook", }, icon: { name: 'hearthollow' }, - onClear({ dismissed }) { + onClear({ dismissed }: any) { if (dismissed) { setWhatsNewCache({ lastDismissedPost: whatsNewData.url }); } diff --git a/code/lib/manager-api/src/tests/refs.test.ts b/code/lib/manager-api/src/tests/refs.test.ts index f0556d560ba3..9150d7d30afa 100644 --- a/code/lib/manager-api/src/tests/refs.test.ts +++ b/code/lib/manager-api/src/tests/refs.test.ts @@ -93,16 +93,16 @@ const setupResponses = ({ throw new Error('Wrong request type'); } - if (l.includes('index') && o.credentials === 'include' && indexPrivate) { + if (l.includes('index') && o?.credentials === 'include' && indexPrivate) { return respond(indexPrivate); } - if (l.includes('index') && o.credentials === 'omit' && indexPublic) { + if (l.includes('index') && o?.credentials === 'omit' && indexPublic) { return respond(indexPublic); } - if (l.includes('stories') && o.credentials === 'include' && storiesPrivate) { + if (l.includes('stories') && o?.credentials === 'include' && storiesPrivate) { return respond(storiesPrivate); } - if (l.includes('stories') && o.credentials === 'omit' && storiesPublic) { + if (l.includes('stories') && o?.credentials === 'omit' && storiesPublic) { return respond(storiesPublic); } if (l.includes('iframe') && iframe) { diff --git a/code/lib/manager-api/src/tests/stories.test.ts b/code/lib/manager-api/src/tests/stories.test.ts index 80ddc1335572..bdf7b1256f92 100644 --- a/code/lib/manager-api/src/tests/stories.test.ts +++ b/code/lib/manager-api/src/tests/stories.test.ts @@ -102,7 +102,7 @@ describe('stories API', () => { api.setIndex({ v: 4, entries: mockEntries }); const { index } = store.getState(); // We need exact key ordering, even if in theory JS doesn't guarantee it - expect(Object.keys(index)).toEqual([ + expect(Object.keys(index!)).toEqual([ 'component-a', 'component-a--docs', 'component-a--story-1', @@ -124,7 +124,7 @@ describe('stories API', () => { storiesImports: [], prepared: false, }); - expect(index['component-a--story-1']).toMatchObject({ + expect(index!['component-a--story-1']).toMatchObject({ type: 'story', id: 'component-a--story-1', parent: 'component-a', @@ -133,7 +133,7 @@ describe('stories API', () => { prepared: false, }); expect( - (index['component-a--story-1'] as API_StoryEntry as API_StoryEntry).args + (index!['component-a--story-1'] as API_StoryEntry as API_StoryEntry).args ).toBeUndefined(); }); it('trims whitespace of group/component names (which originate from the kind)', () => { @@ -154,20 +154,20 @@ describe('stories API', () => { }); const { index } = store.getState(); // We need exact key ordering, even if in theory JS doesn't guarantee it - expect(Object.keys(index)).toEqual([ + expect(Object.keys(index!)).toEqual([ 'design-system', 'design-system-some-component', 'design-system-some-component--my-story', ]); - expect(index['design-system']).toMatchObject({ + expect(index!['design-system']).toMatchObject({ type: 'root', name: 'Design System', // root name originates from `kind`, so it gets trimmed }); - expect(index['design-system-some-component']).toMatchObject({ + expect(index!['design-system-some-component']).toMatchObject({ type: 'component', name: 'Some Component', // component name originates from `kind`, so it gets trimmed }); - expect(index['design-system-some-component--my-story']).toMatchObject({ + expect(index!['design-system-some-component--my-story']).toMatchObject({ type: 'story', title: ' Design System / Some Component ', // title is kept as-is, because it may be used as identifier name: ' My Story ', // story name is kept as-is, because it's set directly on the story @@ -192,7 +192,7 @@ describe('stories API', () => { }); const { index } = store.getState(); // We need exact key ordering, even if in theory JS doesn't guarantee it - expect(Object.keys(index)).toEqual([ + expect(Object.keys(index!)).toEqual([ 'component-a', 'component-a--docs', 'component-a--story-1', @@ -203,7 +203,7 @@ describe('stories API', () => { 'root-first', 'root-first--story-1', ]); - expect(index.root).toMatchObject({ + expect(index!.root).toMatchObject({ type: 'root', id: 'root', children: ['root-first'], @@ -228,19 +228,19 @@ describe('stories API', () => { }); const { index } = store.getState(); // We need exact key ordering, even if in theory JS doens't guarantee it - expect(Object.keys(index)).toEqual(['a', 'a-b', 'a-b--1']); - expect(index.a).toMatchObject({ + expect(Object.keys(index!)).toEqual(['a', 'a-b', 'a-b--1']); + expect(index!.a).toMatchObject({ type: 'root', id: 'a', children: ['a-b'], }); - expect(index['a-b']).toMatchObject({ + expect(index!['a-b']).toMatchObject({ type: 'component', id: 'a-b', parent: 'a', children: ['a-b--1'], }); - expect(index['a-b--1']).toMatchObject({ + expect(index!['a-b--1']).toMatchObject({ type: 'story', id: 'a-b--1', parent: 'a-b', @@ -267,13 +267,13 @@ describe('stories API', () => { }); const { index } = store.getState(); // We need exact key ordering, even if in theory JS doens't guarantee it - expect(Object.keys(index)).toEqual(['a', 'a--1']); - expect(index.a).toMatchObject({ + expect(Object.keys(index!)).toEqual(['a', 'a--1']); + expect(index!.a).toMatchObject({ type: 'component', id: 'a', children: ['a--1'], }); - expect(index['a--1']).toMatchObject({ + expect(index!['a--1']).toMatchObject({ type: 'story', id: 'a--1', parent: 'a', @@ -298,13 +298,13 @@ describe('stories API', () => { }); const { index } = store.getState(); // We need exact key ordering, even if in theory JS doens't guarantee it - expect(Object.keys(index)).toEqual(['a', 'a--1', 'a--2', 'b', 'b--1']); - expect(index.a).toMatchObject({ + expect(Object.keys(index!)).toEqual(['a', 'a--1', 'a--2', 'b', 'b--1']); + expect(index!.a).toMatchObject({ type: 'component', id: 'a', children: ['a--1', 'a--2'], }); - expect(index.b).toMatchObject({ + expect(index!.b).toMatchObject({ type: 'component', id: 'b', children: ['b--1'], @@ -330,7 +330,7 @@ describe('stories API', () => { }, }); const { index } = store.getState(); - expect(index['prepared--story']).toMatchObject({ + expect(index!['prepared--story']).toMatchObject({ type: 'story', id: 'prepared--story', parent: 'prepared', @@ -354,7 +354,7 @@ describe('stories API', () => { }); // Let the promise/await chain resolve await new Promise((r) => setTimeout(r, 0)); - expect(store.getState().index['component-a--story-1'] as API_StoryEntry).toMatchObject({ + expect(store.getState().index!['component-a--story-1'] as API_StoryEntry).toMatchObject({ prepared: true, parameters: { a: 'b' }, args: { c: 'd' }, @@ -362,7 +362,7 @@ describe('stories API', () => { api.setIndex({ v: 4, entries: mockEntries }); // Let the promise/await chain resolve await new Promise((r) => setTimeout(r, 0)); - expect(store.getState().index['component-a--story-1'] as API_StoryEntry).toMatchObject({ + expect(store.getState().index!['component-a--story-1'] as API_StoryEntry).toMatchObject({ prepared: true, parameters: { a: 'b' }, args: { c: 'd' }, @@ -378,7 +378,7 @@ describe('stories API', () => { api.setIndex({ v: 4, entries: docsEntries }); const { index } = store.getState(); // We need exact key ordering, even if in theory JS doesn't guarantee it - expect(Object.keys(index)).toEqual([ + expect(Object.keys(index!)).toEqual([ 'component-a', 'component-a--page', 'component-a--story-2', @@ -387,10 +387,10 @@ describe('stories API', () => { 'component-c', 'component-c--story-4', ]); - expect(index['component-a--page'].type).toBe('story'); - expect(index['component-a--story-2'].type).toBe('story'); - expect(index['component-b--docs'].type).toBe('docs'); - expect(index['component-c--story-4'].type).toBe('story'); + expect(index!['component-a--page'].type).toBe('story'); + expect(index!['component-a--story-2'].type).toBe('story'); + expect(index!['component-b--docs'].type).toBe('docs'); + expect(index!['component-c--story-4'].type).toBe('story'); }); describe('when DOCS_MODE = true', () => { it('strips out story entries', async () => { @@ -402,7 +402,7 @@ describe('stories API', () => { const { store } = moduleArgs; api.setIndex({ v: 4, entries: docsEntries }); const { index } = store.getState(); - expect(Object.keys(index)).toEqual(['component-b', 'component-b--docs']); + expect(Object.keys(index!)).toEqual(['component-b', 'component-b--docs']); }); }); }); @@ -452,7 +452,7 @@ describe('stories API', () => { const { init } = initStories(moduleArgs as unknown as ModuleArgs); const { store } = moduleArgs; - await init(); + await init!(); const { indexError } = store.getState(); expect(indexError).toBeDefined(); @@ -481,7 +481,7 @@ describe('stories API', () => { const { init } = initStories(moduleArgs as unknown as ModuleArgs); const { store, provider } = moduleArgs; - await init(); + await init!(); expect(fetch).toHaveBeenCalledTimes(1); provider.channel.emit(STORY_INDEX_INVALIDATED); @@ -491,7 +491,7 @@ describe('stories API', () => { await wait(16); const { index } = store.getState(); - expect(Object.keys(index)).toEqual(['component-a', 'component-a--story-1']); + expect(Object.keys(index!)).toEqual(['component-a', 'component-a--story-1']); }); it('clears 500 errors when invalidated', async () => { fetch.mockReturnValueOnce( @@ -504,7 +504,7 @@ describe('stories API', () => { const { init } = initStories(moduleArgs as unknown as ModuleArgs); const { store, provider } = moduleArgs; - await init(); + await init!(); const { indexError } = store.getState(); expect(indexError).toBeDefined(); @@ -536,7 +536,7 @@ describe('stories API', () => { const { index, indexError: newIndexError } = store.getState(); expect(newIndexError).not.toBeDefined(); - expect(Object.keys(index)).toEqual(['component-a', 'component-a--story-1']); + expect(Object.keys(index!)).toEqual(['component-a', 'component-a--story-1']); }); }); @@ -616,12 +616,12 @@ describe('stories API', () => { api.setIndex({ v: 4, entries: preparedEntries }); const { index } = store.getState(); - expect((index['a--1'] as API_StoryEntry).args).toEqual({ a: 'b' }); - expect((index['b--1'] as API_StoryEntry).args).toEqual({ x: 'y' }); + expect((index!['a--1'] as API_StoryEntry).args).toEqual({ a: 'b' }); + expect((index!['b--1'] as API_StoryEntry).args).toEqual({ x: 'y' }); provider.channel.emit(STORY_ARGS_UPDATED, { storyId: 'a--1', args: { foo: 'bar' } }); const { index: changedIndex } = store.getState(); - expect((changedIndex['a--1'] as API_StoryEntry).args).toEqual({ foo: 'bar' }); - expect((changedIndex['b--1'] as API_StoryEntry).args).toEqual({ x: 'y' }); + expect((changedIndex!['a--1'] as API_StoryEntry).args).toEqual({ foo: 'bar' }); + expect((changedIndex!['b--1'] as API_StoryEntry).args).toEqual({ x: 'y' }); }); it('changes reffed args properly, per story when receiving STORY_ARGS_UPDATED', () => { const fullAPI = { updateRef: jest.fn() }; @@ -663,8 +663,8 @@ describe('stories API', () => { }); const { index } = store.getState(); - expect((index['a--1'] as API_StoryEntry).args).toEqual({ a: 'b' }); - expect((index['b--1'] as API_StoryEntry).args).toEqual({ x: 'y' }); + expect((index!['a--1'] as API_StoryEntry).args).toEqual({ a: 'b' }); + expect((index!['b--1'] as API_StoryEntry).args).toEqual({ x: 'y' }); }); it('updateStoryArgs emits UPDATE_STORY_ARGS to the right frame', () => { const fullAPI = { updateRef: jest.fn() }; @@ -705,8 +705,8 @@ describe('stories API', () => { }); const { index } = store.getState(); - expect((index['a--1'] as API_StoryEntry).args).toEqual({ a: 'b' }); - expect((index['b--1'] as API_StoryEntry).args).toEqual({ x: 'y' }); + expect((index!['a--1'] as API_StoryEntry).args).toEqual({ a: 'b' }); + expect((index!['b--1'] as API_StoryEntry).args).toEqual({ x: 'y' }); }); it('resetStoryArgs emits RESET_STORY_ARGS to the right frame', () => { const fullAPI = { updateRef: jest.fn() }; @@ -777,7 +777,6 @@ describe('stories API', () => { expect(navigate).not.toHaveBeenCalled(); }); it('does nothing if you have not selected a story', () => { - // @ts-expect-error (storyId type is maybe wrong?) const initialState = { path: '/story', storyId: undefined, viewMode: 'story' }; const moduleArgs = createMockModuleArgs({ initialState }); const { api } = initStories(moduleArgs as unknown as ModuleArgs); @@ -797,7 +796,7 @@ describe('stories API', () => { const { store } = moduleArgs; api.setIndex({ v: 4, entries: navigationEntries }); - const result = api.findSiblingStoryId('a--1', store.getState().index, 1, false); + const result = api.findSiblingStoryId('a--1', store.getState().index!, 1, false); expect(result).toBe('a--2'); }); it('works forward toSiblingGroup', () => { @@ -807,7 +806,7 @@ describe('stories API', () => { const { store } = moduleArgs; api.setIndex({ v: 4, entries: navigationEntries }); - const result = api.findSiblingStoryId('a--1', store.getState().index, 1, true); + const result = api.findSiblingStoryId('a--1', store.getState().index!, 1, true); expect(result).toBe('b-c--1'); }); }); @@ -1016,7 +1015,7 @@ describe('stories API', () => { args: { c: 'd' }, }); const { index } = store.getState(); - expect(index['component-a--story-1']).toMatchObject({ + expect(index!['component-a--story-1']).toMatchObject({ type: 'story', id: 'component-a--story-1', parent: 'component-a', @@ -1064,7 +1063,7 @@ describe('stories API', () => { parameters: { a: 'b' }, }); const { index } = store.getState(); - expect(index['component-a--docs']).toMatchObject({ + expect(index!['component-a--docs']).toMatchObject({ type: 'docs', id: 'component-a--docs', parent: 'component-a', @@ -1294,7 +1293,7 @@ describe('stories API', () => { // do a second update, this time with null await expect( api.experimental_updateStatus('a-addon-id', { - 'a-story-id': null, + 'a-story-id': null!, 'another-story-id': { status: 'success', title: 'a addon title', description: '' }, }) ).resolves.not.toThrow(); @@ -1332,9 +1331,12 @@ describe('stories API', () => { // use existing state in function await expect( - api.experimental_updateStatus('a-addon-id', (current) => { + api.experimental_updateStatus('a-addon-id', (current: any) => { return Object.fromEntries( - Object.entries(current).map(([k, v]) => [k, { ...v['a-addon-id'], status: 'success' }]) + Object.entries(current).map(([k, v]: any) => [ + k, + { ...v['a-addon-id'], status: 'success' }, + ]) ); }) ).resolves.not.toThrow(); @@ -1395,7 +1397,7 @@ describe('stories API', () => { const { store } = moduleArgs; await api.setIndex({ v: 4, entries: navigationEntries }); - await api.experimental_setFilter('myCustomFilter', (item) => item.id.startsWith('a')); + await api.experimental_setFilter('myCustomFilter', (item: any) => item.id.startsWith('a')); const { index } = store.getState(); @@ -1458,9 +1460,9 @@ describe('stories API', () => { await api.setIndex({ v: 4, entries: navigationEntries }); await api.experimental_setFilter( 'myCustomFilter', - (item) => + (item: any) => item.status !== undefined && - Object.values(item.status).some((v) => v.status === 'pending') + Object.values(item.status).some((v: any) => v.status === 'pending') ); // empty, because there are no stories with status @@ -1517,7 +1519,7 @@ describe('stories API', () => { const { store } = moduleArgs; await api.setIndex({ v: 4, entries: navigationEntries }); - await api.experimental_setFilter('myCustomFilter', (item) => item.id.startsWith('a')); + await api.experimental_setFilter('myCustomFilter', (item: any) => item.id.startsWith('a')); await api.setIndex({ v: 4, entries: navigationEntries }); diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 000000000000..3fbc14dd749a --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,27 @@ +{ + "name": "@storybook/root", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@storybook/core-events": { + "version": "7.4.0", + "resolved": "https://registry.npmjs.org/@storybook/core-events/-/core-events-7.4.0.tgz", + "integrity": "sha512-JavEo4dw7TQdF5pSKjk4RtqLgsG2R/eWRI8vZ3ANKa0ploGAnQR/eMTfSxf6TUH3ElBWLJhi+lvUCkKXPQD+dw==", + "dependencies": { + "ts-dedent": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/storybook" + } + }, + "node_modules/ts-dedent": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/ts-dedent/-/ts-dedent-2.2.0.tgz", + "integrity": "sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ==", + "engines": { + "node": ">=6.10" + } + } + } +} diff --git a/node_modules/@storybook/core-events/jest.config.js b/node_modules/@storybook/core-events/jest.config.js new file mode 100644 index 000000000000..343e4c7a7f32 --- /dev/null +++ b/node_modules/@storybook/core-events/jest.config.js @@ -0,0 +1,7 @@ +const path = require('path'); +const baseConfig = require('../../jest.config.node'); + +module.exports = { + ...baseConfig, + displayName: __dirname.split(path.sep).slice(-2).join(path.posix.sep), +}; diff --git a/node_modules/@storybook/core-events/package.json b/node_modules/@storybook/core-events/package.json new file mode 100644 index 000000000000..c4c1b6ff1017 --- /dev/null +++ b/node_modules/@storybook/core-events/package.json @@ -0,0 +1,98 @@ +{ + "name": "@storybook/core-events", + "version": "7.4.0", + "description": "Event names used in storybook core", + "keywords": [ + "storybook" + ], + "homepage": "https://github.com/storybookjs/storybook/tree/next/code/lib/core-events", + "bugs": { + "url": "https://github.com/storybookjs/storybook/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/storybookjs/storybook.git", + "directory": "code/lib/core-events" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/storybook" + }, + "license": "MIT", + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "node": "./dist/index.js", + "require": "./dist/index.js", + "import": "./dist/index.mjs" + }, + "./preview-errors": { + "types": "./dist/errors/preview-errors.d.ts", + "node": "./dist/errors/preview-errors.js", + "require": "./dist/errors/preview-errors.js", + "import": "./dist/errors/preview-errors.mjs" + }, + "./manager-errors": { + "types": "./dist/errors/manager-errors.d.ts", + "node": "./dist/errors/manager-errors.js", + "require": "./dist/errors/manager-errors.js", + "import": "./dist/errors/manager-errors.mjs" + }, + "./server-errors": { + "types": "./dist/errors/server-errors.d.ts", + "node": "./dist/errors/server-errors.js", + "require": "./dist/errors/server-errors.js", + "import": "./dist/errors/server-errors.mjs" + }, + "./package.json": "./package.json" + }, + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "typesVersions": { + "*": { + "*": [ + "dist/index.d.ts" + ], + "preview-errors": [ + "dist/errors/preview-errors.d.ts" + ], + "manager-errors": [ + "dist/errors/manager-errors.d.ts" + ], + "server-errors": [ + "dist/errors/server-errors.d.ts" + ] + } + }, + "files": [ + "dist/**/*", + "README.md", + "*.js", + "*.d.ts", + "!src/**/*" + ], + "scripts": { + "check": "../../../scripts/prepare/check.ts", + "prep": "../../../scripts/prepare/bundle.ts" + }, + "dependencies": { + "ts-dedent": "^2.0.0" + }, + "devDependencies": { + "typescript": "~4.9.3" + }, + "publishConfig": { + "access": "public" + }, + "bundler": { + "entries": [ + "./src/index.ts", + "./src/errors/preview-errors.ts", + "./src/errors/manager-errors.ts", + "./src/errors/server-errors.ts" + ] + }, + "gitHead": "e6a7fd8a655c69780bc20b9749c2699e44beae17" +} \ No newline at end of file diff --git a/node_modules/ts-dedent/HISTORY.md b/node_modules/ts-dedent/HISTORY.md new file mode 100644 index 000000000000..570b3eeb042e --- /dev/null +++ b/node_modules/ts-dedent/HISTORY.md @@ -0,0 +1,55 @@ +# History + +## vNext + +TBA + +## v2.2.0 + +Add indentation to values with multiline strings & added ESM module + +- Updated all dependencies to their latest version +- Updated CI settings (added node 16, multiple os platforms) +- Moved from Travis CI to Github Actions + +## v2.1.1 + +Security update with dependency changes + +- Updated all dependencies to their latest version +- Updated CI settings (added node 15) + +## v2.1.0 + +- Correctly handle escape sequences when used as a tag +- Add test build to CI +- Only run coverage once per change + +## v2.0.0 + +Fixes #4 + +- ! Might break/change existing behavior +- If a line does not start with whitespace don't remove the indentation + +## v1.2.0 + +Security update with dependency changes + +- Updated all dependencies to their latest version +- Updated CI settings +- Replaced tslint with typescript-eslint +- Removed unused @types/node +- Added lint to run with the test suite + +## v1.1.0 + +Security update with dependency changes + +- Updated all dependencies to their latest version + +## v1.0.0 + +First release includes following functions + +- `function dedent(TemplateStringsArray | string, ...any[]): string diff --git a/node_modules/ts-dedent/README.md b/node_modules/ts-dedent/README.md new file mode 100644 index 000000000000..2a4cb66e7f18 --- /dev/null +++ b/node_modules/ts-dedent/README.md @@ -0,0 +1,107 @@ +# TypeScript Dedent + +[![codecov](https://codecov.io/gh/tamino-martinius/node-ts-dedent/branch/master/graph/badge.svg)](https://codecov.io/gh/tamino-martinius/node-ts-dedent) + +TypeScript package which smartly trims and strips indentation from multi-line strings. + +## Usage Examples + +```js +import dedent from 'dedent'; + +console.log(dedent`A string that gets so long you need to break it over + multiple lines. Luckily dedent is here to keep it + readable without lots of spaces ending up in the string + itself.`); + +console.log(dedent` + A string that gets so long you need to break it over + multiple lines. Luckily dedent is here to keep it + readable without lots of spaces ending up in the string + itself. +`); +``` + +```txt +A string that gets so long you need to break it over +multiple lines. Luckily dedent is here to keep it +readable without lots of spaces ending up in the string +itself. +``` + +--- + +```js +console.log(dedent` + Leading and trailing lines will be trimmed, so you can write something like + this and have it work as you expect: + + * how convenient it is + * that I can use an indented list + - and still have it do the right thing + + That's all. +`); +``` + +```txt +Leading and trailing lines will be trimmed, so you can write something like +this and have it work as you expect: + + * how convenient it is + * that I can use an indented list + - and still have it do the right thing + +That's all. +``` + +--- + +```js +console.log(dedent` + Also works fine + + ${1}. With any kind of + ${2}. Placeholders +`); +``` + +```txt +Also works fine + +1. With any kind of +2. Placeholders +``` + +--- + +```js +console.log(dedent(` + Wait! I lied. Dedent can also be used as a function. +`); +``` + +```txt +Wait! I lied. Dedent can also be used as a function. +``` + +## License + +MIT + +## Based on + +- [dedent](https://www.npmjs.com/package/dedent) by ~dmnd +- [dedent-js](https://www.npmjs.com/package/dedent-js) by ~martin-kolarik + +## Changelog + +See [history](HISTORY.md) for more details. + +- `2.2.0` **2021-08-01** Add indentation to values with multiline strings & added ESM module +- `2.1.1` **2021-03-31** Update dependencies +- `2.1.0` **2021-03-24** Bugfixes +- `2.0.0` **2020-09-28** Bugfixes +- `1.2.0` **2020-09-28** Update dependencies and a couple of minor improvments +- `1.1.0` **2019-07-26** Update dependencies and fixed links in readme +- `1.0.0` **2018-06-14** Initial release diff --git a/node_modules/ts-dedent/esm/index.d.ts b/node_modules/ts-dedent/esm/index.d.ts new file mode 100644 index 000000000000..90db68d3914e --- /dev/null +++ b/node_modules/ts-dedent/esm/index.d.ts @@ -0,0 +1,2 @@ +export declare function dedent(templ: TemplateStringsArray | string, ...values: unknown[]): string; +export default dedent; diff --git a/node_modules/ts-dedent/esm/index.js b/node_modules/ts-dedent/esm/index.js new file mode 100644 index 000000000000..2ffa044570a0 --- /dev/null +++ b/node_modules/ts-dedent/esm/index.js @@ -0,0 +1,38 @@ +export function dedent(templ) { + var values = []; + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + var strings = Array.from(typeof templ === 'string' ? [templ] : templ); + strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, ''); + var indentLengths = strings.reduce(function (arr, str) { + var matches = str.match(/\n([\t ]+|(?!\s).)/g); + if (matches) { + return arr.concat(matches.map(function (match) { var _a, _b; return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0; })); + } + return arr; + }, []); + if (indentLengths.length) { + var pattern_1 = new RegExp("\n[\t ]{" + Math.min.apply(Math, indentLengths) + "}", 'g'); + strings = strings.map(function (str) { return str.replace(pattern_1, '\n'); }); + } + strings[0] = strings[0].replace(/^\r?\n/, ''); + var string = strings[0]; + values.forEach(function (value, i) { + var endentations = string.match(/(?:^|\n)( *)$/); + var endentation = endentations ? endentations[1] : ''; + var indentedValue = value; + if (typeof value === 'string' && value.includes('\n')) { + indentedValue = String(value) + .split('\n') + .map(function (str, i) { + return i === 0 ? str : "" + endentation + str; + }) + .join('\n'); + } + string += indentedValue + strings[i + 1]; + }); + return string; +} +export default dedent; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ts-dedent/esm/index.js.map b/node_modules/ts-dedent/esm/index.js.map new file mode 100644 index 000000000000..afe1eadcfdf7 --- /dev/null +++ b/node_modules/ts-dedent/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,MAAM,CACpB,KAAoC;IACpC,gBAAoB;SAApB,UAAoB,EAApB,qBAAoB,EAApB,IAAoB;QAApB,+BAAoB;;IAEpB,IAAI,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;IAGtE,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,OAAO,CAC/D,gBAAgB,EAChB,EAAE,CACH,CAAC;IAGF,IAAM,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,UAAC,GAAG,EAAE,GAAG;QAC5C,IAAM,OAAO,GAAG,GAAG,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC;QACjD,IAAI,OAAO,EAAE;YACX,OAAO,GAAG,CAAC,MAAM,CACf,OAAO,CAAC,GAAG,CAAC,UAAC,KAAK,gBAAK,OAAA,MAAA,MAAA,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,0CAAE,MAAM,mCAAI,CAAC,CAAA,EAAA,CAAC,CAC3D,CAAC;SACH;QACD,OAAO,GAAG,CAAC;IACb,CAAC,EAAY,EAAE,CAAC,CAAC;IAGjB,IAAI,aAAa,CAAC,MAAM,EAAE;QACxB,IAAM,SAAO,GAAG,IAAI,MAAM,CAAC,aAAW,IAAI,CAAC,GAAG,OAAR,IAAI,EAAQ,aAAa,OAAI,EAAE,GAAG,CAAC,CAAC;QAE1E,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,UAAC,GAAG,IAAK,OAAA,GAAG,CAAC,OAAO,CAAC,SAAO,EAAE,IAAI,CAAC,EAA1B,CAA0B,CAAC,CAAC;KAC5D;IAGD,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAG9C,IAAI,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IAExB,MAAM,CAAC,OAAO,CAAC,UAAC,KAAK,EAAE,CAAC;QAEtB,IAAM,YAAY,GAAG,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC,CAAA;QAClD,IAAM,WAAW,GAAG,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;QACvD,IAAI,aAAa,GAAG,KAAK,CAAA;QAEzB,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;YACrD,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC;iBAC1B,KAAK,CAAC,IAAI,CAAC;iBACX,GAAG,CAAC,UAAC,GAAG,EAAE,CAAC;gBACV,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAG,WAAW,GAAG,GAAK,CAAA;YAC/C,CAAC,CAAC;iBACD,IAAI,CAAC,IAAI,CAAC,CAAC;SACf;QAED,MAAM,IAAI,aAAa,GAAG,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3C,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/ts-dedent/package.json b/node_modules/ts-dedent/package.json new file mode 100644 index 000000000000..73f3b231b4de --- /dev/null +++ b/node_modules/ts-dedent/package.json @@ -0,0 +1,68 @@ +{ + "name": "ts-dedent", + "version": "2.2.0", + "description": "TypeScript package which smartly trims and strips indentation from multi-line strings", + "author": "Tamino Martinius ", + "main": "./dist/index.js", + "module": "./esm/index.js", + "jsnext:main": "./dist/index.js", + "typings": "./dist/index.d.ts", + "license": "MIT", + "files": [ + "dist", + "esm", + "src" + ], + "repository": { + "type": "git", + "url": "https://github.com/tamino-martinius/node-ts-dedent.git" + }, + "keywords": [ + "dedent", + "deindent", + "indentation", + "multi-line string", + "multiline strings", + "template literals", + "template strings", + "ts", + "typescript", + "es6", + "harmony" + ], + "engines": { + "node": ">=6.10" + }, + "scripts": { + "coverage": "rm -rf coverage* && jest --coverage", + "pretest": "npm run lint", + "test": "jest", + "lint": "eslint .", + "watch": "tsc -w", + "ci": "npm run coverage && codecov", + "compile": "rm -rf dist/* && rm -rf esm/* && tsc --module commonjs --outdir dist && tsc --module es6 --outdir esm", + "preversion": "npm run compile && git add ." + }, + "devDependencies": { + "@types/jest": "^26.0.24", + "@typescript-eslint/eslint-plugin": "^4.28.5", + "@typescript-eslint/parser": "^4.28.5", + "codecov": "^3.8.3", + "eslint": "^7.32.0", + "jest": "^27.0.6", + "ts-jest": "^27.0.4", + "typescript": "~4.3.5" + }, + "jest": { + "transform": { + ".ts": "ts-jest" + }, + "testRegex": "\\.(test|spec)\\.ts$", + "moduleFileExtensions": [ + "ts", + "tsx", + "js", + "json" + ] + } +} diff --git a/node_modules/ts-dedent/src/__tests__/index.spec.ts b/node_modules/ts-dedent/src/__tests__/index.spec.ts new file mode 100644 index 000000000000..5d0dee0d4a7b --- /dev/null +++ b/node_modules/ts-dedent/src/__tests__/index.spec.ts @@ -0,0 +1,554 @@ +import { dedent } from '..'; + +function tag(strings: TemplateStringsArray, ...values: number[]) { + let string = strings[0]; + + values.forEach((value, i) => { + string += 2 * value + strings[i + 1]; + }); + + return string; +} + +describe('dedent tag', () => { + it('should work with empty string', () => { + expect(dedent``).toEqual(''); + }); + + it('should work with tabs', () => { + expect(dedent`Line #1 + Line #2 + Line #3`).toEqual('Line #1\nLine #2\nLine #3'); + + expect(dedent`Line #${1} + Line #${2} + Line #${3}`).toEqual('Line #1\nLine #2\nLine #3'); + + expect(dedent`${1}. line #${1} + ${2}. line #${2} + ${3}. line`).toEqual('1. line #1\n2. line #2\n3. line'); + }); + + it('should work with spaces', () => { + expect(dedent`Line #1 + Line #2 + Line #3`).toEqual('Line #1\nLine #2\nLine #3'); + + expect(dedent`Line #${1} + Line #${2} + Line #${3}`).toEqual('Line #1\nLine #2\nLine #3'); + + expect(dedent`${1}. line #${1} + ${2}. line #${2} + ${3}. line`).toEqual('1. line #1\n2. line #2\n3. line'); + }); + + it('should remove leading/trailing line break', () => { + expect( + dedent` + Line #1 + Line #2 + Line #3 + `, + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + dedent` +Line #1 + Line #2 + Line #3 + `, + ).toEqual('Line #1\n\tLine #2\n\tLine #3'); + + expect( + dedent` + Line #${1} + Line #${2} + Line #${3} + `, + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + dedent` +Line #${1} + Line #${2} + Line #${3} + `, + ).toEqual('Line #1\n\tLine #2\n\tLine #3'); + + expect( + dedent` + ${1}. line #${1} + ${2}. line #${2} + ${3}. line + `, + ).toEqual('1. line #1\n2. line #2\n3. line'); + }); + + it('should not remove more than one leading/trailing line break', () => { + expect( + dedent` + + Line #1 + Line #2 + Line #3 + + `, + ).toEqual('\nLine #1\nLine #2\nLine #3\n'); + + expect( + dedent` + + Line #${1} + Line #${2} + Line #${3} + + `, + ).toEqual('\nLine #1\nLine #2\nLine #3\n'); + + expect( + dedent` + + ${1}. line #${1} + ${2}. line #${2} + ${3}. line + + `, + ).toEqual('\n1. line #1\n2. line #2\n3. line\n'); + }); + + it('should remove the same number of tabs/spaces from each line', () => { + expect( + dedent` + Line #1 + Line #2 + Line #3 + `, + ).toEqual('Line #1\n\tLine #2\n\t\tLine #3'); + + expect( + dedent` + Line #${1} + Line #${2} + Line #${3} + `, + ).toEqual('Line #1\n\tLine #2\n\t\tLine #3'); + + expect( + dedent` + ${1}. line #${1} + ${2}. line #${2} + ${3}. line + `, + ).toEqual('1. line #1\n\t2. line #2\n\t\t3. line'); + }); + + it("should ignore the last line if it doesn't contain anything else than whitespace", () => { + expect( + (() => { + return dedent` + Line #1 + Line #2 + Line #3 + `; + })(), + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + (() => { + return dedent` + Line #${1} + Line #${2} + Line #${3} + `; + })(), + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + (() => { + return dedent` + ${1}. line #${1} + ${2}. line #${2} + ${3}. line + `; + })(), + ).toEqual('1. line #1\n2. line #2\n3. line'); + }); + + it("should process escape sequences", () => { + expect( + (() => { + return dedent` + \${not interpolated} + \` + `; + })(), + ).toEqual('${not interpolated}\n`'); + }); +}); + +describe('dedent() function', () => { + it('should work with tabs', () => { + expect( + dedent(`Line #1 + Line #2 + Line #3`), + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + dedent(`Line #${1} + Line #${2} + Line #${3}`), + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + dedent(`${1}. line #${1} + ${2}. line #${2} + ${3}. line`), + ).toEqual('1. line #1\n2. line #2\n3. line'); + }); + + it('should work with spaces', () => { + expect( + dedent(`Line #1 + Line #2 + Line #3`), + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + dedent(`Line #${1} + Line #${2} + Line #${3}`), + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + dedent(`${1}. line #${1} + ${2}. line #${2} + ${3}. line`), + ).toEqual('1. line #1\n2. line #2\n3. line'); + }); + + it('should remove leading/trailing line break', () => { + expect( + dedent(` + Line #1 + Line #2 + Line #3 + `), + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + dedent(` +Line #1 + Line #2 + Line #3 + `), + ).toEqual('Line #1\n\tLine #2\n\tLine #3'); + + expect( + dedent(` + Line #${1} + Line #${2} + Line #${3} + `), + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + dedent(` +Line #${1} + Line #${2} + Line #${3} + `), + ).toEqual('Line #1\n\tLine #2\n\tLine #3'); + + expect( + dedent(` + ${1}. line #${1} + ${2}. line #${2} + ${3}. line + `), + ).toEqual('1. line #1\n2. line #2\n3. line'); + }); + + it('should not remove more than one leading/trailing line break', () => { + expect( + dedent(` + + Line #1 + Line #2 + Line #3 + + `), + ).toEqual('\nLine #1\nLine #2\nLine #3\n'); + + expect( + dedent(` + + Line #${1} + Line #${2} + Line #${3} + + `), + ).toEqual('\nLine #1\nLine #2\nLine #3\n'); + + expect( + dedent(` + + ${1}. line #${1} + ${2}. line #${2} + ${3}. line + + `), + ).toEqual('\n1. line #1\n2. line #2\n3. line\n'); + }); + + it('should remove the same number of tabs/spaces from each line', () => { + expect( + dedent(` + Line #1 + Line #2 + Line #3 + `), + ).toEqual('Line #1\n\tLine #2\n\t\tLine #3'); + + expect( + dedent(` + Line #${1} + Line #${2} + Line #${3} + `), + ).toEqual('Line #1\n\tLine #2\n\t\tLine #3'); + + expect( + dedent(` + ${1}. line #${1} + ${2}. line #${2} + ${3}. line + `), + ).toEqual('1. line #1\n\t2. line #2\n\t\t3. line'); + }); + + it("should ignore the last line if it doesn't contain anything else than whitespace", () => { + expect( + (() => { + return dedent(` + Line #1 + Line #2 + Line #3 + `); + })(), + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + (() => { + return dedent(` + Line #${1} + Line #${2} + Line #${3} + `); + })(), + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + (() => { + return dedent(` + ${1}. line #${1} + ${2}. line #${2} + ${3}. line + `); + })(), + ).toEqual('1. line #1\n2. line #2\n3. line'); + }); + + it("should process escape sequences", () => { + expect( + dedent(` + \${not interpolated} + \` + `), + ).toEqual('${not interpolated}\n`'); + }); +}); + +describe('dedent() function with custom tag', () => { + it('should work with tabs', () => { + expect( + dedent(tag`Line #1 + Line #2 + Line #3`), + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + dedent(tag`Line #${1} + Line #${2} + Line #${3}`), + ).toEqual('Line #2\nLine #4\nLine #6'); + + expect( + dedent(tag`${1}. line #${1} + ${2}. line #${2} + ${3}. line`), + ).toEqual('2. line #2\n4. line #4\n6. line'); + }); + + it('should work with spaces', () => { + expect( + dedent(tag`Line #1 + Line #2 + Line #3`), + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + dedent(tag`Line #${1} + Line #${2} + Line #${3}`), + ).toEqual('Line #2\nLine #4\nLine #6'); + + expect( + dedent(tag`${1}. line #${1} + ${2}. line #${2} + ${3}. line`), + ).toEqual('2. line #2\n4. line #4\n6. line'); + }); + + it('should remove leading/trailing line break', () => { + expect( + dedent(tag` + Line #1 + Line #2 + Line #3 + `), + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + dedent(tag` +Line #1 + Line #2 + Line #3 + `), + ).toEqual('Line #1\n\tLine #2\n\tLine #3'); + + expect( + dedent(tag` + Line #${1} + Line #${2} + Line #${3} + `), + ).toEqual('Line #2\nLine #4\nLine #6'); + + expect( + dedent(tag` +Line #${1} + Line #${2} + Line #${3} + `), + ).toEqual('Line #2\n\tLine #4\n\tLine #6'); + + expect( + dedent(tag` + ${1}. line #${1} + ${2}. line #${2} + ${3}. line + `), + ).toEqual('2. line #2\n4. line #4\n6. line'); + }); + + it('should not remove more than one leading/trailing line break', () => { + expect( + dedent(tag` + + Line #1 + Line #2 + Line #3 + + `), + ).toEqual('\nLine #1\nLine #2\nLine #3\n'); + + expect( + dedent(tag` + + Line #${1} + Line #${2} + Line #${3} + + `), + ).toEqual('\nLine #2\nLine #4\nLine #6\n'); + + expect( + dedent(tag` + + ${1}. line #${1} + ${2}. line #${2} + ${3}. line + + `), + ).toEqual('\n2. line #2\n4. line #4\n6. line\n'); + }); + + it('should remove the same number of tabs/spaces from each line', () => { + expect( + dedent(tag` + Line #1 + Line #2 + Line #3 + `), + ).toEqual('Line #1\n\tLine #2\n\t\tLine #3'); + + expect( + dedent(tag` + Line #${1} + Line #${2} + Line #${3} + `), + ).toEqual('Line #2\n\tLine #4\n\t\tLine #6'); + + expect( + dedent(tag` + ${1}. line #${1} + ${2}. line #${2} + ${3}. line + `), + ).toEqual('2. line #2\n\t4. line #4\n\t\t6. line'); + }); + + it("should ignore the last line if it doesn't contain anything else than whitespace", () => { + expect( + (() => { + return dedent(tag` + Line #1 + Line #2 + Line #3 + `); + })(), + ).toEqual('Line #1\nLine #2\nLine #3'); + + expect( + (() => { + return dedent(tag` + Line #${1} + Line #${2} + Line #${3} + `); + })(), + ).toEqual('Line #2\nLine #4\nLine #6'); + + expect( + (() => { + return dedent(tag` + ${1}. line #${1} + ${2}. line #${2} + ${3}. line + `); + })(), + ).toEqual('2. line #2\n4. line #4\n6. line'); + }); + + it("should process escape sequences", () => { + expect( + dedent(tag` + \${not interpolated} + \` + `), + ).toEqual('${not interpolated}\n`'); + }); +}); diff --git a/node_modules/ts-dedent/src/__tests__/issue-21.spec.ts b/node_modules/ts-dedent/src/__tests__/issue-21.spec.ts new file mode 100644 index 000000000000..9da50ff5e935 --- /dev/null +++ b/node_modules/ts-dedent/src/__tests__/issue-21.spec.ts @@ -0,0 +1,88 @@ +import { dedent } from '..'; + +describe('Issue 21', () => { + it('should dedent nested dedents correctly', () => { + const fieldDocs = dedent` + * a + * b + * c + ` + + const a = dedent` + /** + ${fieldIntro()} + * + ${fieldDocs} + * + ${fieldExample()} + */ + ` + + function fieldIntro() { + return dedent` + * 0 + ` + } + function fieldExample() { + return dedent` + * d + ` + } + + const expected = `/** + * 0 + * + * a + * b + * c + * + * d + */` + + expect(a).toEqual(expected); + }); + + /** + * Could not find a way to handle this but is an edge case we'd like to solve eventually + */ + it.skip('should handle function calls of nested dedents correctly', () => { + const fieldDocs = dedent(` + * a + * b + * c + `) + + const a = dedent(` + /** + ${fieldIntro()} + * + ${fieldDocs} + * + ${fieldExample()} + */ + `) + + function fieldIntro() { + return dedent(` + * 0 + `) + } + function fieldExample() { + return dedent(` + * d + `) + } + + const expected = `/** + * 0 + * + * a + * b + * c + * + * d + */` + + expect(a).toEqual(expected); + }); +}); diff --git a/node_modules/ts-dedent/src/index.ts b/node_modules/ts-dedent/src/index.ts new file mode 100644 index 000000000000..fb52fdf052e6 --- /dev/null +++ b/node_modules/ts-dedent/src/index.ts @@ -0,0 +1,58 @@ +export function dedent( + templ: TemplateStringsArray | string, + ...values: unknown[] +): string { + let strings = Array.from(typeof templ === 'string' ? [templ] : templ); + + // 1. Remove trailing whitespace. + strings[strings.length - 1] = strings[strings.length - 1].replace( + /\r?\n([\t ]*)$/, + '', + ); + + // 2. Find all line breaks to determine the highest common indentation level. + const indentLengths = strings.reduce((arr, str) => { + const matches = str.match(/\n([\t ]+|(?!\s).)/g); + if (matches) { + return arr.concat( + matches.map((match) => match.match(/[\t ]/g)?.length ?? 0), + ); + } + return arr; + }, []); + + // 3. Remove the common indentation from all strings. + if (indentLengths.length) { + const pattern = new RegExp(`\n[\t ]{${Math.min(...indentLengths)}}`, 'g'); + + strings = strings.map((str) => str.replace(pattern, '\n')); + } + + // 4. Remove leading whitespace. + strings[0] = strings[0].replace(/^\r?\n/, ''); + + // 5. Perform interpolation. + let string = strings[0]; + + values.forEach((value, i) => { + // 5.1 Read current indentation level + const endentations = string.match(/(?:^|\n)( *)$/) + const endentation = endentations ? endentations[1] : '' + let indentedValue = value + // 5.2 Add indentation to values with multiline strings + if (typeof value === 'string' && value.includes('\n')) { + indentedValue = String(value) + .split('\n') + .map((str, i) => { + return i === 0 ? str : `${endentation}${str}` + }) + .join('\n'); + } + + string += indentedValue + strings[i + 1]; + }); + + return string; +} + +export default dedent; diff --git a/yarn.lock b/yarn.lock index 60e814efe6f8..f44b5fc79564 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1,11 +1,15 @@ -# This file is generated by running "yarn install" inside your project. -# Manual changes might be lost - proceed with caution! +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 -__metadata: - version: 6 -"@storybook/root@workspace:.": - version: 0.0.0-use.local - resolution: "@storybook/root@workspace:." - languageName: unknown - linkType: soft +"@storybook/core-events@^7.4.0": + version "7.4.0" + resolved "https://registry.npmjs.org/@storybook/core-events/-/core-events-7.4.0.tgz" + integrity sha512-JavEo4dw7TQdF5pSKjk4RtqLgsG2R/eWRI8vZ3ANKa0ploGAnQR/eMTfSxf6TUH3ElBWLJhi+lvUCkKXPQD+dw== + dependencies: + ts-dedent "^2.0.0" + +ts-dedent@^2.0.0: + version "2.2.0" + resolved "https://registry.npmjs.org/ts-dedent/-/ts-dedent-2.2.0.tgz" + integrity sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ== From 5a336071e8a63b974179b6a6f8b635aa6b1eaac0 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Wed, 29 Nov 2023 14:25:49 +0100 Subject: [PATCH 4/5] fixes --- code/lib/manager-api/src/index.tsx | 2 + code/lib/manager-api/src/lib/store-setup.ts | 2 + code/lib/manager-api/src/lib/stories.ts | 1 - code/lib/manager-api/src/modules/channel.ts | 10 +-- code/lib/manager-api/src/modules/globals.ts | 10 +-- code/lib/manager-api/src/modules/layout.ts | 2 +- code/lib/manager-api/src/modules/refs.ts | 1 + code/lib/manager-api/src/modules/shortcuts.ts | 2 +- code/lib/manager-api/src/modules/stories.ts | 76 +++++++++++++------ code/lib/manager-api/src/modules/url.ts | 16 ++-- code/lib/manager-api/src/modules/versions.ts | 8 +- code/lib/manager-api/src/modules/whatsnew.ts | 8 +- 12 files changed, 85 insertions(+), 53 deletions(-) diff --git a/code/lib/manager-api/src/index.tsx b/code/lib/manager-api/src/index.tsx index 1c1798830583..c9098edc3844 100644 --- a/code/lib/manager-api/src/index.tsx +++ b/code/lib/manager-api/src/index.tsx @@ -305,6 +305,7 @@ function ManagerConsumer

({ const comboData = filterer.current(managerContext); const comboDataArray = useMemo(() => { + // @ts-expect-error (No overload matches this call) return [...Object.entries(comboData).reduce((acc, keyval) => acc.concat(keyval), [])]; }, [managerContext.state]); @@ -412,6 +413,7 @@ export function useSharedState(stateId: string, defaultState?: S) { useEffect(() => { if (quicksync) { + // @ts-expect-error (Argument of type 'S | undefined' is not assignable) api.setAddonState(stateId, defaultState); } }, [quicksync]); diff --git a/code/lib/manager-api/src/lib/store-setup.ts b/code/lib/manager-api/src/lib/store-setup.ts index 3ee481a35013..c29a0b2ad282 100644 --- a/code/lib/manager-api/src/lib/store-setup.ts +++ b/code/lib/manager-api/src/lib/store-setup.ts @@ -5,9 +5,11 @@ import { parse, stringify } from 'telejson'; // setting up the store, overriding set and get to use telejson export default (_: any) => { _.fn('set', function (key: string, data: object) { + // @ts-expect-error('this' implicitly has type 'any') return _.set(this._area, this._in(key), stringify(data, { maxDepth: 50 })); }); _.fn('get', function (key: string, alt: string) { + // @ts-expect-error('this' implicitly has type 'any') const value = _.get(this._area, this._in(key)); return value !== null ? parse(value) : alt || value; }); diff --git a/code/lib/manager-api/src/lib/stories.ts b/code/lib/manager-api/src/lib/stories.ts index 0ed013cd9ebc..dffc3dd45a86 100644 --- a/code/lib/manager-api/src/lib/stories.ts +++ b/code/lib/manager-api/src/lib/stories.ts @@ -21,7 +21,6 @@ import type { API_HashEntry, SetStoriesPayload, StoryIndexV2, - Renderer, } from '@storybook/types'; // eslint-disable-next-line import/no-cycle import { type API, combineParameters, type State } from '../index'; diff --git a/code/lib/manager-api/src/modules/channel.ts b/code/lib/manager-api/src/modules/channel.ts index c83c342c5253..0ab1dc910087 100644 --- a/code/lib/manager-api/src/modules/channel.ts +++ b/code/lib/manager-api/src/modules/channel.ts @@ -56,12 +56,12 @@ export const init: ModuleFn = ({ provider }) => { const api: SubAPI = { getChannel: () => provider.channel, on: (type, handler) => { - provider.channel.on(type, handler); + provider.channel?.on(type, handler); - return () => provider.channel.off(type, handler); + return () => provider.channel?.off(type, handler); }, - off: (type, handler) => provider.channel.off(type, handler), - once: (type, handler) => provider.channel.once(type, handler), + off: (type, handler) => provider.channel?.off(type, handler), + once: (type, handler) => provider.channel?.once(type, handler), emit: (type, data, ...args) => { if ( data?.options?.target && @@ -73,7 +73,7 @@ export const init: ModuleFn = ({ provider }) => { ? `storybook-ref-${data.options.target}` : 'storybook-preview-iframe'; } - provider.channel.emit(type, data, ...args); + provider.channel?.emit(type, data, ...args); }, collapseAll: () => { api.emit(STORIES_COLLAPSE_ALL, {}); diff --git a/code/lib/manager-api/src/modules/globals.ts b/code/lib/manager-api/src/modules/globals.ts index 17c35bbb7224..e9f33a75e202 100644 --- a/code/lib/manager-api/src/modules/globals.ts +++ b/code/lib/manager-api/src/modules/globals.ts @@ -35,14 +35,14 @@ export interface SubAPI { export const init: ModuleFn = ({ store, fullAPI, provider }) => { const api: SubAPI = { getGlobals() { - return store.getState().globals; + return store.getState().globals as Globals; }, getGlobalTypes() { - return store.getState().globalTypes; + return store.getState().globalTypes as GlobalTypes; }, updateGlobals(newGlobals) { // Only emit the message to the local ref - provider.channel.emit(UPDATE_GLOBALS, { + provider.channel?.emit(UPDATE_GLOBALS, { globals: newGlobals, options: { target: 'storybook-preview-iframe', @@ -62,7 +62,7 @@ export const init: ModuleFn = ({ store, fullAPI, provider }) = } }; - provider.channel.on( + provider.channel?.on( GLOBALS_UPDATED, function handleGlobalsUpdated(this: any, { globals }: { globals: Globals }) { const { ref } = getEventMetadata(this, fullAPI)!; @@ -78,7 +78,7 @@ export const init: ModuleFn = ({ store, fullAPI, provider }) = ); // Emitted by the preview on initialization - provider.channel.on( + provider.channel?.on( SET_GLOBALS, function handleSetStories(this: any, { globals, globalTypes }: SetGlobalsPayload) { const { ref } = getEventMetadata(this, fullAPI)!; diff --git a/code/lib/manager-api/src/modules/layout.ts b/code/lib/manager-api/src/modules/layout.ts index a7d529868613..7c8401e3c173 100644 --- a/code/lib/manager-api/src/modules/layout.ts +++ b/code/lib/manager-api/src/modules/layout.ts @@ -385,7 +385,7 @@ export const init: ModuleFn = ({ store, provider, singleStory const persisted = pick(store.getState(), 'layout', 'selectedPanel'); - provider.channel.on(SET_CONFIG, () => { + provider.channel?.on(SET_CONFIG, () => { api.setOptions(merge(api.getInitialOptions(), persisted)); }); diff --git a/code/lib/manager-api/src/modules/refs.ts b/code/lib/manager-api/src/modules/refs.ts index f1d52c2adf65..8a5159e9fdb9 100644 --- a/code/lib/manager-api/src/modules/refs.ts +++ b/code/lib/manager-api/src/modules/refs.ts @@ -295,6 +295,7 @@ export const init: ModuleFn = ( ) : storyIndex; + // @ts-expect-error (could be undefined) index = transformStoryIndexToStoriesHash(storyIndex, { provider, docsOptions, diff --git a/code/lib/manager-api/src/modules/shortcuts.ts b/code/lib/manager-api/src/modules/shortcuts.ts index 25f9d14095c6..d050028f8b8b 100644 --- a/code/lib/manager-api/src/modules/shortcuts.ts +++ b/code/lib/manager-api/src/modules/shortcuts.ts @@ -392,7 +392,7 @@ export const init: ModuleFn = ({ store, fullAPI, provider }) => { }); // Also listen to keydown events sent over the channel - provider.channel.on(PREVIEW_KEYDOWN, (data: { event: KeyboardEventLike }) => { + provider.channel?.on(PREVIEW_KEYDOWN, (data: { event: KeyboardEventLike }) => { api.handleKeydownEvent(data.event); }); }; diff --git a/code/lib/manager-api/src/modules/stories.ts b/code/lib/manager-api/src/modules/stories.ts index 828eabe1aa0c..b4a027f9be1c 100644 --- a/code/lib/manager-api/src/modules/stories.ts +++ b/code/lib/manager-api/src/modules/stories.ts @@ -93,7 +93,7 @@ export interface SubAPI { * @param {string} [refsId] - The ID of the refs to use for resolving the story. * @returns {API_HashEntry} - The hash entry corresponding to the given story ID. */ - resolveStory: (storyId: StoryId, refsId?: string) => API_HashEntry; + resolveStory: (storyId: StoryId, refsId?: string) => API_HashEntry | undefined; /** * Selects the first story to display in the Storybook UI. * @@ -322,9 +322,10 @@ export const init: ModuleFn = ({ resolveStory: (storyId, refId) => { const { refs, index } = store.getState(); if (refId && !refs[refId]) { - return null; + return undefined; } if (refId) { + // @ts-expect-error (possibly undefined) return refs[refId].index ? refs[refId].index[storyId] : undefined; } return index ? index[storyId] : undefined; @@ -353,7 +354,7 @@ export const init: ModuleFn = ({ }, getCurrentParameter: (parameterName) => { const { storyId, refId } = store.getState(); - const parameters = api.getParameters({ storyId, refId }, parameterName); + const parameters = api.getParameters({ storyId, refId: refId as string }, parameterName); // FIXME Returning falsey parameters breaks a bunch of toolbars code, // so this strange logic needs to be here until various client code is updated. return parameters || undefined; @@ -368,6 +369,11 @@ export const init: ModuleFn = ({ } const hash = refId ? refs[refId].index || {} : index; + + if (!hash) { + return; + } + const result = api.findSiblingStoryId(storyId, hash, direction, true); if (result) { @@ -384,6 +390,11 @@ export const init: ModuleFn = ({ } const hash = story.refId ? refs[story.refId].index : index; + + if (!hash) { + return; + } + const result = api.findSiblingStoryId(storyId, hash, direction, false); if (result) { @@ -392,6 +403,9 @@ export const init: ModuleFn = ({ }, selectFirstStory: () => { const { index } = store.getState(); + if (!index) { + return; + } const firstStory = Object.keys(index).find((id) => index[id].type === 'story'); if (firstStory) { @@ -409,6 +423,10 @@ export const init: ModuleFn = ({ const kindSlug = storyId?.split('--', 2)[0]; + if (!hash) { + return; + } + if (!name) { // Find the entry (group, component or story) that is referred to const entry = titleOrId ? hash[titleOrId] || hash[sanitize(titleOrId)] : hash[kindSlug]; @@ -491,15 +509,15 @@ export const init: ModuleFn = ({ }, updateStoryArgs: (story, updatedArgs) => { const { id: storyId, refId } = story; - provider.channel.emit(UPDATE_STORY_ARGS, { + provider.channel?.emit(UPDATE_STORY_ARGS, { storyId, updatedArgs, options: { target: refId }, }); }, - resetStoryArgs: (story, argNames?: [string]) => { + resetStoryArgs: (story, argNames) => { const { id: storyId, refId } = story; - provider.channel.emit(RESET_STORY_ARGS, { + provider.channel?.emit(RESET_STORY_ARGS, { storyId, argNames, options: { target: refId }, @@ -519,7 +537,7 @@ export const init: ModuleFn = ({ } await api.setIndex(storyIndex); - } catch (err) { + } catch (err: any) { await store.setState({ indexError: err }); } }, @@ -547,6 +565,9 @@ export const init: ModuleFn = ({ ): Promise => { if (!ref) { const { index } = store.getState(); + if (!index) { + return; + } index[storyId] = { ...index[storyId], ...update, @@ -568,6 +589,9 @@ export const init: ModuleFn = ({ ): Promise => { if (!ref) { const { index } = store.getState(); + if (!index) { + return; + } index[docsId] = { ...index[docsId], ...update, @@ -643,7 +667,7 @@ export const init: ModuleFn = ({ // On initial load, the local iframe will select the first story (or other "selection specifier") // and emit STORY_SPECIFIED with the id. We need to ensure we respond to this change. - provider.channel.on( + provider.channel?.on( STORY_SPECIFIED, function handler( this: any, @@ -664,7 +688,7 @@ export const init: ModuleFn = ({ state.path === '/' || state.viewMode === 'story' || state.viewMode === 'docs'; const stateHasSelection = state.viewMode && state.storyId; const stateSelectionDifferent = state.viewMode !== viewMode || state.storyId !== storyId; - const { type } = state.index[state.storyId] || {}; + const { type } = state.index?.[state.storyId] || {}; const isStory = !(type === 'root' || type === 'component' || type === 'group'); /** @@ -677,7 +701,7 @@ export const init: ModuleFn = ({ if (isCanvasRoute) { if (stateHasSelection && stateSelectionDifferent && isStory) { // The manager state is correct, the preview state is lagging behind - provider.channel.emit(SET_CURRENT_STORY, { + provider.channel?.emit(SET_CURRENT_STORY, { storyId: state.storyId, viewMode: state.viewMode, }); @@ -694,12 +718,12 @@ export const init: ModuleFn = ({ // Until the ref has a selection, it will not render anything (e.g. while waiting for // the preview.js file or the index to load). Once it has a selection, it will render its own // preparing spinner. - provider.channel.on(CURRENT_STORY_WAS_SET, function handler(this: any) { + provider.channel?.on(CURRENT_STORY_WAS_SET, function handler(this: any) { const { ref } = getEventMetadata(this, fullAPI)!; api.setPreviewInitialized(ref); }); - provider.channel.on(STORY_CHANGED, function handler(this: any) { + provider.channel?.on(STORY_CHANGED, function handler(this: any) { const { sourceType } = getEventMetadata(this, fullAPI)!; if (sourceType === 'local') { @@ -711,7 +735,7 @@ export const init: ModuleFn = ({ } }); - provider.channel.on( + provider.channel?.on( STORY_PREPARED, function handler(this: any, { id, ...update }: StoryPreparedPayload) { const { ref, sourceType } = getEventMetadata(this, fullAPI)!; @@ -728,6 +752,10 @@ export const init: ModuleFn = ({ if (sourceType === 'local') { const { storyId, index, refId } = store.getState(); + if (!index) { + return; + } + // create a list of related stories to be preloaded const toBePreloaded = Array.from( new Set([ @@ -736,7 +764,7 @@ export const init: ModuleFn = ({ ]) ).filter(Boolean); - provider.channel.emit(PRELOAD_ENTRIES, { + provider.channel?.emit(PRELOAD_ENTRIES, { ids: toBePreloaded, options: { target: refId }, }); @@ -744,7 +772,7 @@ export const init: ModuleFn = ({ } ); - provider.channel.on( + provider.channel?.on( DOCS_PREPARED, function handler(this: any, { id, ...update }: DocsPreparedPayload) { const { ref } = getEventMetadata(this, fullAPI)!; @@ -752,7 +780,7 @@ export const init: ModuleFn = ({ } ); - provider.channel.on(SET_INDEX, function handler(this: any, index: API_PreparedStoryIndex) { + provider.channel?.on(SET_INDEX, function handler(this: any, index: API_PreparedStoryIndex) { const { ref } = getEventMetadata(this, fullAPI)!; if (!ref) { @@ -765,7 +793,7 @@ export const init: ModuleFn = ({ }); // For composition back-compatibilty - provider.channel.on(SET_STORIES, function handler(this: any, data: SetStoriesPayload) { + provider.channel?.on(SET_STORIES, function handler(this: any, data: SetStoriesPayload) { const { ref } = getEventMetadata(this, fullAPI)!; const setStoriesData = data.v ? denormalizeStoryParameters(data) : data.stories; @@ -776,7 +804,7 @@ export const init: ModuleFn = ({ } }); - provider.channel.on( + provider.channel?.on( SELECT_STORY, function handler( this: any, @@ -806,7 +834,7 @@ export const init: ModuleFn = ({ } ); - provider.channel.on( + provider.channel?.on( STORY_ARGS_UPDATED, function handleStoryArgsUpdated( this: any, @@ -818,17 +846,17 @@ export const init: ModuleFn = ({ ); // When there's a preview error, we don't show it in the manager, but simply - provider.channel.on(CONFIG_ERROR, function handleConfigError(this: any, err: any) { + provider.channel?.on(CONFIG_ERROR, function handleConfigError(this: any, err: any) { const { ref } = getEventMetadata(this, fullAPI)!; api.setPreviewInitialized(ref); }); - provider.channel.on(STORY_MISSING, function handleConfigError(this: any, err: any) { + provider.channel?.on(STORY_MISSING, function handleConfigError(this: any, err: any) { const { ref } = getEventMetadata(this, fullAPI)!; api.setPreviewInitialized(ref); }); - provider.channel.on(SET_CONFIG, () => { + provider.channel?.on(SET_CONFIG, () => { const config = provider.getConfig(); if (config?.sidebar?.filters) { store.setState({ @@ -845,7 +873,7 @@ export const init: ModuleFn = ({ return { api, state: { - storyId: initialStoryId, + storyId: initialStoryId as string, viewMode: initialViewMode, hasCalledSetOptions: false, previewInitialized: false, @@ -854,7 +882,7 @@ export const init: ModuleFn = ({ }, init: async () => { if (FEATURES?.storyStoreV7) { - provider.channel.on(STORY_INDEX_INVALIDATED, () => api.fetchIndex()); + provider.channel?.on(STORY_INDEX_INVALIDATED, () => api.fetchIndex()); await api.fetchIndex(); } }, diff --git a/code/lib/manager-api/src/modules/url.ts b/code/lib/manager-api/src/modules/url.ts index 27d8cef5258f..e9431f04a1f5 100644 --- a/code/lib/manager-api/src/modules/url.ts +++ b/code/lib/manager-api/src/modules/url.ts @@ -10,7 +10,7 @@ import { queryFromLocation, buildArgsParam } from '@storybook/router'; import { dequal as deepEqual } from 'dequal'; import { global } from '@storybook/global'; -import type { API_Layout, API_UI } from '@storybook/types'; +import type { API_Layout, API_UI, Args } from '@storybook/types'; import type { ModuleArgs, ModuleFn } from '../lib/types'; import { defaultLayoutState } from './layout'; @@ -101,7 +101,7 @@ const initialUrlSupport = ({ }; export interface QueryParams { - [key: string]: string | null; + [key: string]: string | undefined; } /** @@ -185,7 +185,7 @@ export const init: ModuleFn = (moduleArgs) => { }; if (!deepEqual(customQueryParams, update)) { store.setState({ customQueryParams: update }); - provider.channel.emit(UPDATE_QUERY_PARAMS, update); + provider.channel?.emit(UPDATE_QUERY_PARAMS, update); } }, navigateUrl(url, options) { @@ -204,15 +204,15 @@ export const init: ModuleFn = (moduleArgs) => { if (currentStory?.type !== 'story') return; const { args, initialArgs } = currentStory; - const argsString = buildArgsParam(initialArgs, args); + const argsString = buildArgsParam(initialArgs, args as Args); navigateTo(path, { ...queryParams, args: argsString }, { replace: true }); api.setQueryParams({ args: argsString }); }; - provider.channel.on(SET_CURRENT_STORY, () => updateArgsParam()); + provider.channel?.on(SET_CURRENT_STORY, () => updateArgsParam()); let handleOrId: any; - provider.channel.on(STORY_ARGS_UPDATED, () => { + provider.channel?.on(STORY_ARGS_UPDATED, () => { if ('requestIdleCallback' in globalWindow) { if (handleOrId) globalWindow.cancelIdleCallback(handleOrId); handleOrId = globalWindow.requestIdleCallback(updateArgsParam, { timeout: 1000 }); @@ -222,14 +222,14 @@ export const init: ModuleFn = (moduleArgs) => { } }); - provider.channel.on(GLOBALS_UPDATED, ({ globals, initialGlobals }: any) => { + provider.channel?.on(GLOBALS_UPDATED, ({ globals, initialGlobals }: any) => { const { path, queryParams } = api.getUrlState(); const globalsString = buildArgsParam(initialGlobals, globals); navigateTo(path, { ...queryParams, globals: globalsString }, { replace: true }); api.setQueryParams({ globals: globalsString }); }); - provider.channel.on(NAVIGATE_URL, (url: string, options: NavigateOptions) => { + provider.channel?.on(NAVIGATE_URL, (url: string, options: NavigateOptions) => { api.navigateUrl(url, options); }); diff --git a/code/lib/manager-api/src/modules/versions.ts b/code/lib/manager-api/src/modules/versions.ts index 15a8a724e651..a230da3a501f 100644 --- a/code/lib/manager-api/src/modules/versions.ts +++ b/code/lib/manager-api/src/modules/versions.ts @@ -62,16 +62,16 @@ export const init: ModuleFn = ({ store }) => { const { versions: { current }, } = store.getState(); - return current; + return current as API_Version; }, getLatestVersion: () => { const { versions: { latest, next, current }, } = store.getState(); if (current && semver.prerelease(current.version) && next) { - return latest && semver.gt(latest.version, next.version) ? latest : next; + return (latest && semver.gt(latest.version, next.version) ? latest : next) as API_Version; } - return latest; + return latest as API_Version; }, versionUpdateAvailable: () => { const latest = api.getLatestVersion(); @@ -110,7 +110,7 @@ export const init: ModuleFn = ({ store }) => { const { latest, next } = getVersionCheckData(); await store.setState({ - versions: { ...versions, latest, next }, + versions: { ...versions, latest, next } as API_Versions & API_UnknownEntries, }); }; diff --git a/code/lib/manager-api/src/modules/whatsnew.ts b/code/lib/manager-api/src/modules/whatsnew.ts index 27488f702d2e..ab460aa11486 100644 --- a/code/lib/manager-api/src/modules/whatsnew.ts +++ b/code/lib/manager-api/src/modules/whatsnew.ts @@ -47,7 +47,7 @@ export const init: ModuleFn = ({ fullAPI, store, provider }) => { ...state.whatsNewData, disableWhatsNewNotifications: !state.whatsNewData.disableWhatsNewNotifications, }); - provider.channel.emit(TOGGLE_WHATS_NEW_NOTIFICATIONS, { + provider.channel?.emit(TOGGLE_WHATS_NEW_NOTIFICATIONS, { disableWhatsNewNotifications: state.whatsNewData.disableWhatsNewNotifications, }); } @@ -55,17 +55,17 @@ export const init: ModuleFn = ({ fullAPI, store, provider }) => { }; function getLatestWhatsNewPost(): Promise { - provider.channel.emit(REQUEST_WHATS_NEW_DATA); + provider.channel?.emit(REQUEST_WHATS_NEW_DATA); return new Promise((resolve) => - provider.channel.once(RESULT_WHATS_NEW_DATA, ({ data }: { data: WhatsNewData }) => + provider.channel?.once(RESULT_WHATS_NEW_DATA, ({ data }: { data: WhatsNewData }) => resolve(data) ) ); } function setWhatsNewCache(cache: WhatsNewCache): void { - provider.channel.emit(SET_WHATS_NEW_CACHE, cache); + provider.channel?.emit(SET_WHATS_NEW_CACHE, cache); } const initModule = async () => { From 33eed072ff8a43c0d46211666adebe0a9527d47b Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Wed, 29 Nov 2023 14:30:43 +0100 Subject: [PATCH 5/5] cleanup --- node_modules/.package-lock.json | 27 - .../@storybook/core-events/jest.config.js | 7 - .../@storybook/core-events/package.json | 98 ---- node_modules/ts-dedent/HISTORY.md | 55 -- node_modules/ts-dedent/README.md | 107 ---- node_modules/ts-dedent/esm/index.d.ts | 2 - node_modules/ts-dedent/esm/index.js | 38 -- node_modules/ts-dedent/esm/index.js.map | 1 - node_modules/ts-dedent/package.json | 68 --- .../ts-dedent/src/__tests__/index.spec.ts | 554 ------------------ .../ts-dedent/src/__tests__/issue-21.spec.ts | 88 --- node_modules/ts-dedent/src/index.ts | 58 -- 12 files changed, 1103 deletions(-) delete mode 100644 node_modules/.package-lock.json delete mode 100644 node_modules/@storybook/core-events/jest.config.js delete mode 100644 node_modules/@storybook/core-events/package.json delete mode 100644 node_modules/ts-dedent/HISTORY.md delete mode 100644 node_modules/ts-dedent/README.md delete mode 100644 node_modules/ts-dedent/esm/index.d.ts delete mode 100644 node_modules/ts-dedent/esm/index.js delete mode 100644 node_modules/ts-dedent/esm/index.js.map delete mode 100644 node_modules/ts-dedent/package.json delete mode 100644 node_modules/ts-dedent/src/__tests__/index.spec.ts delete mode 100644 node_modules/ts-dedent/src/__tests__/issue-21.spec.ts delete mode 100644 node_modules/ts-dedent/src/index.ts diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json deleted file mode 100644 index 3fbc14dd749a..000000000000 --- a/node_modules/.package-lock.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "@storybook/root", - "lockfileVersion": 3, - "requires": true, - "packages": { - "node_modules/@storybook/core-events": { - "version": "7.4.0", - "resolved": "https://registry.npmjs.org/@storybook/core-events/-/core-events-7.4.0.tgz", - "integrity": "sha512-JavEo4dw7TQdF5pSKjk4RtqLgsG2R/eWRI8vZ3ANKa0ploGAnQR/eMTfSxf6TUH3ElBWLJhi+lvUCkKXPQD+dw==", - "dependencies": { - "ts-dedent": "^2.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/storybook" - } - }, - "node_modules/ts-dedent": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/ts-dedent/-/ts-dedent-2.2.0.tgz", - "integrity": "sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ==", - "engines": { - "node": ">=6.10" - } - } - } -} diff --git a/node_modules/@storybook/core-events/jest.config.js b/node_modules/@storybook/core-events/jest.config.js deleted file mode 100644 index 343e4c7a7f32..000000000000 --- a/node_modules/@storybook/core-events/jest.config.js +++ /dev/null @@ -1,7 +0,0 @@ -const path = require('path'); -const baseConfig = require('../../jest.config.node'); - -module.exports = { - ...baseConfig, - displayName: __dirname.split(path.sep).slice(-2).join(path.posix.sep), -}; diff --git a/node_modules/@storybook/core-events/package.json b/node_modules/@storybook/core-events/package.json deleted file mode 100644 index c4c1b6ff1017..000000000000 --- a/node_modules/@storybook/core-events/package.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "name": "@storybook/core-events", - "version": "7.4.0", - "description": "Event names used in storybook core", - "keywords": [ - "storybook" - ], - "homepage": "https://github.com/storybookjs/storybook/tree/next/code/lib/core-events", - "bugs": { - "url": "https://github.com/storybookjs/storybook/issues" - }, - "repository": { - "type": "git", - "url": "https://github.com/storybookjs/storybook.git", - "directory": "code/lib/core-events" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/storybook" - }, - "license": "MIT", - "sideEffects": false, - "exports": { - ".": { - "types": "./dist/index.d.ts", - "node": "./dist/index.js", - "require": "./dist/index.js", - "import": "./dist/index.mjs" - }, - "./preview-errors": { - "types": "./dist/errors/preview-errors.d.ts", - "node": "./dist/errors/preview-errors.js", - "require": "./dist/errors/preview-errors.js", - "import": "./dist/errors/preview-errors.mjs" - }, - "./manager-errors": { - "types": "./dist/errors/manager-errors.d.ts", - "node": "./dist/errors/manager-errors.js", - "require": "./dist/errors/manager-errors.js", - "import": "./dist/errors/manager-errors.mjs" - }, - "./server-errors": { - "types": "./dist/errors/server-errors.d.ts", - "node": "./dist/errors/server-errors.js", - "require": "./dist/errors/server-errors.js", - "import": "./dist/errors/server-errors.mjs" - }, - "./package.json": "./package.json" - }, - "main": "./dist/index.js", - "module": "./dist/index.mjs", - "types": "./dist/index.d.ts", - "typesVersions": { - "*": { - "*": [ - "dist/index.d.ts" - ], - "preview-errors": [ - "dist/errors/preview-errors.d.ts" - ], - "manager-errors": [ - "dist/errors/manager-errors.d.ts" - ], - "server-errors": [ - "dist/errors/server-errors.d.ts" - ] - } - }, - "files": [ - "dist/**/*", - "README.md", - "*.js", - "*.d.ts", - "!src/**/*" - ], - "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" - }, - "dependencies": { - "ts-dedent": "^2.0.0" - }, - "devDependencies": { - "typescript": "~4.9.3" - }, - "publishConfig": { - "access": "public" - }, - "bundler": { - "entries": [ - "./src/index.ts", - "./src/errors/preview-errors.ts", - "./src/errors/manager-errors.ts", - "./src/errors/server-errors.ts" - ] - }, - "gitHead": "e6a7fd8a655c69780bc20b9749c2699e44beae17" -} \ No newline at end of file diff --git a/node_modules/ts-dedent/HISTORY.md b/node_modules/ts-dedent/HISTORY.md deleted file mode 100644 index 570b3eeb042e..000000000000 --- a/node_modules/ts-dedent/HISTORY.md +++ /dev/null @@ -1,55 +0,0 @@ -# History - -## vNext - -TBA - -## v2.2.0 - -Add indentation to values with multiline strings & added ESM module - -- Updated all dependencies to their latest version -- Updated CI settings (added node 16, multiple os platforms) -- Moved from Travis CI to Github Actions - -## v2.1.1 - -Security update with dependency changes - -- Updated all dependencies to their latest version -- Updated CI settings (added node 15) - -## v2.1.0 - -- Correctly handle escape sequences when used as a tag -- Add test build to CI -- Only run coverage once per change - -## v2.0.0 - -Fixes #4 - -- ! Might break/change existing behavior -- If a line does not start with whitespace don't remove the indentation - -## v1.2.0 - -Security update with dependency changes - -- Updated all dependencies to their latest version -- Updated CI settings -- Replaced tslint with typescript-eslint -- Removed unused @types/node -- Added lint to run with the test suite - -## v1.1.0 - -Security update with dependency changes - -- Updated all dependencies to their latest version - -## v1.0.0 - -First release includes following functions - -- `function dedent(TemplateStringsArray | string, ...any[]): string diff --git a/node_modules/ts-dedent/README.md b/node_modules/ts-dedent/README.md deleted file mode 100644 index 2a4cb66e7f18..000000000000 --- a/node_modules/ts-dedent/README.md +++ /dev/null @@ -1,107 +0,0 @@ -# TypeScript Dedent - -[![codecov](https://codecov.io/gh/tamino-martinius/node-ts-dedent/branch/master/graph/badge.svg)](https://codecov.io/gh/tamino-martinius/node-ts-dedent) - -TypeScript package which smartly trims and strips indentation from multi-line strings. - -## Usage Examples - -```js -import dedent from 'dedent'; - -console.log(dedent`A string that gets so long you need to break it over - multiple lines. Luckily dedent is here to keep it - readable without lots of spaces ending up in the string - itself.`); - -console.log(dedent` - A string that gets so long you need to break it over - multiple lines. Luckily dedent is here to keep it - readable without lots of spaces ending up in the string - itself. -`); -``` - -```txt -A string that gets so long you need to break it over -multiple lines. Luckily dedent is here to keep it -readable without lots of spaces ending up in the string -itself. -``` - ---- - -```js -console.log(dedent` - Leading and trailing lines will be trimmed, so you can write something like - this and have it work as you expect: - - * how convenient it is - * that I can use an indented list - - and still have it do the right thing - - That's all. -`); -``` - -```txt -Leading and trailing lines will be trimmed, so you can write something like -this and have it work as you expect: - - * how convenient it is - * that I can use an indented list - - and still have it do the right thing - -That's all. -``` - ---- - -```js -console.log(dedent` - Also works fine - - ${1}. With any kind of - ${2}. Placeholders -`); -``` - -```txt -Also works fine - -1. With any kind of -2. Placeholders -``` - ---- - -```js -console.log(dedent(` - Wait! I lied. Dedent can also be used as a function. -`); -``` - -```txt -Wait! I lied. Dedent can also be used as a function. -``` - -## License - -MIT - -## Based on - -- [dedent](https://www.npmjs.com/package/dedent) by ~dmnd -- [dedent-js](https://www.npmjs.com/package/dedent-js) by ~martin-kolarik - -## Changelog - -See [history](HISTORY.md) for more details. - -- `2.2.0` **2021-08-01** Add indentation to values with multiline strings & added ESM module -- `2.1.1` **2021-03-31** Update dependencies -- `2.1.0` **2021-03-24** Bugfixes -- `2.0.0` **2020-09-28** Bugfixes -- `1.2.0` **2020-09-28** Update dependencies and a couple of minor improvments -- `1.1.0` **2019-07-26** Update dependencies and fixed links in readme -- `1.0.0` **2018-06-14** Initial release diff --git a/node_modules/ts-dedent/esm/index.d.ts b/node_modules/ts-dedent/esm/index.d.ts deleted file mode 100644 index 90db68d3914e..000000000000 --- a/node_modules/ts-dedent/esm/index.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export declare function dedent(templ: TemplateStringsArray | string, ...values: unknown[]): string; -export default dedent; diff --git a/node_modules/ts-dedent/esm/index.js b/node_modules/ts-dedent/esm/index.js deleted file mode 100644 index 2ffa044570a0..000000000000 --- a/node_modules/ts-dedent/esm/index.js +++ /dev/null @@ -1,38 +0,0 @@ -export function dedent(templ) { - var values = []; - for (var _i = 1; _i < arguments.length; _i++) { - values[_i - 1] = arguments[_i]; - } - var strings = Array.from(typeof templ === 'string' ? [templ] : templ); - strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, ''); - var indentLengths = strings.reduce(function (arr, str) { - var matches = str.match(/\n([\t ]+|(?!\s).)/g); - if (matches) { - return arr.concat(matches.map(function (match) { var _a, _b; return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0; })); - } - return arr; - }, []); - if (indentLengths.length) { - var pattern_1 = new RegExp("\n[\t ]{" + Math.min.apply(Math, indentLengths) + "}", 'g'); - strings = strings.map(function (str) { return str.replace(pattern_1, '\n'); }); - } - strings[0] = strings[0].replace(/^\r?\n/, ''); - var string = strings[0]; - values.forEach(function (value, i) { - var endentations = string.match(/(?:^|\n)( *)$/); - var endentation = endentations ? endentations[1] : ''; - var indentedValue = value; - if (typeof value === 'string' && value.includes('\n')) { - indentedValue = String(value) - .split('\n') - .map(function (str, i) { - return i === 0 ? str : "" + endentation + str; - }) - .join('\n'); - } - string += indentedValue + strings[i + 1]; - }); - return string; -} -export default dedent; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/ts-dedent/esm/index.js.map b/node_modules/ts-dedent/esm/index.js.map deleted file mode 100644 index afe1eadcfdf7..000000000000 --- a/node_modules/ts-dedent/esm/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,MAAM,CACpB,KAAoC;IACpC,gBAAoB;SAApB,UAAoB,EAApB,qBAAoB,EAApB,IAAoB;QAApB,+BAAoB;;IAEpB,IAAI,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;IAGtE,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,OAAO,CAC/D,gBAAgB,EAChB,EAAE,CACH,CAAC;IAGF,IAAM,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,UAAC,GAAG,EAAE,GAAG;QAC5C,IAAM,OAAO,GAAG,GAAG,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC;QACjD,IAAI,OAAO,EAAE;YACX,OAAO,GAAG,CAAC,MAAM,CACf,OAAO,CAAC,GAAG,CAAC,UAAC,KAAK,gBAAK,OAAA,MAAA,MAAA,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,0CAAE,MAAM,mCAAI,CAAC,CAAA,EAAA,CAAC,CAC3D,CAAC;SACH;QACD,OAAO,GAAG,CAAC;IACb,CAAC,EAAY,EAAE,CAAC,CAAC;IAGjB,IAAI,aAAa,CAAC,MAAM,EAAE;QACxB,IAAM,SAAO,GAAG,IAAI,MAAM,CAAC,aAAW,IAAI,CAAC,GAAG,OAAR,IAAI,EAAQ,aAAa,OAAI,EAAE,GAAG,CAAC,CAAC;QAE1E,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,UAAC,GAAG,IAAK,OAAA,GAAG,CAAC,OAAO,CAAC,SAAO,EAAE,IAAI,CAAC,EAA1B,CAA0B,CAAC,CAAC;KAC5D;IAGD,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAG9C,IAAI,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IAExB,MAAM,CAAC,OAAO,CAAC,UAAC,KAAK,EAAE,CAAC;QAEtB,IAAM,YAAY,GAAG,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC,CAAA;QAClD,IAAM,WAAW,GAAG,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;QACvD,IAAI,aAAa,GAAG,KAAK,CAAA;QAEzB,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;YACrD,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC;iBAC1B,KAAK,CAAC,IAAI,CAAC;iBACX,GAAG,CAAC,UAAC,GAAG,EAAE,CAAC;gBACV,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAG,WAAW,GAAG,GAAK,CAAA;YAC/C,CAAC,CAAC;iBACD,IAAI,CAAC,IAAI,CAAC,CAAC;SACf;QAED,MAAM,IAAI,aAAa,GAAG,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3C,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/ts-dedent/package.json b/node_modules/ts-dedent/package.json deleted file mode 100644 index 73f3b231b4de..000000000000 --- a/node_modules/ts-dedent/package.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "name": "ts-dedent", - "version": "2.2.0", - "description": "TypeScript package which smartly trims and strips indentation from multi-line strings", - "author": "Tamino Martinius ", - "main": "./dist/index.js", - "module": "./esm/index.js", - "jsnext:main": "./dist/index.js", - "typings": "./dist/index.d.ts", - "license": "MIT", - "files": [ - "dist", - "esm", - "src" - ], - "repository": { - "type": "git", - "url": "https://github.com/tamino-martinius/node-ts-dedent.git" - }, - "keywords": [ - "dedent", - "deindent", - "indentation", - "multi-line string", - "multiline strings", - "template literals", - "template strings", - "ts", - "typescript", - "es6", - "harmony" - ], - "engines": { - "node": ">=6.10" - }, - "scripts": { - "coverage": "rm -rf coverage* && jest --coverage", - "pretest": "npm run lint", - "test": "jest", - "lint": "eslint .", - "watch": "tsc -w", - "ci": "npm run coverage && codecov", - "compile": "rm -rf dist/* && rm -rf esm/* && tsc --module commonjs --outdir dist && tsc --module es6 --outdir esm", - "preversion": "npm run compile && git add ." - }, - "devDependencies": { - "@types/jest": "^26.0.24", - "@typescript-eslint/eslint-plugin": "^4.28.5", - "@typescript-eslint/parser": "^4.28.5", - "codecov": "^3.8.3", - "eslint": "^7.32.0", - "jest": "^27.0.6", - "ts-jest": "^27.0.4", - "typescript": "~4.3.5" - }, - "jest": { - "transform": { - ".ts": "ts-jest" - }, - "testRegex": "\\.(test|spec)\\.ts$", - "moduleFileExtensions": [ - "ts", - "tsx", - "js", - "json" - ] - } -} diff --git a/node_modules/ts-dedent/src/__tests__/index.spec.ts b/node_modules/ts-dedent/src/__tests__/index.spec.ts deleted file mode 100644 index 5d0dee0d4a7b..000000000000 --- a/node_modules/ts-dedent/src/__tests__/index.spec.ts +++ /dev/null @@ -1,554 +0,0 @@ -import { dedent } from '..'; - -function tag(strings: TemplateStringsArray, ...values: number[]) { - let string = strings[0]; - - values.forEach((value, i) => { - string += 2 * value + strings[i + 1]; - }); - - return string; -} - -describe('dedent tag', () => { - it('should work with empty string', () => { - expect(dedent``).toEqual(''); - }); - - it('should work with tabs', () => { - expect(dedent`Line #1 - Line #2 - Line #3`).toEqual('Line #1\nLine #2\nLine #3'); - - expect(dedent`Line #${1} - Line #${2} - Line #${3}`).toEqual('Line #1\nLine #2\nLine #3'); - - expect(dedent`${1}. line #${1} - ${2}. line #${2} - ${3}. line`).toEqual('1. line #1\n2. line #2\n3. line'); - }); - - it('should work with spaces', () => { - expect(dedent`Line #1 - Line #2 - Line #3`).toEqual('Line #1\nLine #2\nLine #3'); - - expect(dedent`Line #${1} - Line #${2} - Line #${3}`).toEqual('Line #1\nLine #2\nLine #3'); - - expect(dedent`${1}. line #${1} - ${2}. line #${2} - ${3}. line`).toEqual('1. line #1\n2. line #2\n3. line'); - }); - - it('should remove leading/trailing line break', () => { - expect( - dedent` - Line #1 - Line #2 - Line #3 - `, - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - dedent` -Line #1 - Line #2 - Line #3 - `, - ).toEqual('Line #1\n\tLine #2\n\tLine #3'); - - expect( - dedent` - Line #${1} - Line #${2} - Line #${3} - `, - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - dedent` -Line #${1} - Line #${2} - Line #${3} - `, - ).toEqual('Line #1\n\tLine #2\n\tLine #3'); - - expect( - dedent` - ${1}. line #${1} - ${2}. line #${2} - ${3}. line - `, - ).toEqual('1. line #1\n2. line #2\n3. line'); - }); - - it('should not remove more than one leading/trailing line break', () => { - expect( - dedent` - - Line #1 - Line #2 - Line #3 - - `, - ).toEqual('\nLine #1\nLine #2\nLine #3\n'); - - expect( - dedent` - - Line #${1} - Line #${2} - Line #${3} - - `, - ).toEqual('\nLine #1\nLine #2\nLine #3\n'); - - expect( - dedent` - - ${1}. line #${1} - ${2}. line #${2} - ${3}. line - - `, - ).toEqual('\n1. line #1\n2. line #2\n3. line\n'); - }); - - it('should remove the same number of tabs/spaces from each line', () => { - expect( - dedent` - Line #1 - Line #2 - Line #3 - `, - ).toEqual('Line #1\n\tLine #2\n\t\tLine #3'); - - expect( - dedent` - Line #${1} - Line #${2} - Line #${3} - `, - ).toEqual('Line #1\n\tLine #2\n\t\tLine #3'); - - expect( - dedent` - ${1}. line #${1} - ${2}. line #${2} - ${3}. line - `, - ).toEqual('1. line #1\n\t2. line #2\n\t\t3. line'); - }); - - it("should ignore the last line if it doesn't contain anything else than whitespace", () => { - expect( - (() => { - return dedent` - Line #1 - Line #2 - Line #3 - `; - })(), - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - (() => { - return dedent` - Line #${1} - Line #${2} - Line #${3} - `; - })(), - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - (() => { - return dedent` - ${1}. line #${1} - ${2}. line #${2} - ${3}. line - `; - })(), - ).toEqual('1. line #1\n2. line #2\n3. line'); - }); - - it("should process escape sequences", () => { - expect( - (() => { - return dedent` - \${not interpolated} - \` - `; - })(), - ).toEqual('${not interpolated}\n`'); - }); -}); - -describe('dedent() function', () => { - it('should work with tabs', () => { - expect( - dedent(`Line #1 - Line #2 - Line #3`), - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - dedent(`Line #${1} - Line #${2} - Line #${3}`), - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - dedent(`${1}. line #${1} - ${2}. line #${2} - ${3}. line`), - ).toEqual('1. line #1\n2. line #2\n3. line'); - }); - - it('should work with spaces', () => { - expect( - dedent(`Line #1 - Line #2 - Line #3`), - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - dedent(`Line #${1} - Line #${2} - Line #${3}`), - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - dedent(`${1}. line #${1} - ${2}. line #${2} - ${3}. line`), - ).toEqual('1. line #1\n2. line #2\n3. line'); - }); - - it('should remove leading/trailing line break', () => { - expect( - dedent(` - Line #1 - Line #2 - Line #3 - `), - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - dedent(` -Line #1 - Line #2 - Line #3 - `), - ).toEqual('Line #1\n\tLine #2\n\tLine #3'); - - expect( - dedent(` - Line #${1} - Line #${2} - Line #${3} - `), - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - dedent(` -Line #${1} - Line #${2} - Line #${3} - `), - ).toEqual('Line #1\n\tLine #2\n\tLine #3'); - - expect( - dedent(` - ${1}. line #${1} - ${2}. line #${2} - ${3}. line - `), - ).toEqual('1. line #1\n2. line #2\n3. line'); - }); - - it('should not remove more than one leading/trailing line break', () => { - expect( - dedent(` - - Line #1 - Line #2 - Line #3 - - `), - ).toEqual('\nLine #1\nLine #2\nLine #3\n'); - - expect( - dedent(` - - Line #${1} - Line #${2} - Line #${3} - - `), - ).toEqual('\nLine #1\nLine #2\nLine #3\n'); - - expect( - dedent(` - - ${1}. line #${1} - ${2}. line #${2} - ${3}. line - - `), - ).toEqual('\n1. line #1\n2. line #2\n3. line\n'); - }); - - it('should remove the same number of tabs/spaces from each line', () => { - expect( - dedent(` - Line #1 - Line #2 - Line #3 - `), - ).toEqual('Line #1\n\tLine #2\n\t\tLine #3'); - - expect( - dedent(` - Line #${1} - Line #${2} - Line #${3} - `), - ).toEqual('Line #1\n\tLine #2\n\t\tLine #3'); - - expect( - dedent(` - ${1}. line #${1} - ${2}. line #${2} - ${3}. line - `), - ).toEqual('1. line #1\n\t2. line #2\n\t\t3. line'); - }); - - it("should ignore the last line if it doesn't contain anything else than whitespace", () => { - expect( - (() => { - return dedent(` - Line #1 - Line #2 - Line #3 - `); - })(), - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - (() => { - return dedent(` - Line #${1} - Line #${2} - Line #${3} - `); - })(), - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - (() => { - return dedent(` - ${1}. line #${1} - ${2}. line #${2} - ${3}. line - `); - })(), - ).toEqual('1. line #1\n2. line #2\n3. line'); - }); - - it("should process escape sequences", () => { - expect( - dedent(` - \${not interpolated} - \` - `), - ).toEqual('${not interpolated}\n`'); - }); -}); - -describe('dedent() function with custom tag', () => { - it('should work with tabs', () => { - expect( - dedent(tag`Line #1 - Line #2 - Line #3`), - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - dedent(tag`Line #${1} - Line #${2} - Line #${3}`), - ).toEqual('Line #2\nLine #4\nLine #6'); - - expect( - dedent(tag`${1}. line #${1} - ${2}. line #${2} - ${3}. line`), - ).toEqual('2. line #2\n4. line #4\n6. line'); - }); - - it('should work with spaces', () => { - expect( - dedent(tag`Line #1 - Line #2 - Line #3`), - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - dedent(tag`Line #${1} - Line #${2} - Line #${3}`), - ).toEqual('Line #2\nLine #4\nLine #6'); - - expect( - dedent(tag`${1}. line #${1} - ${2}. line #${2} - ${3}. line`), - ).toEqual('2. line #2\n4. line #4\n6. line'); - }); - - it('should remove leading/trailing line break', () => { - expect( - dedent(tag` - Line #1 - Line #2 - Line #3 - `), - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - dedent(tag` -Line #1 - Line #2 - Line #3 - `), - ).toEqual('Line #1\n\tLine #2\n\tLine #3'); - - expect( - dedent(tag` - Line #${1} - Line #${2} - Line #${3} - `), - ).toEqual('Line #2\nLine #4\nLine #6'); - - expect( - dedent(tag` -Line #${1} - Line #${2} - Line #${3} - `), - ).toEqual('Line #2\n\tLine #4\n\tLine #6'); - - expect( - dedent(tag` - ${1}. line #${1} - ${2}. line #${2} - ${3}. line - `), - ).toEqual('2. line #2\n4. line #4\n6. line'); - }); - - it('should not remove more than one leading/trailing line break', () => { - expect( - dedent(tag` - - Line #1 - Line #2 - Line #3 - - `), - ).toEqual('\nLine #1\nLine #2\nLine #3\n'); - - expect( - dedent(tag` - - Line #${1} - Line #${2} - Line #${3} - - `), - ).toEqual('\nLine #2\nLine #4\nLine #6\n'); - - expect( - dedent(tag` - - ${1}. line #${1} - ${2}. line #${2} - ${3}. line - - `), - ).toEqual('\n2. line #2\n4. line #4\n6. line\n'); - }); - - it('should remove the same number of tabs/spaces from each line', () => { - expect( - dedent(tag` - Line #1 - Line #2 - Line #3 - `), - ).toEqual('Line #1\n\tLine #2\n\t\tLine #3'); - - expect( - dedent(tag` - Line #${1} - Line #${2} - Line #${3} - `), - ).toEqual('Line #2\n\tLine #4\n\t\tLine #6'); - - expect( - dedent(tag` - ${1}. line #${1} - ${2}. line #${2} - ${3}. line - `), - ).toEqual('2. line #2\n\t4. line #4\n\t\t6. line'); - }); - - it("should ignore the last line if it doesn't contain anything else than whitespace", () => { - expect( - (() => { - return dedent(tag` - Line #1 - Line #2 - Line #3 - `); - })(), - ).toEqual('Line #1\nLine #2\nLine #3'); - - expect( - (() => { - return dedent(tag` - Line #${1} - Line #${2} - Line #${3} - `); - })(), - ).toEqual('Line #2\nLine #4\nLine #6'); - - expect( - (() => { - return dedent(tag` - ${1}. line #${1} - ${2}. line #${2} - ${3}. line - `); - })(), - ).toEqual('2. line #2\n4. line #4\n6. line'); - }); - - it("should process escape sequences", () => { - expect( - dedent(tag` - \${not interpolated} - \` - `), - ).toEqual('${not interpolated}\n`'); - }); -}); diff --git a/node_modules/ts-dedent/src/__tests__/issue-21.spec.ts b/node_modules/ts-dedent/src/__tests__/issue-21.spec.ts deleted file mode 100644 index 9da50ff5e935..000000000000 --- a/node_modules/ts-dedent/src/__tests__/issue-21.spec.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { dedent } from '..'; - -describe('Issue 21', () => { - it('should dedent nested dedents correctly', () => { - const fieldDocs = dedent` - * a - * b - * c - ` - - const a = dedent` - /** - ${fieldIntro()} - * - ${fieldDocs} - * - ${fieldExample()} - */ - ` - - function fieldIntro() { - return dedent` - * 0 - ` - } - function fieldExample() { - return dedent` - * d - ` - } - - const expected = `/** - * 0 - * - * a - * b - * c - * - * d - */` - - expect(a).toEqual(expected); - }); - - /** - * Could not find a way to handle this but is an edge case we'd like to solve eventually - */ - it.skip('should handle function calls of nested dedents correctly', () => { - const fieldDocs = dedent(` - * a - * b - * c - `) - - const a = dedent(` - /** - ${fieldIntro()} - * - ${fieldDocs} - * - ${fieldExample()} - */ - `) - - function fieldIntro() { - return dedent(` - * 0 - `) - } - function fieldExample() { - return dedent(` - * d - `) - } - - const expected = `/** - * 0 - * - * a - * b - * c - * - * d - */` - - expect(a).toEqual(expected); - }); -}); diff --git a/node_modules/ts-dedent/src/index.ts b/node_modules/ts-dedent/src/index.ts deleted file mode 100644 index fb52fdf052e6..000000000000 --- a/node_modules/ts-dedent/src/index.ts +++ /dev/null @@ -1,58 +0,0 @@ -export function dedent( - templ: TemplateStringsArray | string, - ...values: unknown[] -): string { - let strings = Array.from(typeof templ === 'string' ? [templ] : templ); - - // 1. Remove trailing whitespace. - strings[strings.length - 1] = strings[strings.length - 1].replace( - /\r?\n([\t ]*)$/, - '', - ); - - // 2. Find all line breaks to determine the highest common indentation level. - const indentLengths = strings.reduce((arr, str) => { - const matches = str.match(/\n([\t ]+|(?!\s).)/g); - if (matches) { - return arr.concat( - matches.map((match) => match.match(/[\t ]/g)?.length ?? 0), - ); - } - return arr; - }, []); - - // 3. Remove the common indentation from all strings. - if (indentLengths.length) { - const pattern = new RegExp(`\n[\t ]{${Math.min(...indentLengths)}}`, 'g'); - - strings = strings.map((str) => str.replace(pattern, '\n')); - } - - // 4. Remove leading whitespace. - strings[0] = strings[0].replace(/^\r?\n/, ''); - - // 5. Perform interpolation. - let string = strings[0]; - - values.forEach((value, i) => { - // 5.1 Read current indentation level - const endentations = string.match(/(?:^|\n)( *)$/) - const endentation = endentations ? endentations[1] : '' - let indentedValue = value - // 5.2 Add indentation to values with multiline strings - if (typeof value === 'string' && value.includes('\n')) { - indentedValue = String(value) - .split('\n') - .map((str, i) => { - return i === 0 ? str : `${endentation}${str}` - }) - .join('\n'); - } - - string += indentedValue + strings[i + 1]; - }); - - return string; -} - -export default dedent;