├── examples └── .gitkeep ├── test ├── __setup__.ts ├── index.test-d.ts └── index.test.ts ├── vite-env.d.ts ├── gui ├── src │ ├── vite-env.d.ts │ ├── store │ │ ├── useManager.ts │ │ ├── useUser.ts │ │ ├── useSliceConflicts.ts │ │ ├── useSliceMachineConfig.ts │ │ └── useRepository.ts │ ├── components │ │ ├── AppFooter.tsx │ │ ├── SharedSliceList.tsx │ │ ├── CustomTypeList.tsx │ │ ├── StatusDot.tsx │ │ ├── AppHeader.tsx │ │ └── CustomTypeCard.tsx │ ├── main.tsx │ ├── index.css │ └── App.tsx ├── postcss.config.js ├── tsconfig.node.json ├── tailwind.config.js ├── vite.config.ts ├── index.html ├── tsconfig.json └── public │ └── icon.svg ├── playground ├── slices │ └── index.ts ├── app │ ├── favicon.ico │ ├── api │ │ ├── exit-preview │ │ │ └── route.ts │ │ ├── revalidate │ │ │ └── route.ts │ │ └── preview │ │ │ └── route.ts │ ├── slice-simulator │ │ └── page.tsx │ ├── layout.tsx │ ├── page.tsx │ ├── globals.css │ └── page.module.css ├── next.config.js ├── slicemachine.config.json ├── .gitignore ├── public │ ├── vercel.svg │ └── next.svg ├── tsconfig.json ├── package.json ├── README.md └── prismicio.ts ├── src ├── lib │ ├── ExplainedError.ts │ ├── assertExists.ts │ ├── listr.ts │ ├── prompt.ts │ └── createUpgradeExpressApp.ts ├── index.ts ├── models │ ├── checkSliceConflicts.ts │ ├── findDuplicatedSlices.ts │ ├── SharedSlice.ts │ ├── CompositeSlice.ts │ └── CustomType.ts ├── cli-watcher.ts ├── cli.ts └── UpgradeProcess.ts ├── bin └── prismic-upgrade-from-legacy.js ├── .github ├── ISSUE_TEMPLATE │ ├── config.yml │ ├── feature_request.md │ └── bug_report.md ├── workflows │ ├── issues.yml │ ├── issues--feature_request.md │ ├── issues--bug_report.md │ └── ci.yml ├── PULL_REQUEST_TEMPLATE.md └── prismic-oss-ecosystem.svg ├── .gitattributes ├── .editorconfig ├── .versionrc ├── .gitignore ├── .eslintignore ├── .prettierignore ├── tsconfig.json ├── .size-limit.cjs ├── vite.config.ts ├── .eslintrc.cjs ├── .prettierrc ├── CHANGELOG.md ├── package.json ├── README.md ├── LICENSE └── CONTRIBUTING.md /examples/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test/__setup__.ts: -------------------------------------------------------------------------------- 1 | // Add global test set up here. 2 | -------------------------------------------------------------------------------- /vite-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /gui/src/vite-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /playground/slices/index.ts: -------------------------------------------------------------------------------- 1 | export const components = {}; 2 | -------------------------------------------------------------------------------- /src/lib/ExplainedError.ts: -------------------------------------------------------------------------------- 1 | export class ExplainedError extends Error {} 2 | -------------------------------------------------------------------------------- /bin/prismic-upgrade-from-legacy.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import("../dist/cli-watcher.cjs"); 4 | -------------------------------------------------------------------------------- /playground/app/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/prismicio/prismic-upgrade-from-legacy/master/playground/app/favicon.ico -------------------------------------------------------------------------------- /gui/postcss.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | plugins: { 3 | tailwindcss: { config: "./gui/tailwind.config.js" }, 4 | autoprefixer: {}, 5 | }, 6 | }; 7 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export type { UpgradeProcessOptions } from "./UpgradeProcess"; 2 | export { createUpgradeProcess, UpgradeProcess } from "./UpgradeProcess"; 3 | -------------------------------------------------------------------------------- /playground/next.config.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable tsdoc/syntax */ 2 | 3 | /** 4 | * @type {import("next").NextConfig} 5 | */ 6 | const nextConfig = {}; 7 | 8 | module.exports = nextConfig; 9 | -------------------------------------------------------------------------------- /playground/app/api/exit-preview/route.ts: -------------------------------------------------------------------------------- 1 | import { exitPreview } from "@prismicio/next"; 2 | 3 | export async function GET(): Promise { 4 | return await exitPreview(); 5 | } 6 | -------------------------------------------------------------------------------- /test/index.test-d.ts: -------------------------------------------------------------------------------- 1 | import { expectTypeOf, it } from "vitest"; 2 | 3 | import * as lib from "../src"; 4 | 5 | it("returns void", () => { 6 | expectTypeOf(lib.createUpgradeProcess).returns.not.toBeVoid(); 7 | }); 8 | -------------------------------------------------------------------------------- /test/index.test.ts: -------------------------------------------------------------------------------- 1 | import { expect, it } from "vitest"; 2 | 3 | import * as lib from "../src"; 4 | 5 | // TODO: Dummy test, meant to be removed when real tests come in 6 | it("exports something", () => { 7 | expect(lib).toBeTruthy(); 8 | }); 9 | -------------------------------------------------------------------------------- /gui/tsconfig.node.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "composite": true, 4 | "skipLibCheck": true, 5 | "module": "ESNext", 6 | "moduleResolution": "bundler", 7 | "allowSyntheticDefaultImports": true 8 | }, 9 | "include": ["vite.config.ts"] 10 | } 11 | -------------------------------------------------------------------------------- /src/lib/assertExists.ts: -------------------------------------------------------------------------------- 1 | // TypeScript cannot use arrow functions for assertions 2 | export function assertExists( 3 | value: T, 4 | message: string, 5 | ): asserts value is NonNullable { 6 | if (value == undefined) { 7 | throw new Error(message); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /gui/tailwind.config.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable tsdoc/syntax */ 2 | 3 | /** 4 | * @type {import("tailwindcss").Config} 5 | */ 6 | export default { 7 | content: ["./gui/index.html", "./gui/src/**/*.{js,ts,jsx,tsx}"], 8 | theme: { 9 | extend: {}, 10 | }, 11 | plugins: [], 12 | }; 13 | -------------------------------------------------------------------------------- /playground/app/api/revalidate/route.ts: -------------------------------------------------------------------------------- 1 | import { revalidateTag } from "next/cache"; 2 | import { NextResponse } from "next/server"; 3 | 4 | export async function POST(): Promise { 5 | revalidateTag("prismic"); 6 | 7 | return NextResponse.json({ revalidated: true, now: Date.now() }); 8 | } 9 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: 👪 Prismic Community Forum 4 | url: https://community.prismic.io 5 | about: Ask a question about the package or raise an issue directly related to Prismic. You will usually get support there more quickly! 6 | -------------------------------------------------------------------------------- /gui/src/store/useManager.ts: -------------------------------------------------------------------------------- 1 | import { 2 | SliceMachineManagerClient, 3 | createSliceMachineManagerClient, 4 | } from "@slicemachine/manager/client"; 5 | 6 | export const useManager = (): SliceMachineManagerClient => 7 | createSliceMachineManagerClient({ 8 | serverURL: "/_manager", 9 | }); 10 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # asserts everything is text 2 | * text eol=lf 3 | 4 | # treats lock files as binaries to prevent merge headache 5 | package-lock.json -diff 6 | yarn.lock -diff 7 | 8 | # treats assets as binaries 9 | *.png binary 10 | *.jpg binary 11 | *.jpeg binary 12 | *.gif binary 13 | *.ico binary 14 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_style = tab 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | 11 | [*.md] 12 | trim_trailing_whitespace = false 13 | 14 | [*.yml] 15 | indent_style = space 16 | indent_size = 2 17 | -------------------------------------------------------------------------------- /.versionrc: -------------------------------------------------------------------------------- 1 | { 2 | "types": [ 3 | { 4 | "type": "feat", 5 | "section": "Features" 6 | }, 7 | { 8 | "type": "fix", 9 | "section": "Bug Fixes" 10 | }, 11 | { 12 | "type": "refactor", 13 | "section": "Refactor" 14 | }, 15 | { 16 | "type": "docs", 17 | "section": "Documentation" 18 | }, 19 | { 20 | "type": "chore", 21 | "section": "Chore" 22 | } 23 | ] 24 | } 25 | -------------------------------------------------------------------------------- /gui/vite.config.ts: -------------------------------------------------------------------------------- 1 | import react from "@vitejs/plugin-react"; 2 | import { defineConfig } from "vite"; 3 | 4 | // https://vitejs.dev/config/ 5 | export default defineConfig({ 6 | plugins: [react()], 7 | resolve: { 8 | alias: [ 9 | { 10 | find: /@cli\/(.*)/, 11 | replacement: "../src/$1", 12 | }, 13 | ], 14 | }, 15 | root: __dirname, 16 | build: { 17 | outDir: "../dist/gui", 18 | }, 19 | }); 20 | -------------------------------------------------------------------------------- /gui/src/components/AppFooter.tsx: -------------------------------------------------------------------------------- 1 | export function AppFooter(): JSX.Element { 2 | return ( 3 | 14 | ); 15 | } 16 | -------------------------------------------------------------------------------- /gui/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 11 | Prismic Upgrade 12 | 13 | 14 | 15 |
16 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /playground/app/slice-simulator/page.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { SliceZone } from "@prismicio/react"; 4 | import { SliceSimulator } from "@slicemachine/adapter-next/simulator"; 5 | 6 | import { components } from "../../slices"; 7 | 8 | export default function SliceSimulatorPage(): JSX.Element { 9 | return ( 10 | } 12 | /> 13 | ); 14 | } 15 | -------------------------------------------------------------------------------- /playground/app/api/preview/route.ts: -------------------------------------------------------------------------------- 1 | import { redirectToPreviewURL } from "@prismicio/next"; 2 | import { draftMode } from "next/headers"; 3 | import { NextRequest } from "next/server"; 4 | 5 | import { createClient } from "../../../prismicio"; 6 | 7 | export async function GET(request: NextRequest): Promise { 8 | const client = createClient(); 9 | 10 | draftMode().enable(); 11 | 12 | await redirectToPreviewURL({ client, request }); 13 | } 14 | -------------------------------------------------------------------------------- /playground/slicemachine.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "___repositoryName": "inspiring-briouat-syt67g", 3 | "__repositoryName": "2306-meetup-figma", 4 | "repositoryName": "upgrade-optimize-full-legacy", 5 | "_repositoryName": "upgrade-no-conflict-full-legacy", 6 | "adapter": { 7 | "resolve": "@slicemachine/adapter-next", 8 | "options": { 9 | "format": false 10 | } 11 | }, 12 | "libraries": [ 13 | "./slices" 14 | ], 15 | "localSliceSimulatorURL": "http://localhost:3000/slice-simulator" 16 | } -------------------------------------------------------------------------------- /gui/src/main.tsx: -------------------------------------------------------------------------------- 1 | import { ThemeProvider, TooltipProvider } from "@prismicio/editor-ui"; 2 | import React from "react"; 3 | import ReactDOM from "react-dom/client"; 4 | 5 | import { App } from "./App"; 6 | import "./index.css"; 7 | 8 | ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( 9 | 10 | 11 | 12 | 13 | 14 | 15 | , 16 | ); 17 | -------------------------------------------------------------------------------- /gui/src/store/useUser.ts: -------------------------------------------------------------------------------- 1 | import { PrismicUserProfile } from "@slicemachine/manager"; 2 | import { create } from "zustand"; 3 | 4 | import { useManager } from "./useManager"; 5 | 6 | type UserState = { 7 | profile: null | PrismicUserProfile; 8 | fetch: () => Promise; 9 | }; 10 | 11 | export const useUser = create((set) => ({ 12 | profile: null, 13 | fetch: async () => { 14 | const profile = await useManager().user.getProfile(); 15 | 16 | set({ profile }); 17 | }, 18 | })); 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # custom 2 | dist 3 | examples/**/package-lock.json 4 | 5 | # os 6 | .DS_Store 7 | ._* 8 | 9 | # node 10 | logs 11 | *.log 12 | node_modules 13 | 14 | # yarn 15 | yarn-debug.log* 16 | yarn-error.log* 17 | lerna-debug.log* 18 | .yarn-integrity 19 | yarn.lock 20 | 21 | # npm 22 | npm-debug.log* 23 | 24 | # tests 25 | coverage 26 | .eslintcache 27 | .nyc_output 28 | 29 | # .env 30 | .env 31 | .env.test 32 | .env*.local 33 | 34 | # vscode 35 | .vscode/* 36 | !.vscode/tasks.json 37 | !.vscode/launch.json 38 | *.code-workspace 39 | -------------------------------------------------------------------------------- /playground/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # next.js 12 | /.next/ 13 | /out/ 14 | 15 | # production 16 | /build 17 | 18 | # misc 19 | .DS_Store 20 | *.pem 21 | 22 | # debug 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | 27 | # local env files 28 | .env*.local 29 | 30 | # vercel 31 | .vercel 32 | 33 | # typescript 34 | *.tsbuildinfo 35 | next-env.d.ts 36 | -------------------------------------------------------------------------------- /src/lib/listr.ts: -------------------------------------------------------------------------------- 1 | // @ts-expect-error - @types package not available 2 | import UpdateRenderer from "@lihbr/listr-update-renderer"; 3 | import Listr from "listr"; 4 | 5 | type ListrArgs = [tasks: Listr.ListrTask[], options?: Listr.ListrOptions]; 6 | 7 | export const listr = (...[tasks, options]: ListrArgs): Listr => { 8 | return new Listr(tasks, { renderer: UpdateRenderer, ...options }); 9 | }; 10 | 11 | export const listrRun = async ( 12 | ...[tasks, options]: ListrArgs 13 | ): Promise => { 14 | return listr(tasks, options).run(); 15 | }; 16 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | # .gitignore copy 2 | 3 | # custom 4 | dist 5 | examples/**/package-lock.json 6 | 7 | # os 8 | .DS_Store 9 | ._* 10 | 11 | # node 12 | logs 13 | *.log 14 | node_modules 15 | 16 | # yarn 17 | yarn-debug.log* 18 | yarn-error.log* 19 | lerna-debug.log* 20 | .yarn-integrity 21 | yarn.lock 22 | 23 | # npm 24 | npm-debug.log* 25 | 26 | # tests 27 | coverage 28 | .eslintcache 29 | .nyc_output 30 | 31 | # .env 32 | .env 33 | .env.test 34 | .env*.local 35 | 36 | # vscode 37 | .vscode/* 38 | !.vscode/tasks.json 39 | !.vscode/launch.json 40 | *.code-workspace 41 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # custom 2 | CHANGELOG.md 3 | 4 | # .gitignore copy 5 | 6 | # custom 7 | dist 8 | examples/**/package-lock.json 9 | 10 | # os 11 | .DS_Store 12 | ._* 13 | 14 | # node 15 | logs 16 | *.log 17 | node_modules 18 | 19 | # yarn 20 | yarn-debug.log* 21 | yarn-error.log* 22 | lerna-debug.log* 23 | .yarn-integrity 24 | yarn.lock 25 | 26 | # npm 27 | npm-debug.log* 28 | 29 | # tests 30 | coverage 31 | .eslintcache 32 | .nyc_output 33 | 34 | # .env 35 | .env 36 | .env.test 37 | .env*.local 38 | 39 | # vscode 40 | .vscode/* 41 | !.vscode/tasks.json 42 | !.vscode/launch.json 43 | *.code-workspace 44 | -------------------------------------------------------------------------------- /playground/public/vercel.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /playground/app/layout.tsx: -------------------------------------------------------------------------------- 1 | import type { Metadata } from "next"; 2 | import { Inter } from "next/font/google"; 3 | 4 | import "./globals.css"; 5 | 6 | const inter = Inter({ subsets: ["latin"] }); 7 | 8 | // eslint-disable-next-line react-refresh/only-export-components 9 | export const metadata: Metadata = { 10 | title: "Create Next App", 11 | description: "Generated by create next app", 12 | }; 13 | 14 | export default function RootLayout({ 15 | children, 16 | }: { 17 | children: React.ReactNode; 18 | }): JSX.Element { 19 | return ( 20 | 21 | {children} 22 | 23 | ); 24 | } 25 | -------------------------------------------------------------------------------- /gui/src/components/SharedSliceList.tsx: -------------------------------------------------------------------------------- 1 | import { useRepository } from "../store/useRepository"; 2 | 3 | // TODO: Rendering 4 | export function SharedSliceList(): JSX.Element { 5 | const sharedSlices = useRepository((state) => state.sharedSlices); 6 | 7 | return ( 8 |
9 |

Shared Slices ({sharedSlices?.length})

10 |
    11 | {sharedSlices?.map((sharedSlice) => ( 12 |
  • {sharedSlice.id}
  • 13 | ))} 14 | {sharedSlices?.length === 0 ? ( 15 |
  • No Shared Slices found.
  • 16 | ) : null} 17 |
18 |
19 | ); 20 | } 21 | -------------------------------------------------------------------------------- /gui/src/store/useSliceConflicts.ts: -------------------------------------------------------------------------------- 1 | import { create } from "zustand"; 2 | 3 | import { CompositeSlice } from "../../../src/models/CompositeSlice"; 4 | import { SharedSlice } from "../../../src/models/SharedSlice"; 5 | import { 6 | SliceConflicts, 7 | checkSliceConflicts, 8 | } from "../../../src/models/checkSliceConflicts"; 9 | 10 | type SliceConflictsState = { 11 | conflicts: null | SliceConflicts; 12 | }; 13 | 14 | export const useSliceConflicts = create((set) => ({ 15 | conflicts: null, 16 | check: (slices: (CompositeSlice | SharedSlice)[]) => { 17 | const conflicts = checkSliceConflicts(slices); 18 | 19 | set({ conflicts }); 20 | }, 21 | })); 22 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "skipLibCheck": true, 5 | "target": "esnext", 6 | "module": "esnext", 7 | "declaration": false, 8 | "moduleResolution": "node", 9 | "resolveJsonModule": true, 10 | "allowSyntheticDefaultImports": true, 11 | "esModuleInterop": true, 12 | "forceConsistentCasingInFileNames": true, 13 | "jsx": "preserve", 14 | "lib": [ 15 | "esnext", 16 | "dom" 17 | ], 18 | "types": [ 19 | "node", 20 | "vitest", 21 | "vite/client" 22 | ] 23 | }, 24 | "include": [ 25 | "vite.config.ts" 26 | ], 27 | "exclude": [ 28 | "node_modules", 29 | "dist", 30 | "examples", 31 | "playground" 32 | ] 33 | } -------------------------------------------------------------------------------- /.size-limit.cjs: -------------------------------------------------------------------------------- 1 | const pkg = require("./package.json"); 2 | 3 | function getObjectValues(input, acc = []) { 4 | if (typeof input === "string") { 5 | return input; 6 | } else { 7 | return [ 8 | ...acc, 9 | ...Object.values(input).flatMap((value) => getObjectValues(value)), 10 | ]; 11 | } 12 | } 13 | 14 | module.exports = [ 15 | ...new Set([pkg.main, pkg.module, ...getObjectValues(pkg.exports)]), 16 | ] 17 | .sort() 18 | .filter((path) => { 19 | return path && path !== "./package.json" && !path.endsWith(".d.ts"); 20 | }) 21 | .map((path) => { 22 | return { 23 | path, 24 | modifyEsbuildConfig(config) { 25 | config.platform = "node"; 26 | 27 | return config; 28 | }, 29 | }; 30 | }); 31 | -------------------------------------------------------------------------------- /src/models/checkSliceConflicts.ts: -------------------------------------------------------------------------------- 1 | import { CompositeSlice } from "./CompositeSlice"; 2 | import { SharedSlice } from "./SharedSlice"; 3 | 4 | export type SliceConflicts = Record; 5 | 6 | export const checkSliceConflicts = ( 7 | slices: (SharedSlice | CompositeSlice)[], 8 | ): SliceConflicts => { 9 | const ids: Record = {}; 10 | const conflicts: SliceConflicts = {}; 11 | 12 | for (const slice of slices) { 13 | if (!(slice.id in ids)) { 14 | ids[slice.id] = slice; 15 | 16 | continue; 17 | } 18 | 19 | conflicts[slice.id] ||= [ids[slice.id]]; 20 | conflicts[slice.id].push(slice); 21 | } 22 | 23 | return conflicts; 24 | }; 25 | -------------------------------------------------------------------------------- /playground/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "strict": true, 8 | "noEmit": true, 9 | "esModuleInterop": true, 10 | "module": "esnext", 11 | "moduleResolution": "bundler", 12 | "resolveJsonModule": true, 13 | "isolatedModules": true, 14 | "jsx": "preserve", 15 | "incremental": true, 16 | "plugins": [ 17 | { 18 | "name": "next" 19 | } 20 | ], 21 | "paths": { 22 | "@/*": ["./*"] 23 | } 24 | }, 25 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], 26 | "exclude": ["node_modules"] 27 | } 28 | -------------------------------------------------------------------------------- /gui/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2020", 4 | "useDefineForClassFields": true, 5 | "lib": [ 6 | "ES2020", 7 | "DOM", 8 | "DOM.Iterable" 9 | ], 10 | "module": "ESNext", 11 | "skipLibCheck": true, 12 | /* Bundler mode */ 13 | "moduleResolution": "bundler", 14 | "allowImportingTsExtensions": true, 15 | "resolveJsonModule": true, 16 | "isolatedModules": true, 17 | "noEmit": true, 18 | "jsx": "react-jsx", 19 | /* Linting */ 20 | "strict": true, 21 | "noUnusedLocals": true, 22 | "noUnusedParameters": true, 23 | "noFallthroughCasesInSwitch": true 24 | }, 25 | "include": [ 26 | "src" 27 | ], 28 | "references": [ 29 | { 30 | "path": "./tsconfig.node.json" 31 | } 32 | ] 33 | } -------------------------------------------------------------------------------- /gui/src/components/CustomTypeList.tsx: -------------------------------------------------------------------------------- 1 | import { useRepository } from "../store/useRepository"; 2 | 3 | import { CustomTypeCard } from "./CustomTypeCard"; 4 | 5 | export function CustomTypeList(): JSX.Element { 6 | const customTypes = useRepository((state) => state.customTypes); 7 | 8 | return ( 9 |
10 |

Custom Types ({customTypes?.length})

11 |
    12 | {customTypes?.map((customType) => ( 13 |
  • 14 | 15 |
  • 16 | ))} 17 | {customTypes?.length === 0 ? ( 18 |
  • No Shared Slices found.
  • 19 | ) : null} 20 |
21 |
22 | ); 23 | } 24 | -------------------------------------------------------------------------------- /gui/src/store/useSliceMachineConfig.ts: -------------------------------------------------------------------------------- 1 | import { SliceMachineConfig } from "@slicemachine/manager"; 2 | import { create } from "zustand"; 3 | 4 | import { useManager } from "./useManager"; 5 | 6 | type SliceMachineConfigState = { 7 | config: null | SliceMachineConfig; 8 | dashboard: null | string; 9 | fetch: () => Promise; 10 | }; 11 | 12 | export const useSliceMachineConfig = create((set) => ({ 13 | config: null, 14 | dashboard: null, 15 | fetch: async () => { 16 | const config = await useManager().project.getSliceMachineConfig(); 17 | 18 | const dashboard = config.apiEndpoint 19 | ? config.apiEndpoint.replace(".cdn", "") 20 | : `https://${config.repositoryName}.prismic.io`; 21 | 22 | set({ config, dashboard }); 23 | }, 24 | })); 25 | -------------------------------------------------------------------------------- /src/cli-watcher.ts: -------------------------------------------------------------------------------- 1 | if ( 2 | import.meta.env.MODE === "development" && 3 | !["check", "migrate"].includes(process.argv.slice(2).pop() ?? "") 4 | ) { 5 | // Automatically restart the process ONLY when app is in development mode. 6 | Promise.all([import("node:url"), import("nodemon"), import("chalk")]).then( 7 | ([url, { default: nodemon }, { default: chalk }]) => { 8 | const relativePath = (path: string) => 9 | url.fileURLToPath(new URL(path, import.meta.url)); 10 | 11 | nodemon({ 12 | script: relativePath("./cli.cjs"), 13 | args: process.argv.slice(2), 14 | delay: 1, 15 | watch: [relativePath("../dist")], 16 | }).on("restart", () => { 17 | console.info(`${chalk.dim("[cli]")} Restarting...`); 18 | }); 19 | }, 20 | ); 21 | } else { 22 | import("./cli"); 23 | } 24 | -------------------------------------------------------------------------------- /playground/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "inspiring-briouat-syt67g", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "next dev", 7 | "build": "next build", 8 | "start": "next start", 9 | "lint": "next lint", 10 | "slicemachine": "start-slicemachine" 11 | }, 12 | "dependencies": { 13 | "@prismicio/client": "^7.1.1", 14 | "@prismicio/next": "^1.3.4", 15 | "@prismicio/react": "^2.7.1", 16 | "@types/node": "20.5.0", 17 | "@types/react": "18.2.20", 18 | "@types/react-dom": "18.2.7", 19 | "next": "13.4.17", 20 | "react": "18.2.0", 21 | "react-dom": "18.2.0", 22 | "typescript": "5.1.6" 23 | }, 24 | "devDependencies": { 25 | "@slicemachine/adapter-next": "^0.3.10", 26 | "slice-machine-ui": "^1.8.0" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /gui/src/index.css: -------------------------------------------------------------------------------- 1 | @import "@prismicio/editor-ui/style.css"; 2 | 3 | @tailwind base; 4 | @tailwind components; 5 | @tailwind utilities; 6 | 7 | html { 8 | @apply overflow-y-scroll; 9 | } 10 | 11 | .container { 12 | @apply px-4 max-w-screen-lg mx-auto; 13 | } 14 | 15 | .heading-1 { 16 | @apply font-medium text-2xl; 17 | } 18 | 19 | .heading-2 { 20 | @apply font-medium text-xl; 21 | } 22 | 23 | .heading-3 { 24 | @apply font-medium; 25 | } 26 | 27 | .heading-4 { 28 | @apply font-medium; 29 | } 30 | 31 | .heading-5 { 32 | @apply font-medium; 33 | } 34 | 35 | .badge { 36 | @apply text-xs rounded bg-stone-200/50 cursor-default inline-flex items-center gap-2 px-2 py-1 text-stone-500 not-italic; 37 | } 38 | 39 | .badge.badge--medium { 40 | @apply py-1.5 41 | } 42 | 43 | .badge:hover { 44 | @apply bg-stone-200; 45 | } 46 | -------------------------------------------------------------------------------- /src/lib/prompt.ts: -------------------------------------------------------------------------------- 1 | import prompts from "prompts"; 2 | 3 | type promptArgs< 4 | TValue = unknown, 5 | TProperty extends string = string, 6 | > = prompts.PromptObject & { 7 | // Method is available, cf. docs 8 | onRender?: (this: { msg: string; value?: TValue; initial?: TValue }) => void; 9 | }; 10 | 11 | export const prompt = async ( 12 | question: promptArgs, 13 | ): Promise> => { 14 | const answers: Record = 15 | await prompts(question); 16 | 17 | if (!Object.keys(answers).length) { 18 | process.exit(130); 19 | } 20 | 21 | // Clear prompt line, clean recap are done manually 22 | process.stdout.moveCursor?.(0, -1); 23 | process.stdout.clearLine?.(1); 24 | 25 | return answers; 26 | }; 27 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🙋‍♀️ Feature request 3 | about: Suggest an idea or enhancement for the package. 4 | title: "" 5 | labels: "enhancement" 6 | assignees: "" 7 | --- 8 | 9 | 10 | 11 | ### Is your feature request related to a problem? Please describe. 12 | 13 | 14 | 15 | ### Describe the solution you'd like 16 | 17 | 18 | 19 | ### Describe alternatives you've considered 20 | 21 | 22 | 23 | ### Additional context 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/models/findDuplicatedSlices.ts: -------------------------------------------------------------------------------- 1 | import { CompositeSlice } from "./CompositeSlice"; 2 | import { SharedSlice } from "./SharedSlice"; 3 | 4 | export const findDuplicatedSlices = ( 5 | slices: (CompositeSlice | SharedSlice)[], 6 | ): (CompositeSlice | SharedSlice)[][] => { 7 | const duplicatedSlices: (CompositeSlice | SharedSlice)[][] = []; 8 | 9 | for (const slice of slices) { 10 | const maybeDuplicatedSlices = duplicatedSlices.find((slices) => { 11 | if (slice instanceof SharedSlice) { 12 | // TODO 13 | } else { 14 | const diff = slice.diff(slices[0]); 15 | 16 | // All fields are alike 17 | return !diff.primary.length && !diff.items.length; 18 | } 19 | 20 | return false; 21 | }); 22 | 23 | if (maybeDuplicatedSlices) { 24 | maybeDuplicatedSlices.push(slice); 25 | } else { 26 | duplicatedSlices.push([slice]); 27 | } 28 | } 29 | 30 | return duplicatedSlices.filter((slices) => slices.length > 1); 31 | }; 32 | -------------------------------------------------------------------------------- /.github/workflows/issues.yml: -------------------------------------------------------------------------------- 1 | name: issues 2 | 3 | on: 4 | issues: 5 | types: 6 | - opened 7 | 8 | jobs: 9 | issues: 10 | if: github.event.issue.author_association == 'NONE' 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Checkout 15 | uses: actions/checkout@master 16 | 17 | - name: Reply bug report 18 | if: contains(github.event.issue.labels.*.name, 'bug') 19 | env: 20 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 21 | ISSUE_URL: ${{ github.event.issue.html_url }} 22 | run: gh issue comment $ISSUE_URL --body-file ./.github/workflows/issues--bug_report.md 23 | 24 | - name: Reply feature request 25 | if: contains(github.event.issue.labels.*.name, 'enhancement') 26 | env: 27 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 28 | ISSUE_URL: ${{ github.event.issue.html_url }} 29 | run: gh issue comment $ISSUE_URL --body-file ./.github/workflows/issues--feature_request.md 30 | -------------------------------------------------------------------------------- /src/models/SharedSlice.ts: -------------------------------------------------------------------------------- 1 | import { SharedSlice as SharedSliceDefinition } from "@prismicio/types-internal/lib/customtypes"; 2 | 3 | import { CompositeSlice } from "./CompositeSlice"; 4 | 5 | export class SharedSlice { 6 | definition: SharedSliceDefinition; 7 | 8 | get id(): string { 9 | return this.definition.id; 10 | } 11 | 12 | constructor(sharedSlice: SharedSliceDefinition) { 13 | this.definition = sharedSlice; 14 | } 15 | 16 | static fromCompositeSlice(compositeSlice: CompositeSlice): SharedSlice { 17 | return new SharedSlice({ 18 | id: compositeSlice.id, 19 | type: "SharedSlice", 20 | name: compositeSlice.definition.fieldset ?? compositeSlice.id, 21 | variations: [ 22 | { 23 | id: "default", 24 | name: "Default", 25 | description: "Default", 26 | imageUrl: "", 27 | docURL: "...", 28 | version: "initial", 29 | primary: compositeSlice.definition["non-repeat"], 30 | items: compositeSlice.definition.repeat, 31 | }, 32 | ], 33 | }); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /vite.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from "vite"; 2 | import sdk from "vite-plugin-sdk"; 3 | 4 | export default defineConfig({ 5 | build: { 6 | lib: { 7 | entry: { 8 | index: "./src/index.ts", 9 | cli: "./src/cli.ts", 10 | "cli-watcher": "./src/cli-watcher.ts", 11 | }, 12 | }, 13 | rollupOptions: { 14 | // Listing `nodemon` as external prevents it from being 15 | // bundled. Note that `nodemon` is listed under 16 | // devDependencies and is used in 17 | // `./src/bin/start-slicemachine.ts`, which would 18 | // normally prompt Vite to bundle the dependency. 19 | external: ["nodemon"], 20 | }, 21 | }, 22 | plugins: [ 23 | sdk({ 24 | internalDependencies: ["meow"], 25 | }), 26 | ], 27 | test: { 28 | coverage: { 29 | provider: "v8", 30 | reporter: ["lcovonly", "text"], 31 | }, 32 | setupFiles: ["./test/__setup__.ts"], 33 | server: { 34 | deps: { 35 | inline: 36 | // TODO: Replace with true once https://github.com/vitest-dev/vitest/issues/2806 is fixed. 37 | [/^(?!.*vitest).*$/], 38 | }, 39 | }, 40 | }, 41 | }); 42 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🚨 Bug report 3 | about: Report a bug report to help improve the package. 4 | title: "" 5 | labels: "bug" 6 | assignees: "" 7 | --- 8 | 9 | 16 | 17 | ### Versions 18 | 19 | - @prismicio/upgrade-from-legacy: 20 | - node: 21 | 22 | ### Reproduction 23 | 24 | 25 | 26 |
27 | Additional Details 28 |
29 | 30 |
31 | 32 | ### Steps to reproduce 33 | 34 | ### What is expected? 35 | 36 | ### What is actually happening? 37 | -------------------------------------------------------------------------------- /gui/src/components/StatusDot.tsx: -------------------------------------------------------------------------------- 1 | import clsx from "clsx"; 2 | import { forwardRef } from "react"; 3 | 4 | type StatusDotProps = { 5 | type: "unknown" | "success" | "warn" | "error"; 6 | }; 7 | 8 | export const StatusDot = forwardRef( 9 | function StatusDot({ type }: StatusDotProps, ref): JSX.Element { 10 | return ( 11 | 12 | {["warn", "error"].includes(type) ? ( 13 | 24 | ) : null} 25 | 33 | 34 | ); 35 | }, 36 | ); 37 | -------------------------------------------------------------------------------- /src/lib/createUpgradeExpressApp.ts: -------------------------------------------------------------------------------- 1 | import * as path from "node:path"; 2 | 3 | import { 4 | SliceMachineManager, 5 | createSliceMachineManagerMiddleware, 6 | } from "@slicemachine/manager"; 7 | import cors from "cors"; 8 | import express, { Express } from "express"; 9 | import { createProxyMiddleware } from "http-proxy-middleware"; 10 | import serveStatic from "serve-static"; 11 | 12 | type CreateUpgradeExpressAppArgs = { 13 | sliceMachineManager: SliceMachineManager; 14 | }; 15 | 16 | export const createUpgradeExpressApp = ( 17 | args: CreateUpgradeExpressAppArgs, 18 | ): Express => { 19 | const app = express(); 20 | 21 | app.use(cors()); 22 | 23 | app.use( 24 | "/_manager", 25 | createSliceMachineManagerMiddleware({ 26 | sliceMachineManager: args.sliceMachineManager, 27 | }), 28 | ); 29 | 30 | if (import.meta.env.MODE === "development") { 31 | app.use( 32 | "/", 33 | createProxyMiddleware({ 34 | target: "http://localhost:5173", 35 | changeOrigin: true, 36 | ws: true, 37 | logLevel: "warn", 38 | }), 39 | ); 40 | } else { 41 | app.use( 42 | serveStatic(path.resolve(__dirname, "../gui"), { 43 | extensions: ["html"], 44 | }), 45 | ); 46 | } 47 | 48 | return app; 49 | }; 50 | -------------------------------------------------------------------------------- /.github/workflows/issues--feature_request.md: -------------------------------------------------------------------------------- 1 | > This issue has been labeled as a **feature request** since it was created using the [🙋‍♀️ **Feature Request Template**](./new?assignees=&labels=enhancement&template=feature_request.md&title=). 2 | 3 | Hi there, thank you so much for your request! 4 | 5 | Following our [Maintenance Process](../blob/HEAD/CONTRIBUTING.md#maintaining), we will review your request and get back to you soon. If we decide to implement it, will proceed to implement the feature during the _last week of the month_. In the meantime, feel free to provide any details to help us better understand your request, such as: 6 | 7 | - The context that made you think of this feature request 8 | - As many details about the solution you'd like to see implemented, how it should behave, etc. 9 | - Any alternative solution you have considered 10 | 11 | If you think you can implement the proposed change yourself, you're more than welcome to [open a pull request](../pulls) implementing the new feature. Check out our [quick start guide](../blob/HEAD/CONTRIBUTING.md#quick-start) for a simple contribution process. Please note that submitting a pull request does not guarantee the feature will be merged. 12 | 13 | _- The Prismic Open-Source Team_ 14 | -------------------------------------------------------------------------------- /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { 4 | browser: true, 5 | node: true, 6 | }, 7 | parserOptions: { 8 | parser: "@typescript-eslint/parser", 9 | ecmaVersion: 2020, 10 | }, 11 | extends: [ 12 | "plugin:@typescript-eslint/eslint-recommended", 13 | "plugin:@typescript-eslint/recommended", 14 | "plugin:prettier/recommended", 15 | "plugin:react-hooks/recommended", 16 | ], 17 | plugins: ["eslint-plugin-tsdoc", "react-refresh"], 18 | rules: { 19 | "no-console": ["warn", { allow: ["info", "warn", "error"] }], 20 | "no-debugger": "warn", 21 | "no-undef": "off", 22 | curly: "error", 23 | "prefer-const": "error", 24 | "padding-line-between-statements": [ 25 | "error", 26 | { blankLine: "always", prev: "*", next: "return" }, 27 | ], 28 | "@typescript-eslint/no-unused-vars": [ 29 | "error", 30 | { 31 | argsIgnorePattern: "^_", 32 | varsIgnorePattern: "^_", 33 | }, 34 | ], 35 | "@typescript-eslint/no-var-requires": "off", 36 | "@typescript-eslint/explicit-module-boundary-types": "error", 37 | "tsdoc/syntax": "warn", 38 | "react-refresh/only-export-components": [ 39 | "warn", 40 | { allowConstantExport: true }, 41 | ], 42 | "react-hooks/rules-of-hooks": "off", 43 | }, 44 | }; 45 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Types of changes 4 | 5 | 6 | 7 | - [ ] Chore (a non-breaking change which is related to package maintenance) 8 | - [ ] Bug fix (a non-breaking change which fixes an issue) 9 | - [ ] New feature (a non-breaking change which adds functionality) 10 | - [ ] Breaking change (fix or feature that would cause existing functionality to change) 11 | 12 | ## Description 13 | 14 | 15 | 16 | 17 | 18 | ## Checklist: 19 | 20 | 21 | 22 | 23 | - [ ] My change requires an update to the official documentation. 24 | - [ ] All [TSDoc](https://tsdoc.org) comments are up-to-date and new ones have been added where necessary. 25 | - [ ] All new and existing tests are passing. 26 | 27 | 28 | -------------------------------------------------------------------------------- /gui/src/components/AppHeader.tsx: -------------------------------------------------------------------------------- 1 | import { Icon, Skeleton } from "@prismicio/editor-ui"; 2 | 3 | import { useSliceMachineConfig } from "../store/useSliceMachineConfig"; 4 | import { useUser } from "../store/useUser"; 5 | 6 | export function AppHeader(): JSX.Element { 7 | const [config, dashboard] = useSliceMachineConfig((state) => [ 8 | state.config, 9 | state.dashboard, 10 | ]); 11 | const profile = useUser((state) => state.profile); 12 | 13 | return ( 14 |
15 | {config ? ( 16 |
17 |

{config.repositoryName}

18 | 24 |
25 | ) : ( 26 |
27 | 28 |
29 | )} 30 | {profile ? ( 31 | 32 | 33 | Logged in as {profile.email} 34 | 35 | ) : ( 36 |
37 | 38 |
39 | )} 40 |
41 | ); 42 | } 43 | -------------------------------------------------------------------------------- /playground/public/next.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/workflows/issues--bug_report.md: -------------------------------------------------------------------------------- 1 | > This issue has been labeled as a **bug** since it was created using the [🚨 **Bug Report Template**](./new?assignees=&labels=bug&template=bug_report.md&title=). 2 | 3 | Hi there, thank you so much for the report! 4 | 5 | Following our [Maintenance Process](../blob/HEAD/CONTRIBUTING.md#maintaining), we will review your bug report and get back to you _next Wednesday_. To ensure a smooth review of your issue and avoid unnecessary delays, please make sure your issue includes the following: 6 | 7 | - Information about your environment and packages you use (Node.js version, package names and their versions, etc.) 8 | _Feel free to attach a copy of your `package.json` file._ 9 | - Any troubleshooting steps you already went through 10 | - A minimal reproduction of the issue, and/or instructions on how to reproduce it 11 | 12 | If you have identified the cause of the bug described in your report and know how to fix it, you're more than welcome to [open a pull request](../pulls) addressing it. Check out our [quick start guide](../blob/HEAD/CONTRIBUTING.md#quick-start) for a simple contribution process. 13 | 14 | If you think your issue is a _question_ (not a bug) and would like quicker support, please _close this issue_ and forward it to an appropriate section on our community forum: https://community.prismic.io 15 | 16 | _- The Prismic Open-Source Team_ 17 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "@trivago/prettier-plugin-sort-imports", 4 | "prettier-plugin-jsdoc" 5 | ], 6 | "jsdocCapitalizeDescription": false, 7 | "jsdocSeparateReturnsFromParam": true, 8 | "jsdocSeparateTagGroups": true, 9 | "jsdocSingleLineComment": false, 10 | "tsdoc": true, 11 | "importOrder": [ 12 | "^vitest(/|$)", 13 | "^node:", 14 | "", 15 | "^(?!.*/src(/|$)).*/__testutils__(/|$)", 16 | "^(?!.*/src(/|$)).*/__fixtures__(/|$)", 17 | "^(?!.*/src(/|$)).*/lib(/|$)", 18 | "^(?!.*/src(/|$)).*/types(/|$)", 19 | "^(?!.*/src(/|$)).*/errors(/|$)", 20 | "^(?!.*/src(/|$))../../../../../", 21 | "^(?!.*/src(/|$))../../../../", 22 | "^(?!.*/src(/|$))../../../", 23 | "^(?!.*/src(/|$))../../", 24 | "^(?!.*/src(/|$))../", 25 | "^(?!.*/src(/|$))./(.*/)+", 26 | "^(?!.*/src(/|$))./", 27 | "/src(/|$)" 28 | ], 29 | "importOrderSeparation": true, 30 | "importOrderSortSpecifiers": true, 31 | "importOrderGroupNamespaceSpecifiers": true, 32 | "printWidth": 80, 33 | "useTabs": true, 34 | "semi": true, 35 | "singleQuote": false, 36 | "quoteProps": "as-needed", 37 | "jsxSingleQuote": false, 38 | "trailingComma": "all", 39 | "bracketSpacing": true, 40 | "bracketSameLine": false, 41 | "arrowParens": "always", 42 | "requirePragma": false, 43 | "insertPragma": false, 44 | "htmlWhitespaceSensitivity": "css", 45 | "endOfLine": "lf" 46 | } -------------------------------------------------------------------------------- /playground/README.md: -------------------------------------------------------------------------------- 1 | This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app). 2 | 3 | ## Getting Started 4 | 5 | First, run the development server: 6 | 7 | ```bash 8 | npm run dev 9 | # or 10 | yarn dev 11 | # or 12 | pnpm dev 13 | ``` 14 | 15 | Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. 16 | 17 | You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. 18 | 19 | This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font. 20 | 21 | ## Learn More 22 | 23 | To learn more about Next.js, take a look at the following resources: 24 | 25 | - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. 26 | - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. 27 | 28 | You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! 29 | 30 | ## Deploy on Vercel 31 | 32 | The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. 33 | 34 | Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. 35 | -------------------------------------------------------------------------------- /playground/prismicio.ts: -------------------------------------------------------------------------------- 1 | import * as prismic from "@prismicio/client"; 2 | import * as prismicNext from "@prismicio/next"; 3 | 4 | import config from "./slicemachine.config.json"; 5 | 6 | /** 7 | * The project's Prismic repository name. 8 | */ 9 | export const repositoryName = config.repositoryName; 10 | 11 | /** 12 | * A list of Route Resolver objects that define how a document's `url` field is 13 | * resolved. 14 | * 15 | * {@link https://prismic.io/docs/route-resolver#route-resolver} 16 | */ 17 | // TODO: Update the routes array to match your project's route structure. 18 | const routes: prismic.ClientConfig["routes"] = [ 19 | { 20 | type: "homepage", 21 | path: "/", 22 | }, 23 | { 24 | type: "page", 25 | path: "/:uid", 26 | }, 27 | ]; 28 | 29 | /** 30 | * Creates a Prismic client for the project's repository. The client is used to 31 | * query content from the Prismic API. 32 | * 33 | * @param config - Configuration for the Prismic client. 34 | */ 35 | export const createClient = ( 36 | config: prismicNext.CreateClientConfig = {}, 37 | ): prismic.Client => { 38 | const client = prismic.createClient(repositoryName, { 39 | routes, 40 | fetchOptions: 41 | process.env.NODE_ENV === "production" 42 | ? { next: { tags: ["prismic"] }, cache: "force-cache" } 43 | : { next: { revalidate: 5 } }, 44 | ...config, 45 | }); 46 | 47 | prismicNext.enableAutoPreviews({ 48 | client, 49 | previewData: config.previewData, 50 | req: config.req, 51 | }); 52 | 53 | return client; 54 | }; 55 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. 4 | 5 | ### [0.0.3](https://github.com/prismicio/prismic-upgrade-from-legacy/compare/v0.0.2...v0.0.3) (2023-08-31) 6 | 7 | 8 | ### Features 9 | 10 | * migrate composite slices and custom types ([0977b3b](https://github.com/prismicio/prismic-upgrade-from-legacy/commit/0977b3b91f03743a97664030e2f0cd89c165a601)) 11 | * start looking for optimizations ([3a355ac](https://github.com/prismicio/prismic-upgrade-from-legacy/commit/3a355aca762dd695c9b28787d6812d1693249abf)) 12 | 13 | ### [0.0.2](https://github.com/prismicio/prismic-upgrade-from-legacy/compare/v0.0.1...v0.0.2) (2023-08-21) 14 | 15 | ### 0.0.1 (2023-08-21) 16 | 17 | 18 | ### Features 19 | 20 | * base CLI ([9677fe8](https://github.com/prismicio/prismic-upgrade-from-legacy/commit/9677fe85fd14429cebd190258a2ff0402d427252)) 21 | 22 | 23 | ### Chore 24 | 25 | * init ([41062c1](https://github.com/prismicio/prismic-upgrade-from-legacy/commit/41062c139fae6965beb71595edc19c93426c2f78)) 26 | * init project ([e0c34cb](https://github.com/prismicio/prismic-upgrade-from-legacy/commit/e0c34cbfd9bf5dac6365a6761f8dcc73baad98f3)) 27 | * playground ([280ab17](https://github.com/prismicio/prismic-upgrade-from-legacy/commit/280ab17f91f375238eaccec0e1de15bedf9f8b76)) 28 | * rename package ([dc655a5](https://github.com/prismicio/prismic-upgrade-from-legacy/commit/dc655a58b488817e7294fbdc39091b99e6a4e5ea)) 29 | -------------------------------------------------------------------------------- /gui/src/store/useRepository.ts: -------------------------------------------------------------------------------- 1 | import { create } from "zustand"; 2 | 3 | import { useManager } from "./useManager"; 4 | import { useSliceConflicts } from "./useSliceConflicts"; 5 | 6 | import { CompositeSlice } from "../../../src/models/CompositeSlice"; 7 | import { CustomType } from "../../../src/models/CustomType"; 8 | import { SharedSlice } from "../../../src/models/SharedSlice"; 9 | import { checkSliceConflicts } from "../../../src/models/checkSliceConflicts"; 10 | 11 | type RepositoryState = { 12 | customTypes: null | CustomType[]; 13 | sharedSlices: null | SharedSlice[]; 14 | compositeSlices: null | CompositeSlice[]; 15 | fetch: () => Promise; 16 | }; 17 | 18 | export const useRepository = create((set) => ({ 19 | customTypes: null, 20 | sharedSlices: null, 21 | compositeSlices: null, 22 | fetch: async () => { 23 | const [rawCustomTypes, rawSharedSlices] = await Promise.all([ 24 | useManager().customTypes.fetchRemoteCustomTypes(), 25 | useManager().slices.fetchRemoteSlices(), 26 | ]); 27 | const customTypes = rawCustomTypes.map( 28 | (customType) => new CustomType(customType), 29 | ); 30 | const sharedSlices = rawSharedSlices.map( 31 | (sharedSlice) => new SharedSlice(sharedSlice), 32 | ); 33 | const compositeSlices = customTypes 34 | .map((customType) => customType.getAllCompositeSlices()) 35 | .flat(); 36 | 37 | set({ 38 | customTypes, 39 | sharedSlices, 40 | compositeSlices, 41 | }); 42 | 43 | useSliceConflicts.setState((_state) => ({ 44 | conflicts: checkSliceConflicts([...sharedSlices, ...compositeSlices]), 45 | })); 46 | }, 47 | })); 48 | -------------------------------------------------------------------------------- /src/models/CompositeSlice.ts: -------------------------------------------------------------------------------- 1 | import { CompositeSlice as CompositeSliceDefinition } from "@prismicio/types-internal/lib/customtypes"; 2 | 3 | import { CustomType } from "./CustomType"; 4 | import { SharedSlice } from "./SharedSlice"; 5 | 6 | export type CompositeSliceMeta = { 7 | parent: CustomType; 8 | path: { 9 | tabID: string; 10 | sliceZoneID: string; 11 | sliceID: string; 12 | }; 13 | }; 14 | 15 | export class CompositeSlice { 16 | definition: CompositeSliceDefinition; 17 | meta: CompositeSliceMeta; 18 | 19 | get id(): string { 20 | return this.meta.path.sliceID; 21 | } 22 | 23 | constructor( 24 | compositeSlice: CompositeSliceDefinition, 25 | meta: CompositeSliceMeta, 26 | ) { 27 | this.definition = compositeSlice; 28 | this.meta = meta; 29 | } 30 | 31 | diff(slice: CompositeSlice | SharedSlice): { 32 | primary: string[]; 33 | items: string[]; 34 | } { 35 | const primary: string[] = []; 36 | const items: string[] = []; 37 | 38 | if (slice instanceof SharedSlice) { 39 | // TODO 40 | } else if ( 41 | JSON.stringify(this.definition) !== JSON.stringify(slice.definition) 42 | ) { 43 | const nonRepeatKeys = Object.keys({ 44 | ...this.definition["non-repeat"], 45 | ...slice.definition["non-repeat"], 46 | }); 47 | for (const key of nonRepeatKeys) { 48 | if ( 49 | this.definition["non-repeat"]?.[key]?.type !== 50 | slice.definition["non-repeat"]?.[key]?.type 51 | ) { 52 | primary.push(key); 53 | } 54 | } 55 | 56 | const repeatKeys = Object.keys({ 57 | ...this.definition.repeat, 58 | ...slice.definition.repeat, 59 | }); 60 | for (const key of repeatKeys) { 61 | if ( 62 | this.definition.repeat?.[key]?.type !== 63 | slice.definition.repeat?.[key]?.type 64 | ) { 65 | items.push(key); 66 | } 67 | } 68 | } 69 | 70 | return { 71 | primary, 72 | items, 73 | }; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /gui/src/App.tsx: -------------------------------------------------------------------------------- 1 | import { AnimatedElement, DocumentStatusBar, Tab } from "@prismicio/editor-ui"; 2 | import { useEffect, useState } from "react"; 3 | 4 | import { AppFooter } from "./components/AppFooter"; 5 | import { AppHeader } from "./components/AppHeader"; 6 | import { CustomTypeList } from "./components/CustomTypeList"; 7 | import { SharedSliceList } from "./components/SharedSliceList"; 8 | import { useRepository } from "./store/useRepository"; 9 | import { useSliceMachineConfig } from "./store/useSliceMachineConfig"; 10 | import { useUser } from "./store/useUser"; 11 | 12 | export function App(): JSX.Element { 13 | const repository = useRepository(); 14 | const sliceMachineConfig = useSliceMachineConfig(); 15 | const user = useUser(); 16 | 17 | const tabs = ["Slices", "Custom Types", "Upgrade Summary"] as const; 18 | const [activeTab, setActiveTab] = 19 | useState<(typeof tabs)[number]>("Custom Types"); 20 | 21 | useEffect(() => { 22 | repository.fetch(); 23 | sliceMachineConfig.fetch(); 24 | user.fetch(); 25 | }, []); 26 | 27 | return ( 28 | <> 29 | 30 | 31 |
32 |
33 | 43 | 44 | {activeTab === "Slices" ? ( 45 |
46 | TODO: Slices 47 |
48 | ) : activeTab === "Custom Types" ? ( 49 |
50 | 51 | 52 |
53 | ) : ( 54 |
55 | TODO: Upgrade Summary 56 |
57 | )} 58 |
59 |
60 |
61 | 62 | 63 | ); 64 | } 65 | -------------------------------------------------------------------------------- /src/models/CustomType.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CustomType as CustomTypeDefinition, 3 | DynamicSlice as DynamicSliceDefinition, 4 | } from "@prismicio/types-internal/lib/customtypes"; 5 | 6 | import { CompositeSlice } from "./CompositeSlice"; 7 | 8 | export class CustomType { 9 | definition: CustomTypeDefinition; 10 | 11 | get id(): string { 12 | return this.definition.id; 13 | } 14 | 15 | constructor(customType: CustomTypeDefinition) { 16 | this.definition = customType; 17 | } 18 | 19 | getAllCompositeSlices = (): CompositeSlice[] => { 20 | const extractedCompositeSlices: CompositeSlice[] = []; 21 | 22 | for (const tabID in this.definition.json) { 23 | const fields = this.definition.json[tabID]; 24 | 25 | for (const fieldID in fields) { 26 | const field = fields[fieldID]; 27 | 28 | // TODO: Do we need to handle "choice" also? 29 | if (field.type !== "Slices") { 30 | continue; 31 | } 32 | 33 | const slices = field.config?.choices; 34 | 35 | if (!slices) { 36 | continue; 37 | } 38 | 39 | for (const sliceID in slices) { 40 | const slice = slices[sliceID]; 41 | 42 | // TODO: Handle legacy slices 43 | if (slice.type !== "Slice") { 44 | continue; 45 | } 46 | 47 | extractedCompositeSlices.push( 48 | new CompositeSlice(slice, { 49 | parent: this, 50 | path: { 51 | tabID, 52 | sliceZoneID: fieldID, 53 | sliceID, 54 | }, 55 | }), 56 | ); 57 | } 58 | } 59 | } 60 | 61 | return extractedCompositeSlices; 62 | }; 63 | 64 | updateSliceInSliceZone( 65 | definition: DynamicSliceDefinition, 66 | path: { 67 | tabID: string; 68 | sliceZoneID: string; 69 | sliceID: string; 70 | }, 71 | ): void { 72 | const maybeSliceZone = 73 | this.definition.json?.[path.tabID]?.[path.sliceZoneID]; 74 | 75 | if (maybeSliceZone.type === "Slices" && maybeSliceZone.config?.choices) { 76 | maybeSliceZone.config.choices[path.sliceID] = definition; 77 | } else { 78 | throw new Error( 79 | `Could not find slice zone at ${this.id}::${path.tabID}::${path.sliceZoneID}`, 80 | ); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/cli.ts: -------------------------------------------------------------------------------- 1 | import meow from "meow"; 2 | 3 | import { ExplainedError } from "./lib/ExplainedError"; 4 | 5 | import { name as pkgName, version as pkgVersion } from "../package.json"; 6 | 7 | import { createUpgradeProcess } from "./UpgradeProcess"; 8 | 9 | const cli = meow( 10 | ` 11 | Prismic Slice Machine Upgrade CLI 12 | 13 | DOCUMENTATION 14 | https://prismic.dev/upgrade 15 | 16 | VERSION 17 | ${pkgName}@${pkgVersion} 18 | 19 | USAGE 20 | $ npx @prismicio/upgrade-from-legacy 21 | $ npx @prismicio/upgrade-from-legacy 22 | 23 | COMMANDS 24 | gui (default) Launch upgrade GUI 25 | 26 | check Check for conflicts on current project 27 | migrate Migrate to shared slices 28 | 29 | OPTIONS 30 | --open, -o Open GUI in browser when ready 31 | 32 | --help, -h Display CLI help 33 | --version, -v Display CLI version 34 | `, 35 | { 36 | importMeta: import.meta, 37 | flags: { 38 | open: { 39 | type: "boolean", 40 | shortFlag: "o", 41 | default: false, 42 | }, 43 | help: { 44 | type: "boolean", 45 | shortFlag: "h", 46 | default: false, 47 | }, 48 | version: { 49 | type: "boolean", 50 | shortFlag: "v", 51 | default: false, 52 | }, 53 | }, 54 | description: false, 55 | autoHelp: false, 56 | autoVersion: false, 57 | allowUnknownFlags: false, 58 | }, 59 | ); 60 | 61 | if ( 62 | cli.flags.help || 63 | (cli.input[0] && !["gui", "check", "migrate"].includes(cli.input[0])) 64 | ) { 65 | cli.showHelp(); 66 | } else if (cli.flags.version) { 67 | // eslint-disable-next-line no-console 68 | console.log(`${pkgName}@${pkgVersion}`); 69 | process.exit(0); 70 | } else { 71 | const initProcess = createUpgradeProcess({ 72 | ...cli.flags, 73 | input: cli.input, 74 | }); 75 | 76 | (async () => { 77 | try { 78 | switch (cli.input[0]) { 79 | case "check": 80 | await initProcess.check(); 81 | break; 82 | 83 | case "migrate": 84 | await initProcess.migrate(); 85 | break; 86 | 87 | default: 88 | await initProcess.gui(); 89 | break; 90 | } 91 | } catch (error) { 92 | if (error instanceof ExplainedError) { 93 | // eslint-disable-next-line no-console 94 | console.log(error.message); 95 | 96 | return; 97 | } 98 | throw error; 99 | } 100 | })(); 101 | } 102 | -------------------------------------------------------------------------------- /gui/public/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /playground/app/page.tsx: -------------------------------------------------------------------------------- 1 | import Image from "next/image"; 2 | 3 | import styles from "./page.module.css"; 4 | 5 | export default function Home(): JSX.Element { 6 | return ( 7 |
8 |
9 |

10 | Get started by editing  11 | app/page.tsx 12 |

13 | 30 |
31 | 32 |
33 | Next.js Logo 41 |
42 | 43 | 94 |
95 | ); 96 | } 97 | -------------------------------------------------------------------------------- /playground/app/globals.css: -------------------------------------------------------------------------------- 1 | :root { 2 | --max-width: 1100px; 3 | --border-radius: 12px; 4 | --font-mono: ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', 5 | 'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro', 6 | 'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace; 7 | 8 | --foreground-rgb: 0, 0, 0; 9 | --background-start-rgb: 214, 219, 220; 10 | --background-end-rgb: 255, 255, 255; 11 | 12 | --primary-glow: conic-gradient( 13 | from 180deg at 50% 50%, 14 | #16abff33 0deg, 15 | #0885ff33 55deg, 16 | #54d6ff33 120deg, 17 | #0071ff33 160deg, 18 | transparent 360deg 19 | ); 20 | --secondary-glow: radial-gradient( 21 | rgba(255, 255, 255, 1), 22 | rgba(255, 255, 255, 0) 23 | ); 24 | 25 | --tile-start-rgb: 239, 245, 249; 26 | --tile-end-rgb: 228, 232, 233; 27 | --tile-border: conic-gradient( 28 | #00000080, 29 | #00000040, 30 | #00000030, 31 | #00000020, 32 | #00000010, 33 | #00000010, 34 | #00000080 35 | ); 36 | 37 | --callout-rgb: 238, 240, 241; 38 | --callout-border-rgb: 172, 175, 176; 39 | --card-rgb: 180, 185, 188; 40 | --card-border-rgb: 131, 134, 135; 41 | } 42 | 43 | @media (prefers-color-scheme: dark) { 44 | :root { 45 | --foreground-rgb: 255, 255, 255; 46 | --background-start-rgb: 0, 0, 0; 47 | --background-end-rgb: 0, 0, 0; 48 | 49 | --primary-glow: radial-gradient(rgba(1, 65, 255, 0.4), rgba(1, 65, 255, 0)); 50 | --secondary-glow: linear-gradient( 51 | to bottom right, 52 | rgba(1, 65, 255, 0), 53 | rgba(1, 65, 255, 0), 54 | rgba(1, 65, 255, 0.3) 55 | ); 56 | 57 | --tile-start-rgb: 2, 13, 46; 58 | --tile-end-rgb: 2, 5, 19; 59 | --tile-border: conic-gradient( 60 | #ffffff80, 61 | #ffffff40, 62 | #ffffff30, 63 | #ffffff20, 64 | #ffffff10, 65 | #ffffff10, 66 | #ffffff80 67 | ); 68 | 69 | --callout-rgb: 20, 20, 20; 70 | --callout-border-rgb: 108, 108, 108; 71 | --card-rgb: 100, 100, 100; 72 | --card-border-rgb: 200, 200, 200; 73 | } 74 | } 75 | 76 | * { 77 | box-sizing: border-box; 78 | padding: 0; 79 | margin: 0; 80 | } 81 | 82 | html, 83 | body { 84 | max-width: 100vw; 85 | overflow-x: hidden; 86 | } 87 | 88 | body { 89 | color: rgb(var(--foreground-rgb)); 90 | background: linear-gradient( 91 | to bottom, 92 | transparent, 93 | rgb(var(--background-end-rgb)) 94 | ) 95 | rgb(var(--background-start-rgb)); 96 | } 97 | 98 | a { 99 | color: inherit; 100 | text-decoration: none; 101 | } 102 | 103 | @media (prefers-color-scheme: dark) { 104 | html { 105 | color-scheme: dark; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: push 4 | 5 | jobs: 6 | prepare: 7 | name: Prepare (${{ matrix.os}}, Node ${{ matrix.node }}) 8 | runs-on: ${{ matrix.os }} 9 | strategy: 10 | matrix: 11 | os: [ubuntu-latest] 12 | # https://github.com/vitejs/vite/issues/14299 13 | node: [16, 18, 20.5] 14 | 15 | steps: 16 | - name: Set up Node 17 | uses: actions/setup-node@v3 18 | with: 19 | node-version: ${{ matrix.node }} 20 | 21 | - name: Checkout 22 | uses: actions/checkout@master 23 | 24 | - name: Cache node_modules 25 | id: cache 26 | uses: actions/cache@v3 27 | with: 28 | path: node_modules 29 | key: ${{ matrix.os }}-node-v${{ matrix.node }}-deps-${{ hashFiles(format('{0}{1}', github.workspace, '/package-lock.json')) }} 30 | 31 | - name: Install dependencies 32 | if: steps.cache.outputs.cache-hit != 'true' 33 | run: npm ci 34 | 35 | suite: 36 | needs: prepare 37 | name: Suite (${{ matrix.os}}, Node ${{ matrix.node }}) 38 | runs-on: ${{ matrix.os }} 39 | strategy: 40 | fail-fast: false 41 | matrix: 42 | os: [ubuntu-latest] 43 | # https://github.com/vitejs/vite/issues/14299 44 | node: [16, 18, 20.5] 45 | 46 | steps: 47 | - name: Set up Node 48 | uses: actions/setup-node@v3 49 | with: 50 | node-version: ${{ matrix.node }} 51 | 52 | - name: Checkout 53 | uses: actions/checkout@master 54 | 55 | - name: Retrieve node_modules 56 | uses: actions/cache@v3 57 | with: 58 | path: node_modules 59 | key: ${{ matrix.os }}-node-v${{ matrix.node }}-deps-${{ hashFiles(format('{0}{1}', github.workspace, '/package-lock.json')) }} 60 | 61 | - name: Lint 62 | run: npm run lint 63 | 64 | - name: Unit 65 | run: npm run unit 66 | 67 | - name: Build 68 | run: npm run build 69 | 70 | - name: Coverage 71 | if: matrix.os == 'ubuntu-latest' && matrix.node == 16 72 | uses: codecov/codecov-action@v3 73 | 74 | types: 75 | needs: prepare 76 | name: Types (${{ matrix.os}}, Node ${{ matrix.node }}, TS ${{ matrix.typescript }}) 77 | runs-on: ${{ matrix.os }} 78 | strategy: 79 | fail-fast: false 80 | matrix: 81 | os: [ubuntu-latest] 82 | node: [16] 83 | typescript: ["4.6", "4.7", "4.8", "4.9", "5.0"] 84 | 85 | steps: 86 | - name: Set up Node 87 | uses: actions/setup-node@v3 88 | with: 89 | node-version: ${{ matrix.node }} 90 | 91 | - name: Checkout 92 | uses: actions/checkout@master 93 | 94 | - name: Retrieve node_modules 95 | uses: actions/cache@v3 96 | with: 97 | path: node_modules 98 | key: ${{ matrix.os }}-node-v${{ matrix.node }}-deps-${{ hashFiles(format('{0}{1}', github.workspace, '/package-lock.json')) }} 99 | 100 | - name: Overwrite TypeScript 101 | run: npm install --no-save typescript@${{ matrix.typescript }} && npx tsc --version 102 | 103 | - name: Types 104 | run: npm run types 105 | 106 | size: 107 | needs: prepare 108 | if: github.event_name == 'pull_request' 109 | name: Size (${{ matrix.os}}, Node ${{ matrix.node }}) 110 | runs-on: ${{ matrix.os }} 111 | strategy: 112 | fail-fast: false 113 | matrix: 114 | os: [ubuntu-latest] 115 | node: [16] 116 | 117 | steps: 118 | - name: Set up Node 119 | uses: actions/setup-node@v3 120 | with: 121 | node-version: ${{ matrix.node }} 122 | 123 | - name: Checkout 124 | uses: actions/checkout@master 125 | 126 | - name: Retrieve node_modules 127 | uses: actions/cache@v3 128 | with: 129 | path: node_modules 130 | key: ${{ matrix.os }}-node-v${{ matrix.node }}-deps-${{ hashFiles(format('{0}{1}', github.workspace, '/package-lock.json')) }} 131 | 132 | - name: Size 133 | uses: andresz1/size-limit-action@v1 134 | with: 135 | github_token: ${{ secrets.GITHUB_TOKEN }} 136 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@prismicio/upgrade-from-legacy", 3 | "version": "0.0.3", 4 | "description": "A tool to ease upgrade to Slice Machine", 5 | "keywords": [ 6 | "typescript", 7 | "prismic" 8 | ], 9 | "repository": { 10 | "type": "git", 11 | "url": "ssh://git@github.com/prismicio/prismic-upgrade-from-legacy.git" 12 | }, 13 | "license": "Apache-2.0", 14 | "author": "Prismic (https://prismic.io)", 15 | "type": "module", 16 | "exports": { 17 | ".": { 18 | "require": { 19 | "types": "./dist/index.d.ts", 20 | "default": "./dist/index.cjs" 21 | }, 22 | "import": { 23 | "types": "./dist/index.d.ts", 24 | "default": "./dist/index.js" 25 | } 26 | }, 27 | "./cli": { 28 | "require": { 29 | "types": "./dist/cli.d.ts", 30 | "default": "./dist/cli.cjs" 31 | }, 32 | "import": { 33 | "types": "./dist/cli.d.ts", 34 | "default": "./dist/cli.js" 35 | } 36 | }, 37 | "./package.json": "./package.json" 38 | }, 39 | "main": "./dist/index.cjs", 40 | "module": "./dist/index.js", 41 | "types": "./dist/index.d.ts", 42 | "bin": { 43 | "prismic-upgrade-from-legacy": "./bin/prismic-upgrade-from-legacy.js" 44 | }, 45 | "files": [ 46 | "./bin", 47 | "./dist", 48 | "./src" 49 | ], 50 | "scripts": { 51 | "build": "npm run build:cli && npm run build:gui", 52 | "build:gui": "vite build gui", 53 | "build:cli": "vite build", 54 | "dev": "concurrently npm:dev:* --prefix-colors cyan,dim", 55 | "dev:gui": "vite gui", 56 | "dev:cli": "vite build --watch --mode development", 57 | "format": "prettier --write .", 58 | "prepare": "npm run build", 59 | "release": "npm run test && standard-version && git push --follow-tags && npm run build && npm publish", 60 | "release:dry": "standard-version --dry-run", 61 | "release:alpha": "npm run test && standard-version --release-as major --prerelease alpha && git push --follow-tags && npm run build && npm publish --tag alpha", 62 | "release:alpha:dry": "standard-version --release-as major --prerelease alpha --dry-run", 63 | "lint": "eslint --ext .js,.ts,.tsx .", 64 | "types": "vitest typecheck --run && tsc --noEmit", 65 | "types:watch": "vitest typecheck", 66 | "unit": "vitest run --coverage", 67 | "unit:watch": "vitest watch", 68 | "size": "size-limit", 69 | "test": "npm run lint && npm run types && npm run unit && npm run build && npm run size" 70 | }, 71 | "dependencies": { 72 | "@lihbr/listr-update-renderer": "^0.5.3", 73 | "@prismicio/types-internal": "^2.0.0", 74 | "@slicemachine/manager": "^0.10.0", 75 | "chalk": "^4.1.2", 76 | "cors": "^2.8.5", 77 | "express": "^4.18.2", 78 | "get-port-please": "^3.0.2", 79 | "http-proxy-middleware": "^2.0.6", 80 | "listr": "^0.14.3", 81 | "log-symbols": "^4.1.0", 82 | "meow": "^12.1.1", 83 | "open": "^8.4.2", 84 | "prompts": "^2.4.2", 85 | "serve-static": "^1.15.0" 86 | }, 87 | "devDependencies": { 88 | "@prismicio/editor-ui": "^0.4.9", 89 | "@size-limit/preset-small-lib": "^8.2.6", 90 | "@trivago/prettier-plugin-sort-imports": "^4.2.0", 91 | "@types/cors": "^2.8.14", 92 | "@types/express": "^4.17.17", 93 | "@types/listr": "0.14.5", 94 | "@types/nodemon": "^1.19.2", 95 | "@types/prompts": "2.4.4", 96 | "@types/react": "^18.2.21", 97 | "@types/react-dom": "^18.2.7", 98 | "@types/serve-static": "^1.15.2", 99 | "@typescript-eslint/eslint-plugin": "^6.6.0", 100 | "@typescript-eslint/parser": "^6.6.0", 101 | "@vitejs/plugin-react": "^4.0.4", 102 | "@vitest/coverage-v8": "^0.34.3", 103 | "autoprefixer": "^10.4.15", 104 | "clsx": "^2.0.0", 105 | "concurrently": "^8.2.1", 106 | "eslint": "^8.48.0", 107 | "eslint-config-prettier": "^9.0.0", 108 | "eslint-plugin-prettier": "^5.0.0", 109 | "eslint-plugin-react-hooks": "^4.6.0", 110 | "eslint-plugin-react-refresh": "^0.4.3", 111 | "eslint-plugin-tsdoc": "^0.2.17", 112 | "nodemon": "^3.0.1", 113 | "postcss": "^8.4.29", 114 | "prettier": "^3.0.3", 115 | "prettier-plugin-jsdoc": "^1.0.1", 116 | "react": "^18.2.0", 117 | "react-dom": "^18.2.0", 118 | "size-limit": "^8.2.6", 119 | "standard-version": "^9.5.0", 120 | "tailwindcss": "^3.3.3", 121 | "typescript": "^5.1.6", 122 | "vite": "^4.4.9", 123 | "vite-plugin-sdk": "^0.1.1", 124 | "vitest": "^0.34.3", 125 | "zustand": "^4.4.1" 126 | }, 127 | "engines": { 128 | "node": ">=14.15.0" 129 | }, 130 | "publishConfig": { 131 | "access": "public" 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /playground/app/page.module.css: -------------------------------------------------------------------------------- 1 | .main { 2 | display: flex; 3 | flex-direction: column; 4 | justify-content: space-between; 5 | align-items: center; 6 | padding: 6rem; 7 | min-height: 100vh; 8 | } 9 | 10 | .description { 11 | display: inherit; 12 | justify-content: inherit; 13 | align-items: inherit; 14 | font-size: 0.85rem; 15 | max-width: var(--max-width); 16 | width: 100%; 17 | z-index: 2; 18 | font-family: var(--font-mono); 19 | } 20 | 21 | .description a { 22 | display: flex; 23 | justify-content: center; 24 | align-items: center; 25 | gap: 0.5rem; 26 | } 27 | 28 | .description p { 29 | position: relative; 30 | margin: 0; 31 | padding: 1rem; 32 | background-color: rgba(var(--callout-rgb), 0.5); 33 | border: 1px solid rgba(var(--callout-border-rgb), 0.3); 34 | border-radius: var(--border-radius); 35 | } 36 | 37 | .code { 38 | font-weight: 700; 39 | font-family: var(--font-mono); 40 | } 41 | 42 | .grid { 43 | display: grid; 44 | grid-template-columns: repeat(4, minmax(25%, auto)); 45 | max-width: 100%; 46 | width: var(--max-width); 47 | } 48 | 49 | .card { 50 | padding: 1rem 1.2rem; 51 | border-radius: var(--border-radius); 52 | background: rgba(var(--card-rgb), 0); 53 | border: 1px solid rgba(var(--card-border-rgb), 0); 54 | transition: background 200ms, border 200ms; 55 | } 56 | 57 | .card span { 58 | display: inline-block; 59 | transition: transform 200ms; 60 | } 61 | 62 | .card h2 { 63 | font-weight: 600; 64 | margin-bottom: 0.7rem; 65 | } 66 | 67 | .card p { 68 | margin: 0; 69 | opacity: 0.6; 70 | font-size: 0.9rem; 71 | line-height: 1.5; 72 | max-width: 30ch; 73 | } 74 | 75 | .center { 76 | display: flex; 77 | justify-content: center; 78 | align-items: center; 79 | position: relative; 80 | padding: 4rem 0; 81 | } 82 | 83 | .center::before { 84 | background: var(--secondary-glow); 85 | border-radius: 50%; 86 | width: 480px; 87 | height: 360px; 88 | margin-left: -400px; 89 | } 90 | 91 | .center::after { 92 | background: var(--primary-glow); 93 | width: 240px; 94 | height: 180px; 95 | z-index: -1; 96 | } 97 | 98 | .center::before, 99 | .center::after { 100 | content: ''; 101 | left: 50%; 102 | position: absolute; 103 | filter: blur(45px); 104 | transform: translateZ(0); 105 | } 106 | 107 | .logo { 108 | position: relative; 109 | } 110 | /* Enable hover only on non-touch devices */ 111 | @media (hover: hover) and (pointer: fine) { 112 | .card:hover { 113 | background: rgba(var(--card-rgb), 0.1); 114 | border: 1px solid rgba(var(--card-border-rgb), 0.15); 115 | } 116 | 117 | .card:hover span { 118 | transform: translateX(4px); 119 | } 120 | } 121 | 122 | @media (prefers-reduced-motion) { 123 | .card:hover span { 124 | transform: none; 125 | } 126 | } 127 | 128 | /* Mobile */ 129 | @media (max-width: 700px) { 130 | .content { 131 | padding: 4rem; 132 | } 133 | 134 | .grid { 135 | grid-template-columns: 1fr; 136 | margin-bottom: 120px; 137 | max-width: 320px; 138 | text-align: center; 139 | } 140 | 141 | .card { 142 | padding: 1rem 2.5rem; 143 | } 144 | 145 | .card h2 { 146 | margin-bottom: 0.5rem; 147 | } 148 | 149 | .center { 150 | padding: 8rem 0 6rem; 151 | } 152 | 153 | .center::before { 154 | transform: none; 155 | height: 300px; 156 | } 157 | 158 | .description { 159 | font-size: 0.8rem; 160 | } 161 | 162 | .description a { 163 | padding: 1rem; 164 | } 165 | 166 | .description p, 167 | .description div { 168 | display: flex; 169 | justify-content: center; 170 | position: fixed; 171 | width: 100%; 172 | } 173 | 174 | .description p { 175 | align-items: center; 176 | inset: 0 0 auto; 177 | padding: 2rem 1rem 1.4rem; 178 | border-radius: 0; 179 | border: none; 180 | border-bottom: 1px solid rgba(var(--callout-border-rgb), 0.25); 181 | background: linear-gradient( 182 | to bottom, 183 | rgba(var(--background-start-rgb), 1), 184 | rgba(var(--callout-rgb), 0.5) 185 | ); 186 | background-clip: padding-box; 187 | backdrop-filter: blur(24px); 188 | } 189 | 190 | .description div { 191 | align-items: flex-end; 192 | pointer-events: none; 193 | inset: auto 0 0; 194 | padding: 2rem; 195 | height: 200px; 196 | background: linear-gradient( 197 | to bottom, 198 | transparent 0%, 199 | rgb(var(--background-end-rgb)) 40% 200 | ); 201 | z-index: 1; 202 | } 203 | } 204 | 205 | /* Tablet and Smaller Desktop */ 206 | @media (min-width: 701px) and (max-width: 1120px) { 207 | .grid { 208 | grid-template-columns: repeat(2, 50%); 209 | } 210 | } 211 | 212 | @media (prefers-color-scheme: dark) { 213 | .vercelLogo { 214 | filter: invert(1); 215 | } 216 | 217 | .logo { 218 | filter: invert(1) drop-shadow(0 0 0.3rem #ffffff70); 219 | } 220 | } 221 | 222 | @keyframes rotate { 223 | from { 224 | transform: rotate(360deg); 225 | } 226 | to { 227 | transform: rotate(0deg); 228 | } 229 | } 230 | -------------------------------------------------------------------------------- /gui/src/components/CustomTypeCard.tsx: -------------------------------------------------------------------------------- 1 | import { Button, Icon, Tooltip } from "@prismicio/editor-ui"; 2 | import { useMemo } from "react"; 3 | 4 | import { useSliceConflicts } from "../store/useSliceConflicts"; 5 | import { useSliceMachineConfig } from "../store/useSliceMachineConfig"; 6 | 7 | import { StatusDot } from "./StatusDot"; 8 | 9 | import { CompositeSlice } from "../../../src/models/CompositeSlice"; 10 | import { CustomType } from "../../../src/models/CustomType"; 11 | 12 | export function CustomTypeCard({ 13 | customType, 14 | }: { 15 | customType: CustomType; 16 | }): JSX.Element { 17 | const dashboard = useSliceMachineConfig((state) => state.dashboard); 18 | const conflicts = useSliceConflicts((state) => state.conflicts); 19 | 20 | const sliceZones = useMemo(() => { 21 | const sliceZoneMap: Record< 22 | string, 23 | { id: string; tabID: string; compositeSlices: CompositeSlice[] } 24 | > = {}; 25 | const compositeSlices = customType.getAllCompositeSlices(); 26 | 27 | for (const compositeSlice of compositeSlices) { 28 | sliceZoneMap[compositeSlice.meta.path.sliceZoneID] ||= { 29 | id: compositeSlice.meta.path.sliceZoneID, 30 | tabID: compositeSlice.meta.path.tabID, 31 | compositeSlices: [], 32 | }; 33 | sliceZoneMap[compositeSlice.meta.path.sliceZoneID].compositeSlices.push( 34 | compositeSlice, 35 | ); 36 | } 37 | 38 | return Object.values(sliceZoneMap); 39 | }, [customType]); 40 | 41 | const hasConflicts = useMemo(() => { 42 | return Object.values(conflicts ?? {}).some((slices) => { 43 | return slices.some((slice) => { 44 | return ( 45 | slice instanceof CompositeSlice && 46 | slice.meta.parent.id === customType.id 47 | ); 48 | }); 49 | }); 50 | }, [conflicts, customType]); 51 | 52 | return ( 53 |
54 |
55 |
56 |

57 | 58 | {customType.definition.label} 59 |

60 | 61 | ID: {customType.id} 62 | 63 |
64 | 75 |
76 |
77 |
78 |
    79 | {sliceZones.length ? ( 80 | sliceZones.map((sliceZone) => ( 81 |
  • 82 |
    83 |

    84 | 85 | {sliceZone.id} 86 |

    87 | 88 | {sliceZone.compositeSlices.length} legacy slice 89 | {sliceZone.compositeSlices.length > 1 ? "s" : ""} in this 90 | slice zone. 91 | 92 |
    93 |
      94 | {sliceZone.compositeSlices.map((compositeSlice) => ( 95 |
    • 99 |
      100 |
      101 | 110 | 111 | 120 | {compositeSlice.definition.fieldset} 121 | 122 | 123 |
      124 | 125 | ID:{" "} 126 | {compositeSlice.id} 127 | 128 |
      129 |
    • 130 | ))} 131 |
    132 |
  • 133 | )) 134 | ) : ( 135 |
  • 136 | 137 | No slice zone in this custom type. 138 | 139 |
  • 140 | )} 141 |
142 |
143 |
144 | ); 145 | } 146 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 12 | 13 | # @prismicio/upgrade-from-legacy 14 | 15 | [![npm version][npm-version-src]][npm-version-href] 16 | [![npm downloads][npm-downloads-src]][npm-downloads-href] 17 | [![Github Actions CI][github-actions-ci-src]][github-actions-ci-href] 18 | [![Codecov][codecov-src]][codecov-href] 19 | [![Conventional Commits][conventional-commits-src]][conventional-commits-href] 20 | [![License][license-src]][license-href] 21 | 22 | 23 | 24 | > ⚠  This project is in an experimental state. Use it at your own risk or stay tuned for the official release! 25 | 26 | A tool to ease upgrade to Slice Machine. 27 | 28 | 39 | 40 | ## Install 41 | 42 | ```bash 43 | npx @prismicio/upgrade-from-legacy@latest 44 | ``` 45 | 46 | ## Documentation 47 | 48 | To discover what's new on this package check out [the changelog][changelog]. For full documentation, visit the [official Prismic documentation][prismic-docs]. 49 | 50 | ## Contributing 51 | 52 | Whether you're helping us fix bugs, improve the docs, or spread the word, we'd love to have you as part of the Prismic developer community! 53 | 54 | **Asking a question**: [Open a new topic][forum-question] on our community forum explaining what you want to achieve / your question. Our support team will get back to you shortly. 55 | 56 | **Reporting a bug**: [Open an issue][repo-bug-report] explaining your application's setup and the bug you're encountering. 57 | 58 | **Suggesting an improvement**: [Open an issue][repo-feature-request] explaining your improvement or feature so we can discuss and learn more. 59 | 60 | **Submitting code changes**: For small fixes, feel free to [open a pull request][repo-pull-requests] with a description of your changes. For large changes, please first [open an issue][repo-feature-request] so we can discuss if and how the changes should be implemented. 61 | 62 | For more clarity on this project and its structure you can also check out the detailed [CONTRIBUTING.md][contributing] document. 63 | 64 | ## License 65 | 66 | ``` 67 | Copyright 2013-2023 Prismic (https://prismic.io) 68 | 69 | Licensed under the Apache License, Version 2.0 (the "License"); 70 | you may not use this file except in compliance with the License. 71 | You may obtain a copy of the License at 72 | 73 | http://www.apache.org/licenses/LICENSE-2.0 74 | 75 | Unless required by applicable law or agreed to in writing, software 76 | distributed under the License is distributed on an "AS IS" BASIS, 77 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 78 | See the License for the specific language governing permissions and 79 | limitations under the License. 80 | ``` 81 | 82 | 83 | 84 | [prismic]: https://prismic.io 85 | 86 | 87 | 88 | [prismic-docs]: https://prismic.io/docs 89 | [changelog]: ./CHANGELOG.md 90 | [contributing]: ./CONTRIBUTING.md 91 | 92 | 93 | 94 | [forum-question]: https://community.prismic.io 95 | [repo-bug-report]: https://github.com/prismicio/prismic-upgrade-from-legacy/issues/new?assignees=&labels=bug&template=bug_report.md&title= 96 | [repo-feature-request]: https://github.com/prismicio/prismic-upgrade-from-legacy/issues/new?assignees=&labels=enhancement&template=feature_request.md&title= 97 | [repo-pull-requests]: https://github.com/prismicio/prismic-upgrade-from-legacy/pulls 98 | 99 | 100 | 101 | [npm-version-src]: https://img.shields.io/npm/v/@prismicio/upgrade-from-legacy/latest.svg 102 | [npm-version-href]: https://npmjs.com/package/@prismicio/upgrade-from-legacy 103 | [npm-downloads-src]: https://img.shields.io/npm/dm/@prismicio/upgrade-from-legacy.svg 104 | [npm-downloads-href]: https://npmjs.com/package/@prismicio/upgrade-from-legacy 105 | [github-actions-ci-src]: https://github.com/prismicio/prismic-upgrade-from-legacy/workflows/ci/badge.svg 106 | [github-actions-ci-href]: https://github.com/prismicio/prismic-upgrade-from-legacy/actions?query=workflow%3Aci 107 | [codecov-src]: https://img.shields.io/codecov/c/github/prismicio/prismic-upgrade-from-legacy.svg 108 | [codecov-href]: https://codecov.io/gh/prismicio/prismic-upgrade-from-legacy 109 | [conventional-commits-src]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-%23FE5196?logo=conventionalcommits&logoColor=white 110 | [conventional-commits-href]: https://conventionalcommits.org 111 | [license-src]: https://img.shields.io/npm/l/@prismicio/upgrade-from-legacy.svg 112 | [license-href]: https://npmjs.com/package/@prismicio/upgrade-from-legacy 113 | -------------------------------------------------------------------------------- /.github/prismic-oss-ecosystem.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /src/UpgradeProcess.ts: -------------------------------------------------------------------------------- 1 | import { 2 | PrismicUserProfile, 3 | SliceMachineConfig, 4 | SliceMachineManager, 5 | createSliceMachineManager, 6 | } from "@slicemachine/manager"; 7 | import chalk from "chalk"; 8 | import { Express } from "express"; 9 | import { getPort } from "get-port-please"; 10 | import logSymbols from "log-symbols"; 11 | import open from "open"; 12 | 13 | import { ExplainedError } from "./lib/ExplainedError"; 14 | import { assertExists } from "./lib/assertExists"; 15 | import { createUpgradeExpressApp } from "./lib/createUpgradeExpressApp"; 16 | import { listr, listrRun } from "./lib/listr"; 17 | 18 | import { CompositeSlice } from "./models/CompositeSlice"; 19 | import { CustomType } from "./models/CustomType"; 20 | import { SharedSlice } from "./models/SharedSlice"; 21 | import { 22 | SliceConflicts, 23 | checkSliceConflicts, 24 | } from "./models/checkSliceConflicts"; 25 | import { findDuplicatedSlices } from "./models/findDuplicatedSlices"; 26 | 27 | export type UpgradeProcessOptions = { 28 | cwd?: string; 29 | open?: boolean; 30 | } & Record; 31 | 32 | const DEFAULT_OPTIONS: UpgradeProcessOptions = {}; 33 | 34 | export const createUpgradeProcess = ( 35 | options?: UpgradeProcessOptions, 36 | ): UpgradeProcess => { 37 | return new UpgradeProcess(options); 38 | }; 39 | 40 | type UpgradeProcessContext = { 41 | gui?: { 42 | app?: Express; 43 | port?: number; 44 | }; 45 | config?: SliceMachineConfig; 46 | userProfile?: PrismicUserProfile; 47 | repository?: { 48 | customTypes?: CustomType[]; 49 | sharedSlices?: SharedSlice[]; 50 | compositeSlices?: CompositeSlice[]; 51 | }; 52 | conflicts?: SliceConflicts; 53 | }; 54 | 55 | export class UpgradeProcess { 56 | protected options: UpgradeProcessOptions; 57 | protected manager: SliceMachineManager; 58 | 59 | protected context: UpgradeProcessContext; 60 | 61 | constructor(options?: UpgradeProcessOptions) { 62 | this.options = { ...DEFAULT_OPTIONS, ...options }; 63 | this.manager = createSliceMachineManager({ cwd: options?.cwd }); 64 | 65 | this.context = {}; 66 | } 67 | 68 | async check(): Promise { 69 | this.report("Check command started"); 70 | 71 | await this.ensureSliceMachineProject(); 72 | await this.loginAndFetchUserData(); 73 | await this.fetchRepository(); 74 | await this.searchCompositeSlices(); 75 | await this.checkSliceConflicts(); 76 | 77 | assertExists( 78 | this.context.conflicts, 79 | "Conflicts must be available through context to proceed", 80 | ); 81 | 82 | if (Object.keys(this.context.conflicts).length) { 83 | // We prefer to manually allow console logs despite the app being a CLI to catch wild/unwanted console logs better 84 | // eslint-disable-next-line no-console 85 | console.log(`\n${this.formatConflicts()}`); 86 | } 87 | 88 | this.report("Check command successful!"); 89 | 90 | const output = []; 91 | if (Object.keys(this.context.conflicts).length) { 92 | output.push( 93 | ` Your project ${chalk.cyan( 94 | "has conflicting slice IDs", 95 | )}, see details above.`, 96 | " You won't be able to upgrade yet.", 97 | ); 98 | } else { 99 | output.push( 100 | ` Your project is ${chalk.cyan("conflict-free")}!`, 101 | " You will be able to upgrade soon.", 102 | ); 103 | } 104 | 105 | output.push( 106 | "", 107 | " Stay tuned for more information about the upgrade project:", 108 | " - Newsletter: https://prismic.dev/upgrade/newsletter", 109 | " - Twitter/X: https://twitter.com/prismicio", 110 | ); 111 | 112 | // We prefer to manually allow console logs despite the app being a CLI to catch wild/unwanted console logs better 113 | // eslint-disable-next-line no-console 114 | console.log(output.join("\n")); 115 | } 116 | 117 | async migrate(): Promise { 118 | this.report("Migrate command started"); 119 | 120 | await this.ensureSliceMachineProject(); 121 | await this.loginAndFetchUserData(); 122 | await this.fetchRepository(); 123 | await this.searchCompositeSlices(); 124 | await this.checkSliceConflicts(); 125 | 126 | assertExists( 127 | this.context.conflicts, 128 | "Conflicts must be available through context to proceed", 129 | ); 130 | 131 | if (Object.keys(this.context.conflicts).length) { 132 | throw new ExplainedError( 133 | `\n${ 134 | logSymbols.error 135 | } Cannot migrate a project with conflicts.\n\n Run ${chalk.cyan( 136 | "npx @prismicio/upgrade-from-legacy check", 137 | )} for more details.`, 138 | ); 139 | } 140 | 141 | await this.migrateCompositeSlices(); 142 | await this.upsertCustomTypes(); 143 | 144 | this.report("Migrate command successful!"); 145 | } 146 | 147 | async gui(): Promise { 148 | this.report("GUI command started"); 149 | 150 | await this.ensureSliceMachineProject(); 151 | await this.loginAndFetchUserData(); 152 | await this.startGUI(); 153 | 154 | if (this.options.open) { 155 | assertExists( 156 | this.context.gui?.port, 157 | "GUI port must be available through context to proceed", 158 | ); 159 | 160 | await open(`http://localhost:${this.context.gui.port}`); 161 | } 162 | } 163 | 164 | protected report(message: string): void { 165 | // We prefer to manually allow console logs despite the app being a CLI to catch wild/unwanted console logs better 166 | // eslint-disable-next-line no-console 167 | console.log( 168 | `\n${chalk.bgCyan(` ${chalk.bold.white("Prismic")} `)} ${chalk.dim( 169 | "→", 170 | )} ${message}\n`, 171 | ); 172 | } 173 | 174 | protected async ensureSliceMachineProject(): Promise { 175 | try { 176 | this.context.config = await this.manager.project.getSliceMachineConfig(); 177 | 178 | // We prefer to manually allow console logs despite the app being a CLI to catch wild/unwanted console logs better 179 | // eslint-disable-next-line no-console 180 | console.log( 181 | `${logSymbols.success} Working with repository ${chalk.cyan( 182 | this.context.config.repositoryName, 183 | )}`, 184 | ); 185 | } catch (error) { 186 | throw new ExplainedError( 187 | `${logSymbols.error} Cannot run ${chalk.cyan( 188 | "@prismicio/upgrade-from-legacy", 189 | )} outside of a Slice Machine project.\n\n Run ${chalk.cyan( 190 | "npx @slicemachine/init@latest", 191 | )} first or make sure you're in the right directory.`, 192 | error instanceof Error ? { cause: error } : {}, 193 | ); 194 | } 195 | 196 | await this.manager.plugins.initPlugins(); 197 | } 198 | 199 | protected async loginAndFetchUserData(): Promise { 200 | return listrRun([ 201 | { 202 | title: "Logging in to Prismic...", 203 | task: async (_, parentTask) => { 204 | parentTask.output = "Validating session..."; 205 | const isLoggedIn = await this.manager.user.checkIsLoggedIn(); 206 | 207 | if (!isLoggedIn) { 208 | parentTask.output = "Press any key to open the browser to login..."; 209 | await new Promise((resolve) => { 210 | const initialRawMode = !!process.stdin.isRaw; 211 | process.stdin.setRawMode?.(true); 212 | process.stdin.once("data", (data: Buffer) => { 213 | process.stdin.setRawMode?.(initialRawMode); 214 | process.stdin.pause(); 215 | resolve(data.toString("utf-8")); 216 | }); 217 | }); 218 | 219 | parentTask.output = "Browser opened, waiting for you to login..."; 220 | const { port, url } = await this.manager.user.getLoginSessionInfo(); 221 | await this.manager.user.nodeLoginSession({ 222 | port, 223 | onListenCallback() { 224 | open(url); 225 | }, 226 | }); 227 | } 228 | 229 | parentTask.output = ""; 230 | parentTask.title = `Logged in`; 231 | 232 | return listr( 233 | [ 234 | { 235 | title: "Fetching user profile...", 236 | task: async (_, task) => { 237 | this.context.userProfile = 238 | await this.manager.user.getProfile(); 239 | 240 | parentTask.title = `Logged in as ${chalk.cyan( 241 | this.context.userProfile?.email, 242 | )}`; 243 | task.title = "Fetched user profile"; 244 | }, 245 | }, 246 | ], 247 | { concurrent: true }, 248 | ); 249 | }, 250 | }, 251 | ]); 252 | } 253 | 254 | protected async fetchRepository(): Promise { 255 | return listrRun([ 256 | { 257 | title: `Fetching ${chalk.cyan( 258 | this.context.config?.repositoryName, 259 | )} repository...`, 260 | task: async (_, parentTask) => { 261 | return listr( 262 | [ 263 | { 264 | title: "Fetching custom types...", 265 | task: async (_, task) => { 266 | const customTypeDefinitions = 267 | await this.manager.customTypes.fetchRemoteCustomTypes(); 268 | 269 | this.context.repository ||= {}; 270 | this.context.repository.customTypes = 271 | customTypeDefinitions.map( 272 | (customTypeDefinition) => 273 | new CustomType(customTypeDefinition), 274 | ); 275 | 276 | task.title = `Fetched ${chalk.cyan( 277 | this.context.repository.customTypes.length, 278 | )} custom type${ 279 | this.context.repository.customTypes.length > 1 ? "s" : "" 280 | }`; 281 | if (this.context.repository.sharedSlices) { 282 | parentTask.title = `Fetched ${chalk.cyan( 283 | this.context.repository.customTypes.length, 284 | )} custom type${ 285 | this.context.repository.customTypes.length > 1 ? "s" : "" 286 | } and ${chalk.cyan( 287 | this.context.repository.sharedSlices.length, 288 | )} shared slice${ 289 | this.context.repository.sharedSlices.length > 1 ? "s" : "" 290 | } from repository`; 291 | } 292 | }, 293 | }, 294 | { 295 | title: "Fetching shared slices...", 296 | task: async (_, task) => { 297 | const sharedSliceDefinitions = 298 | await this.manager.slices.fetchRemoteSlices(); 299 | 300 | this.context.repository ||= {}; 301 | this.context.repository.sharedSlices = 302 | sharedSliceDefinitions.map( 303 | (sharedSliceDefinition) => 304 | new SharedSlice(sharedSliceDefinition), 305 | ); 306 | 307 | task.title = `Fetched ${chalk.cyan( 308 | this.context.repository.sharedSlices.length, 309 | )} shared slice${ 310 | this.context.repository.sharedSlices.length > 1 ? "s" : "" 311 | }`; 312 | if (this.context.repository.customTypes) { 313 | parentTask.title = `Fetched ${chalk.cyan( 314 | this.context.repository.customTypes.length, 315 | )} custom type${ 316 | this.context.repository.customTypes.length > 1 ? "s" : "" 317 | } and ${chalk.cyan( 318 | this.context.repository.sharedSlices.length, 319 | )} shared slice${ 320 | this.context.repository.sharedSlices.length > 1 ? "s" : "" 321 | } from repository`; 322 | } 323 | }, 324 | }, 325 | ], 326 | { concurrent: true }, 327 | ); 328 | }, 329 | }, 330 | ]); 331 | } 332 | 333 | protected async searchCompositeSlices(): Promise { 334 | return listrRun([ 335 | { 336 | title: "Searching composite slices...", 337 | task: (_, task) => { 338 | assertExists( 339 | this.context.repository?.customTypes, 340 | "Repository Custom Types must be available through context to proceed", 341 | ); 342 | 343 | this.context.repository.compositeSlices = []; 344 | 345 | for (const customType of this.context.repository.customTypes) { 346 | this.context.repository.compositeSlices.push( 347 | ...customType.getAllCompositeSlices(), 348 | ); 349 | } 350 | 351 | task.title = `Found ${chalk.cyan( 352 | this.context.repository.compositeSlices.length, 353 | )} composite slices`; 354 | }, 355 | }, 356 | ]); 357 | } 358 | 359 | protected async checkSliceConflicts(): Promise { 360 | return listrRun([ 361 | { 362 | title: "Checking conflicts...", 363 | task: (_, task) => { 364 | assertExists( 365 | this.context.repository?.sharedSlices, 366 | "Repository Shared Slices must be available through context to proceed", 367 | ); 368 | assertExists( 369 | this.context.repository?.compositeSlices, 370 | "Repository Composite Slices (legacy) must be available through context to proceed", 371 | ); 372 | 373 | this.context.conflicts = checkSliceConflicts([ 374 | ...this.context.repository.sharedSlices, 375 | ...this.context.repository.compositeSlices, 376 | ]); 377 | 378 | const conflictsLength = Object.keys(this.context.conflicts).length; 379 | if (conflictsLength) { 380 | task.title = `Found ${chalk.cyan(conflictsLength)} conflict${ 381 | conflictsLength > 1 ? "s" : "" 382 | }`; 383 | } else { 384 | task.title = `Found no conflict`; 385 | } 386 | }, 387 | }, 388 | ]); 389 | } 390 | 391 | protected formatConflicts(): string { 392 | assertExists( 393 | this.context.conflicts, 394 | "Conflicts must be available through context to proceed", 395 | ); 396 | 397 | const output: string[] = []; 398 | 399 | output.push( 400 | ` ${chalk.dim("(shared slice)")} ${chalk.cyan( 401 | "", 402 | )} ${chalk.dim("(maybe-suffix)")}\n ${chalk.dim( 403 | "(composite slice)", 404 | )} ${chalk.dim("::::::")}${chalk.cyan( 405 | "", 406 | )} ${chalk.dim("(maybe-suffix)")}`, 407 | ); 408 | 409 | for (const id in this.context.conflicts) { 410 | const conflict = this.context.conflicts[id]; 411 | 412 | output.push( 413 | `\n\n ${logSymbols.error} ${chalk.cyan(id)} is conflicting:\n`, 414 | ); 415 | 416 | const duplicatedSlices = findDuplicatedSlices(conflict); 417 | const allDuplicated = 418 | duplicatedSlices.length === 1 && 419 | duplicatedSlices[0].length === conflict.length; 420 | 421 | for (const slice of conflict) { 422 | const maybeIndex = 423 | duplicatedSlices.findIndex((slices) => slices.includes(slice)) + 1; 424 | 425 | const suffix = maybeIndex 426 | ? ` ${chalk.hsl(maybeIndex * 45, 50, 50)(`(d${maybeIndex})`)}` 427 | : ""; 428 | if (slice instanceof SharedSlice) { 429 | output.push( 430 | ` ${chalk.dim("(shared slice)")} ${chalk.cyan( 431 | slice.id, 432 | )}${suffix}`, 433 | ); 434 | } else { 435 | output.push( 436 | ` ${chalk.dim("(composite slice)")} ${chalk.dim( 437 | `${slice.meta.parent.id}::${slice.meta.path.tabID}::${slice.meta.path.sliceZoneID}::`, 438 | )}${chalk.cyan(slice.id)}${suffix}`, 439 | ); 440 | } 441 | } 442 | 443 | if (allDuplicated) { 444 | output.push(`\n ${chalk.dim("All slices are identical!")}`); 445 | } else if (duplicatedSlices.length) { 446 | output.push( 447 | `\n ${chalk.dim( 448 | `(d${chalk.italic( 449 | duplicatedSlices.length === 1 450 | ? "1" 451 | : `1-${duplicatedSlices.length}`, 452 | )}) suffixed slices are identical to slices with the same suffix`, 453 | )}`, 454 | ); 455 | } 456 | } 457 | 458 | return output.join("\n"); 459 | } 460 | 461 | protected async migrateCompositeSlices(): Promise { 462 | return listrRun([ 463 | { 464 | title: `Migrating ${chalk.cyan( 465 | this.context.repository?.compositeSlices?.length, 466 | )} composite slices...`, 467 | task: async (_, task) => { 468 | assertExists( 469 | this.context.config, 470 | "Config must be available through context to proceed", 471 | ); 472 | assertExists( 473 | this.context.repository?.compositeSlices, 474 | "Repository Composite Slices (legacy) must be available through context to proceed", 475 | ); 476 | 477 | // TODO: This needs to be more flexible 478 | const libraryID = this.context.config.libraries?.[0] ?? "./slices"; 479 | 480 | await Promise.all( 481 | this.context.repository.compositeSlices.map( 482 | async (compositeSlice) => { 483 | const sharedSlice = 484 | SharedSlice.fromCompositeSlice(compositeSlice); 485 | const { errors } = await this.manager.slices.createSlice({ 486 | libraryID, 487 | model: sharedSlice.definition, 488 | }); 489 | 490 | if (errors.length) { 491 | throw errors; 492 | } 493 | 494 | compositeSlice.meta.parent.updateSliceInSliceZone( 495 | { 496 | type: "SharedSlice", 497 | }, 498 | compositeSlice.meta.path, 499 | ); 500 | }, 501 | ), 502 | ); 503 | 504 | task.title = `Migrated ${chalk.cyan( 505 | this.context.repository.compositeSlices.length, 506 | )} composite slices as shared slices`; 507 | }, 508 | }, 509 | ]); 510 | } 511 | 512 | protected async upsertCustomTypes(): Promise { 513 | return listrRun([ 514 | { 515 | title: `Upserting ${chalk.cyan( 516 | this.context.repository?.customTypes?.length, 517 | )} custom types...`, 518 | task: async (_, task) => { 519 | assertExists( 520 | this.context.config, 521 | "Config must be available through context to proceed", 522 | ); 523 | assertExists( 524 | this.context.repository?.customTypes, 525 | "Repository Custom Types must be available through context to proceed", 526 | ); 527 | 528 | await Promise.all( 529 | this.context.repository.customTypes.map(async (customType) => { 530 | // TODO: Need to handle existing custom type perhaps(?) 531 | const { errors } = 532 | await this.manager.customTypes.createCustomType({ 533 | model: customType.definition, 534 | }); 535 | 536 | if (errors.length) { 537 | throw errors; 538 | } 539 | }), 540 | ); 541 | 542 | task.title = `Upserted ${chalk.cyan( 543 | this.context.repository.customTypes.length, 544 | )} custom types`; 545 | }, 546 | }, 547 | ]); 548 | } 549 | 550 | protected async startGUI(): Promise { 551 | return listrRun([ 552 | { 553 | title: "Starting GUI...", 554 | task: async (_, task) => { 555 | task.output = "Finding port..."; 556 | 557 | const port = await getPort({ port: 8888 }); 558 | 559 | task.output = "Starting server..."; 560 | 561 | const app = createUpgradeExpressApp({ 562 | sliceMachineManager: this.manager, 563 | }); 564 | 565 | await new Promise((resolve) => { 566 | app.listen(port, () => { 567 | resolve(); 568 | }); 569 | }); 570 | 571 | this.context.gui ||= {}; 572 | this.context.gui.port = port; 573 | this.context.gui.app = app; 574 | 575 | task.output = ""; 576 | task.title = `GUI started! Available at ${chalk.cyan( 577 | `http://localhost:${this.context.gui.port}`, 578 | )} ${import.meta.env.MODE === "development" ? "(proxying)" : ""}`; 579 | }, 580 | }, 581 | ]); 582 | } 583 | } 584 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Prismic 2 | 3 | This document is aimed at providing developers (mainly maintainers) documentation on this project and its structure. It is not intended to pass requirements for contributing to this project. 4 | 5 | For the latter, the [Quick Start](#quick-start) section below can help you. You are free to [open issues][repo-issue] and [submit pull requests][repo-pull-requests] toward the `master` branch directly without worrying about our standards. For pull requests, we will help you through our merging process. 6 | 7 | > For a Table of Contents, use GitHub's TOC button, top left of the document. 8 | 9 | ## Quick Start 10 | 11 | ```bash 12 | # First, fork the repository to your GitHub account if you aren't an existing maintainer 13 | 14 | # Clone your fork 15 | git clone git@github.com:/prismic-upgrade-from-legacy.git 16 | 17 | # Create a feature branch with your initials and feature name 18 | git checkout -b / # e.g. `lh/fix-win32-paths` 19 | 20 | # Install dependencies with npm 21 | npm install 22 | 23 | # Test your changes 24 | npm run test 25 | 26 | # Commit your changes once they are ready 27 | # Conventional Commits are encouraged, but not required 28 | git add . 29 | git commit -m "short description of your changes" 30 | 31 | # Lastly, open a pull request on GitHub describing your changes 32 | ``` 33 | 34 | ## Processes 35 | 36 | Processes refer to tasks that you may need to perform while working on this project. 37 | 38 | ### Developing 39 | 40 | There is no development branch. The `master` branch refers to the latest [stable (living) version](#stable-xxx) of the project and pull requests should be made against it. 41 | 42 | If development on a [new major version](#iteration-cycle) has begun, a branch named after the major version will be created (e.g. `v2` for work on the future `v2.0.0` of the project). Pull requests targeting that new major version should be made against it. 43 | 44 | To develop locally: 45 | 46 | 1. **If you have maintainer access**:
[Clone the repository](https://help.github.com/articles/cloning-a-repository) to your local environment. 47 | 48 | **If you do no have maintainer access**:
[Fork](https://help.github.com/articles/fork-a-repo) and [clone](https://help.github.com/articles/cloning-a-repository) the repository to your local environment. 49 | 50 | 2. Create a new branch: 51 | 52 | ```bash 53 | git checkout -b / # e.g. `aa/graphql-support` 54 | ``` 55 | 56 | 3. Install dependencies with [npm][npm] (avoid using [Yarn][yarn]): 57 | 58 | ```bash 59 | npm install 60 | ``` 61 | 62 | 4. Start developing: 63 | 64 | ```bash 65 | npm run dev 66 | ``` 67 | 68 | 5. Commit your changes: 69 | 70 | If you already know the [Conventional Commits convention][conventional-commits], feel free to embrace it for your commit messages. If you don't, no worries; it can always be taken care of when the pull request is merged. 71 | 72 | ### Building 73 | 74 | Our build system is handled by [Vite][vite]. Vite takes care of: 75 | 76 | - Generating a [CommonJS (`.cjs`)](https://nodejs.org/docs/latest/api/modules.html#modules_modules_commonjs_modules) bundle and its source map; 77 | - Generating an [ECMAScript (`.mjs`)](https://nodejs.org/docs/latest/api/modules.html#modules_modules_commonjs_modules) bundle and its source map; 78 | - Generating a TypeScript declaration (`.d.ts`) file. 79 | 80 | To build the project: 81 | 82 | ```bash 83 | npm run build 84 | ``` 85 | 86 | The CI system will try to build the project on each commit targeting the `master` branch. The CI check will fail if the build does. 87 | 88 | ### Testing 89 | 90 | All projects have at least linting and unit tests. Linting is handled by [ESLint][eslint] with [Prettier][prettier] and unit tests are handled by [Vitest][vitest]. 91 | 92 | To run all tests: 93 | 94 | ```bash 95 | npm run test 96 | ``` 97 | 98 | If you'd like to run only the linter (note that it won't reformat your code; use the `format` script for that): 99 | 100 | ```bash 101 | npm run lint 102 | ``` 103 | 104 | If you'd like to run only the unit tests: 105 | 106 | ```bash 107 | npm run unit 108 | ``` 109 | 110 | If you'd like to run only the unit tests in watch mode (re-runs tests each time a file is saved): 111 | 112 | ```bash 113 | npm run unit:watch 114 | ``` 115 | 116 | When working on unit tests, you might want to update snapshots (be careful when doing so): 117 | 118 | ```bash 119 | npm run unit -- --update-snapshots 120 | ``` 121 | 122 | The CI system will run tests on each commit targeting the `master` branch. The CI check will fail if any test does. 123 | 124 | ### Publishing 125 | 126 | > ⚠  Only project maintainers with at least collaborator access to the related npm package can publish new versions. 127 | 128 | Publishing a package correctly involves multiple steps: 129 | 130 | - Writing a changelog; 131 | - [Building](#building) the project; 132 | - Publishing a new version tag to GitHub; 133 | - Publishing build artifacts to [npm][npm]. 134 | 135 | In order to make sure all these steps are consistently and correctly done, we use [Standard Version][standard-version] and build scripts. 136 | 137 | To release a new version of the project: 138 | 139 | ```bash 140 | npm run release 141 | ``` 142 | 143 | To release a new [alpha](#alpha-xxx-alphax) version of the project: 144 | 145 | ```bash 146 | npm run release:alpha 147 | ``` 148 | 149 | Those scripts will: 150 | 151 | - Run tests and try to build the project; 152 | - Figure out the new version number by looking at commit messages matching the [Conventional Commits convention][conventional-commits]; 153 | - Write the [changelog][changelog] for the new version after Conventional Commit messages; 154 | - Build the project for publishing; 155 | - Publish a new version tag to GitHub; 156 | - Publish build artifacts to [npm][npm]. 157 | 158 | Once a script has been run successfully, a new version of the package should have been published to npm. To complete the publishing process you only need to head to the repository's releases tab on GitHub to publish the new version tag that was created. 159 | 160 | If you ran any of those commands but happen not to have access to the related npm package, you can still ask a collaborator of the said package to publish it for you. 161 | 162 | Appending `:dry` (e.g. `release:dry`) to any of the above commands will dry-run the targeted release script and output the new changelog to the console. 163 | 164 | We consider maintaining project dependencies before publishing a new version a best practice. 165 | 166 | ### Maintaining 167 | 168 | Anyone can, and is welcome to, contribute to the project by opening bug reports and submitting feature requests. To remain focused and ensure we are able to respond to each contribution, we have adopted the following framework to maintain this package: 169 | 170 | **🚨  Bug reports** 171 | 172 | > **Note**: An automated reply is posted when a bug report is opened to explain our maintenance schedule. 173 | 174 | Every Wednesday is _bug squashing day_. During this day, we respond to and/or fix bug reports. 175 | 176 | At the end of each Wednesday (assuming there were issues to fix), or later during the week if reviews are required, a _patch_ version is [released](#publishing) containing any fixes that were needed. Releasing multiple patches during the same week should be avoided. 177 | 178 | Ideally, all opened bug reports are addressed each Wednesday. If a particular bug report is not able to be resolved in that timeframe, maintainers are free to continue working on the issue or to report back to it next Wednesday. Overall, while most issues should be closed within _7 days_, we consider up to _14 days_ to get back to and address an issue a reasonable delay. Beyond that threshold, an issue is considered problematic and will be given more attention. 179 | 180 | **🙋‍♀️  Feature requests** 181 | 182 | > **Note**: An automated message gets sent to people creating feature requests about this process. 183 | 184 | Every last week of a month is _feature week_. During this week, we implement new features. Discussing and coming up with implementation proposals can happen before that week, but implementations are targeted for the last week. 185 | 186 | At the end of the week (assuming there were features to implement), a _minor_ version is [released](#publishing) containing the new features. Releasing multiple minors during the same week should be avoided. 187 | 188 | Ideally, all opened feature requests are discussed each month and implemented if consensus was reached. Unlike bug reports, we do not consider delays to address feature requests as good or bad. Instead, those should essentially be driven by the community's demand on a per-request basis. 189 | 190 | **🏗  Updating the project structure** 191 | 192 | We actively maintain a [TypeScript template][template] with Prismic's latest open-source standards. Keeping every project in sync with this template is nearly impossible so we're not trying to immediately reflect changes to the template in every project. Instead we consider a best practice to manually pull changes from the template into the project whenever someone is doing project maintenance and has time for it, or wants to enjoy the latest standards from it. 193 | 194 | ## `@prismicio/upgrade-from-legacy` in Prismic's Open-Source Ecosystem 195 | 196 | Prismic's Open-Source ecosystem is built around a 3-stage pyramid: 197 | 198 |

199 | Prismic open-source pyramid 200 |

201 | 202 | Where: 203 | 204 | - **Core**: Represents libraries providing core Prismic integration such as data fetching and content transformation, e.g. [`@prismicio/client`](https://github.com/prismicio/prismic-client); 205 | - **Integration**: Represents libraries to integration into UI libraries. They must be framework agnostic, e.g. [`@prismicio/react`](https://github.com/prismicio/prismic-react); 206 | - **Framework**: Represents libraries to integrate into frameworks, including data fetching and normalizing. They must follow frameworks' expected practices, e.g. [`@prismicio/next`](https://github.com/prismicio/prismic-next). 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | ## Iteration Cycle 215 | 216 | We break iteration cycle of a project's library into 4 phases: 217 | 218 | - **Pre-alpha** 219 | - **Alpha** 220 | - **Beta** 221 | - **Stable** 222 | 223 | ### Pre-alpha 224 | 225 | > At any point we might feel the need to introduce breaking changes to a project's library (getting rid of legacy APIs, embracing latest features from a framework, etc.). When such a need has been identified for a project, it will enter the pre-alpha phase. The project might also enter the pre-alpha phase for large, non-breaking changes that need more planning and thoughts. 226 | > 227 | > The goal of the pre-alpha phase is to design and share the new project's library API through an RFC. Under certain circumstances (e.g. the API has already been clearly defined in another language and only some adaptations have to be made), the project can skip the pre-alpha phase and enter the alpha phase directly. Skipping the pre-alpha phase should be treated as an exception. 228 | 229 | During the pre-alpha phase, the following will happen: 230 | 231 | **Documenting and understanding the library's current functionality:** 232 | 233 | Doing so leads to a better understanding of the library's current functionality and limitations. Reviewing GitHub Issues will provide insight into existing bugs and user requests. We want to reduce the number of breaking changes where possible while not being afraid to do so if necessary. 234 | 235 | **Sketching the API in code, examples, and written explanations:** 236 | 237 | The library should be written in concept before its concrete implementation. This frees us from technical limitations and implementation details. It also allows us to craft the best feeling API. 238 | 239 | **Writing the public RFC:** 240 | 241 | A formal RFC should be posted publicly once the initial brainstorming session is complete that focuses on new and changed concepts. This allows everyone to read and voice their opinions should they choose to. 242 | 243 | ### Alpha (`x.x.x-alpha.x`) 244 | 245 | > As soon as the RFC has been posted, the project enters the alpha phase. 246 | > 247 | > The goal of the alpha phase is to implement the new project's library API, to test it, and to document it. 248 | 249 | During the alpha phase, the following will happen: 250 | 251 | **Writing the implementation:** 252 | 253 | The implementation must be done in TypeScript and include extensive tests and in-code documentation. Generally the process goes as follows: 254 | 255 | 1. Writing the implementation in TypeScript; 256 | 2. Testing the implementation; 257 | 3. Documenting the implementation with TSDocs (at least all publicly exported APIs). 258 | 259 | **Publishing public alpha versions:** 260 | 261 | Publishing alpha versions of the library allows for easier internal testing. With alpha versions, users can test the library as it is published publicly, however those versions are not recommended or shared extensively as breaking changes are still very likely to occur and the library is still not documented. Alpha versions can be published as often as needed. 262 | 263 | **Adjusting per internal and external feedback:** 264 | 265 | An internal code review should be performed. As users use the alpha, issues will be opened for bugs and suggestions. Appropriate adjustments to the library should be made with a focus on doing what users expect while minimizing technical debt. For that purpose, breaking changes to the new API can be introduced. 266 | 267 | **Updating documentation:** 268 | 269 | Documentation for the library should be updated on [prismic.io][prismic-docs] and is treated as the primary source of documentation. Contributors will work closely with Prismic Education team to complete this. This involves updating related documentation and code examples as well, including any starter projects on GitHub. A migration guide should be included if necessary. 270 | 271 | ### Beta (`x.x.x-beta.x`) 272 | 273 | > As soon as the implementation is completed and the updated documentation is ready to be published, the project enters the beta phase. 274 | > 275 | > The goal of the beta phase is to test the updated library's API by publicly sharing it with the community and receiving early adopters' feedback. The beta phase is the last opportunity for breaking changes to be introduced. 276 | 277 | During the beta phase, the following will happen: 278 | 279 | **Publishing public beta versions and related documentation:** 280 | 281 | A first beta should be published along the related documentation that has been worked on during the alpha phase. This release should be announced and shared to users in order to get feedback from early adopters. Subsequent beta versions can be published as often as needed, but we have to keep in mind users are now expected to be using them. 282 | 283 | **Adjusting per internal and external feedback:** 284 | 285 | As users use the beta, issues will be opened for bugs and suggestions. Appropriate adjustments to the library should be made with a focus on doing what users expect while minimizing technical debt. For that purpose, breaking changes to the new API can still be introduced and documentation should be updated accordingly at the moment of publishing a new beta. 286 | 287 | ### Stable (`x.x.x`) 288 | 289 | > Once the beta phase has arrived to maturity (users seem to be happy with it, all issues and concerns have been addressed, etc.), the project enters the stable phase. 290 | > 291 | > The goal of the stable phase is to publish the new project version and to advocate it as Prismic's latest standard. During this "living" phase of the project bug fixes and new features will be added. If the need for breaking or large changes arises, the project will enter the pre-alpha phase and begin a new cycle. 292 | 293 | During the stable phase, the following will happen: 294 | 295 | **Publishing public stable versions and related documentation:** 296 | 297 | The first stable version should be published along the related documentation. This release should be announced and shared to users extensively in order to get them up to Prismic latest standard. Subsequent stable versions can be published as often as needed but a particular attention should be paid toward testing and avoiding regressions. 298 | 299 | **Implementing new features:** 300 | 301 | New features can be implemented during the stable phase following user suggestions and new use cases discovered. To be published, new features should be extensively tested. Ideally, documentation should be updated at the time of publishing, however a delay is tolerated here as it requires coordination with the Prismic Education team. 302 | 303 | **Adding new examples:** 304 | 305 | While examples can be added at any time, it's certainly during the stable phase that most of them will be added. Examples should be added whenever it feels relevant for a use case to be pictured with a recommended recipe, allowing for later shares of said examples. 306 | 307 | ## Project Structure 308 | 309 | > Prismic open-source projects have been structured around standards maintainers brought from their different background and agreed upon on. They are meant to implement the same sensible defaults allowing for a coherent open-source ecosystem. 310 | > 311 | > Any changes to this structure are welcome but they should be first discussed on our [TypeScript template][template-issue]. Common sense still applies on a per-project basis if one requires some specific changes. 312 | 313 | Project is structured as follows (alphabetically, folders first): 314 | 315 | ### 📁  `.github` 316 | 317 | This folder is used to configure the project's GitHub repository. It contains: 318 | 319 | **Issue templates (`ISSUE_TEMPLATE/*`)** 320 | 321 | Those are used to standardize the way issues are created on the repository and to help with their triage by making sure all needed information is provided. Issue templates are also used to redirect users to our [community forum][community-forum] when relevant. 322 | 323 | **Pull request templates (`PULL_REQUEST_TEMPLATE.md`)** 324 | 325 | This one is used to standardize the way pull requests are created on the repository and to help with their triage by making sure all needed information is provided. 326 | 327 | **CI configuration (`.github/workflows/ci.yml`)** 328 | 329 | Our CI workflow is configured to run against all commits and pull requests directed toward the `master` branch. It makes sure the project builds and passes all tests configured on it (lint, unit, e2e, etc.) Coverage and bundle size are also collected by this workflow. 330 | 331 | ### 📁  `dist` 332 | 333 | This folder is not versioned. It contains the built artifacts of the project after a successful build. 334 | 335 | ### 📁  `examples` 336 | 337 | This folder contains examples of how to use the project. Examples are meant to be written over time as new use cases are discovered. 338 | 339 | ### 📁  `playground` 340 | 341 | This folder might not be available in this project. If it is, it is meant to contain a playground for developers to try the project during the development process. 342 | 343 | Scripts such as `playground:dev` or `playground:build` might be available inside the project [package.json](#-packagejson) to interact with it easily. 344 | 345 | ### 📁  `src` 346 | 347 | This folder contains the source code of the project written in TypeScript. The `index.ts` file inside it should only contain exports made available by the project. It should not contain any logic. 348 | 349 | ### 📁  `test` 350 | 351 | This folder contains tests of the project written in TypeScript. It may contain the following subdirectory: 352 | 353 | **Fixtures (`__fixtures__`)** 354 | 355 | This folder contains [fixtures](https://en.wikipedia.org/wiki/Test_fixture) used to test the project. 356 | 357 | **Test Utils (`__testutils__`)** 358 | 359 | This folder contains utility functions used to test the project. 360 | 361 | **Snapshots (`snapshots`)** 362 | 363 | This folder contains snapshots generated by the test framework when using snapshot testing strategies. It should not be altered manually. 364 | 365 | ### 📄  `.editorconfig`, `.eslintrc.cjs`, `.prettierrc`, `.size-limit.json`, `.versionrc`, `vite.config.ts`, `tsconfig.json` 366 | 367 | These files contain configuration for their eponymous tools: 368 | 369 | - [EditorConfig][editor-config]; 370 | - [ESLint][eslint]; 371 | - [Prettier][prettier]; 372 | - [Size Limit][size-limit]; 373 | - [Standard Version][standard-version]; 374 | - [Vite][vite]; 375 | - [Vitest][vitest]; 376 | - [TypeScript][typescript]. 377 | 378 | Any change to those files are welcome but they should be first discussed on our [TypeScript template][template-issue]. Common sense still applies if the project requires some specific changes. 379 | 380 | ### 📄  `.eslintignore`, `.gitignore`, `.prettierignore` 381 | 382 | These files contain ignore configuration for their eponymous tools. Ignore configuration should be based on the one available from `.gitignore` and extended from it. 383 | 384 | ### 📄  `.gitattributes` 385 | 386 | This file contains [attributes](https://git-scm.com/docs/gitattributes) used by Git to deal with the project's files. Our configuration makes sure all files use correct line endings and that lock files aren't subject to conflicts. 387 | 388 | ### 📄  `CHANGELOG.md` 389 | 390 | This file is automatically generated by [Standard Version](https://github.com/conventional-changelog/standard-version) according to commit messages following the [Conventional Commits specification][conventional-commits] whenever a release is made. 391 | 392 | ### 📄  `CONTRIBUTING.md`, `README.md` 393 | 394 | These files contain project's related information and developers (maintainers) documentation. 395 | 396 | ### 📄  `LICENSE` 397 | 398 | This file contains a copy of the project's Apache 2.0 license we use on this project. The Apache 2.0 license has a few more restrictions over the MIT one. Notably (not legal advice), any change by a third party to Apache 2.0 licensed code is required to be stated by the third party. Same applies for changes to the project name by a third party (still not legal advice). For full details refer to the [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) license text itself. 399 | 400 | ### 📄  `package-lock.json` 401 | 402 | This file is the lock file generated by [npm][npm] to represent the resolved dependencies used by the project. We use npm over [Yarn][yarn] to manage dependencies and only this lock file should be versioned (`yarn.lock` is even ignored to prevent mistakes). 403 | 404 | ### 📄  `package.json` 405 | 406 | The project's package definition file. 407 | 408 | **Scripts (`scripts`)** 409 | 410 | - `build`: Builds the project; 411 | - `dev`: Builds the project with watch mode enabled; 412 | - `playground:*`: Any command related to the project [playground](#-playground) if any; 413 | - `format`: Runs Prettier on the project; 414 | - `prepare`: npm life cycle script to make sure the project is built before any npm related command (`publish`, `install`, etc.); 415 | - `release`: creates and publishes a new release of the package, version is determined after commit messages following the [Conventional Commits specification][conventional-commits]; 416 | - `release:dry`: dry-run of the `release` script; 417 | - `release:alpha`: creates and publishes a new alpha release of the package; 418 | - `release:alpha:dry`: dry-run of the `release:alpha` script; 419 | - `lint`: Runs ESLint on the project; 420 | - `unit`: Runs Vitest on the project; 421 | - `unit:watch`: Runs Vitest on the project in watch mode; 422 | - `size`: Runs Size Limit on the project; 423 | - `test`: Runs the `lint`, `unit`, `build`, and `size` scripts. 424 | 425 | **Minimum Node version supported (`engines.node`)** 426 | 427 | The minimum Node version supported by the project is stated under the `engines` object. We aim at supporting the oldest Long Term Support (LTS) version of Node that has still not reached End Of Life (EOL): [nodejs.org/en/about/releases](https://nodejs.org/en/about/releases) 428 | 429 | 430 | 431 | [prismic-docs]: https://prismic.io/docs 432 | [community-forum]: https://community.prismic.io 433 | [conventional-commits]: https://conventionalcommits.org/en/v1.0.0 434 | [npm]: https://www.npmjs.com 435 | [yarn]: https://yarnpkg.com 436 | [editor-config]: https://editorconfig.org 437 | [eslint]: https://eslint.org 438 | [prettier]: https://prettier.io 439 | [size-limit]: https://github.com/ai/size-limit 440 | [standard-version]: https://github.com/conventional-changelog/standard-version 441 | [vite]: https://vitejs.dev 442 | [vitest]: https://vitest.dev 443 | [typescript]: https://www.typescriptlang.org 444 | [template]: https://github.com/prismicio/prismic-typescript-template 445 | [template-issue]: https://github.com/prismicio/prismic-typescript-template/issues/new/choose 446 | [changelog]: ./CHANGELOG.md 447 | [forum-question]: https://community.prismic.io 448 | [repo-issue]: https://github.com/prismicio/prismic-upgrade-from-legacy/issues/new/choose 449 | [repo-pull-requests]: https://github.com/prismicio/prismic-upgrade-from-legacy/pulls 450 | --------------------------------------------------------------------------------