@slicemachine/manager 0.15.3-dev-next-release.1 → 0.15.3-dev-next-release.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/PrismicAuthManager.cjs +8 -3
- package/dist/auth/PrismicAuthManager.cjs.map +1 -1
- package/dist/auth/PrismicAuthManager.js +8 -3
- package/dist/auth/PrismicAuthManager.js.map +1 -1
- package/dist/lib/fetchGitHubReleaseBodyForRelease.cjs +4 -1
- package/dist/lib/fetchGitHubReleaseBodyForRelease.cjs.map +1 -1
- package/dist/lib/fetchGitHubReleaseBodyForRelease.js +4 -1
- package/dist/lib/fetchGitHubReleaseBodyForRelease.js.map +1 -1
- package/dist/lib/installDependencies.cjs +6 -1
- package/dist/lib/installDependencies.cjs.map +1 -1
- package/dist/lib/installDependencies.js +6 -1
- package/dist/lib/installDependencies.js.map +1 -1
- package/dist/managers/customTypes/CustomTypesManager.cjs +3 -1
- package/dist/managers/customTypes/CustomTypesManager.cjs.map +1 -1
- package/dist/managers/customTypes/CustomTypesManager.js +3 -1
- package/dist/managers/customTypes/CustomTypesManager.js.map +1 -1
- package/dist/managers/prismicRepository/PrismicRepositoryManager.cjs +6 -3
- package/dist/managers/prismicRepository/PrismicRepositoryManager.cjs.map +1 -1
- package/dist/managers/prismicRepository/PrismicRepositoryManager.js +6 -3
- package/dist/managers/prismicRepository/PrismicRepositoryManager.js.map +1 -1
- package/dist/managers/project/ProjectManager.cjs +3 -1
- package/dist/managers/project/ProjectManager.cjs.map +1 -1
- package/dist/managers/project/ProjectManager.js +3 -1
- package/dist/managers/project/ProjectManager.js.map +1 -1
- package/dist/managers/screenshots/ScreenshotsManager.cjs +17 -5
- package/dist/managers/screenshots/ScreenshotsManager.cjs.map +1 -1
- package/dist/managers/screenshots/ScreenshotsManager.js +17 -5
- package/dist/managers/screenshots/ScreenshotsManager.js.map +1 -1
- package/package.json +3 -3
- package/src/auth/PrismicAuthManager.ts +8 -2
- package/src/lib/fetchGitHubReleaseBodyForRelease.ts +4 -1
- package/src/lib/installDependencies.ts +6 -0
- package/src/managers/customTypes/CustomTypesManager.ts +3 -0
- package/src/managers/prismicRepository/PrismicRepositoryManager.ts +6 -3
- package/src/managers/project/ProjectManager.ts +3 -1
- package/src/managers/screenshots/ScreenshotsManager.ts +17 -2
|
@@ -208,7 +208,9 @@ class PrismicAuthManager {
|
|
|
208
208
|
authState.cookies[AUTH_COOKIE_KEY] = text;
|
|
209
209
|
await this._writePersistedAuthState(authState);
|
|
210
210
|
} else {
|
|
211
|
-
throw new errors.InternalError("Failed to refresh authentication token."
|
|
211
|
+
throw new errors.InternalError("Failed to refresh authentication token.", {
|
|
212
|
+
cause: text
|
|
213
|
+
});
|
|
212
214
|
}
|
|
213
215
|
} else {
|
|
214
216
|
throw new errors.UnauthenticatedError();
|
|
@@ -228,15 +230,18 @@ class PrismicAuthManager {
|
|
|
228
230
|
"User-Agent": SLICE_MACHINE_USER_AGENT.SLICE_MACHINE_USER_AGENT
|
|
229
231
|
}
|
|
230
232
|
});
|
|
231
|
-
const json = await res.json();
|
|
232
233
|
if (res.ok) {
|
|
234
|
+
const json = await res.json();
|
|
233
235
|
const { value: profile, error } = decode.decode(PrismicUserProfile, json);
|
|
234
236
|
if (error) {
|
|
235
237
|
throw new errors.UnexpectedDataError("Received invalid data from the Prismic user service.");
|
|
236
238
|
}
|
|
237
239
|
return profile;
|
|
238
240
|
} else {
|
|
239
|
-
|
|
241
|
+
const text = await res.text();
|
|
242
|
+
throw new errors.InternalError("Failed to retrieve profile from the Prismic user service.", {
|
|
243
|
+
cause: text
|
|
244
|
+
});
|
|
240
245
|
}
|
|
241
246
|
}
|
|
242
247
|
async _readPersistedAuthState() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PrismicAuthManager.cjs","sources":["../../../src/auth/PrismicAuthManager.ts"],"sourcesContent":["import * as t from \"io-ts\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport * as os from \"node:os\";\nimport * as http from \"node:http\";\n\nimport * as h3 from \"h3\";\nimport fetch from \"../lib/fetch\";\nimport cookie from \"cookie\";\nimport cors from \"cors\";\nimport getPort from \"get-port\";\n\nimport { decode } from \"../lib/decode\";\nimport { serializeCookies } from \"../lib/serializeCookies\";\n\nimport { API_ENDPOINTS } from \"../constants/API_ENDPOINTS\";\nimport { SLICE_MACHINE_USER_AGENT } from \"../constants/SLICE_MACHINE_USER_AGENT\";\nimport { createPrismicAuthManagerMiddleware } from \"./createPrismicAuthManagerMiddleware\";\nimport {\n\tInternalError,\n\tUnauthenticatedError,\n\tUnexpectedDataError,\n} from \"../errors\";\n\nconst COOKIE_SEPARATOR = \"; \";\nconst AUTH_COOKIE_KEY = \"prismic-auth\";\nconst SESSION_COOKIE_KEY = \"SESSION\";\n\nconst PERSISTED_AUTH_STATE_FILE_NAME = \".prismic\";\nconst DEFAULT_PERSISTED_AUTH_STATE: PrismicAuthState = {\n\tbase: \"https://prismic.io\",\n\tcookies: {},\n};\n\nconst PrismicAuthState = t.intersection([\n\tt.type({\n\t\tbase: t.string,\n\t\tcookies: t.intersection([\n\t\t\tt.partial({\n\t\t\t\t[AUTH_COOKIE_KEY]: t.string,\n\t\t\t\tSESSION: t.string,\n\t\t\t}),\n\t\t\tt.record(t.string, t.string),\n\t\t]),\n\t}),\n\tt.partial({\n\t\tshortId: t.string,\n\t\tintercomHash: t.string,\n\t\toauthAccessToken: t.string,\n\t\tauthUrl: t.string,\n\t}),\n]);\nexport type PrismicAuthState = t.TypeOf<typeof PrismicAuthState>;\n\nconst PrismicUserProfile = t.exact(\n\tt.type({\n\t\tuserId: t.string,\n\t\tshortId: t.string,\n\t\tintercomHash: t.string,\n\t\temail: t.string,\n\t\tfirstName: t.string,\n\t\tlastName: t.string,\n\t}),\n);\nexport type PrismicUserProfile = t.TypeOf<typeof PrismicUserProfile>;\n\ntype PrismicAuthManagerConstructorArgs = {\n\tscopedDirectory?: string;\n};\n\ntype PrismicAuthManagerLoginArgs = {\n\temail: string;\n\tcookies: string[];\n};\n\ntype PrismicAuthManagerGetLoginSessionInfoReturnType = {\n\tport: number;\n\turl: string;\n};\n\ntype PrismicAuthManagerNodeLoginSessionArgs = {\n\tport: number;\n\tonListenCallback?: () => void;\n};\n\ntype GetProfileForAuthenticationTokenArgs = {\n\tauthenticationToken: string;\n};\n\nconst checkHasAuthenticationToken = (\n\tauthState: PrismicAuthState,\n): authState is PrismicAuthState & {\n\tcookies: Required<\n\t\tPick<\n\t\t\tPrismicAuthState[\"cookies\"],\n\t\t\ttypeof AUTH_COOKIE_KEY | typeof SESSION_COOKIE_KEY\n\t\t>\n\t>;\n} => {\n\treturn Boolean(\n\t\tauthState.cookies[AUTH_COOKIE_KEY] && authState.cookies[SESSION_COOKIE_KEY],\n\t);\n};\n\nconst parseCookies = (cookies: string): Record<string, string> => {\n\treturn cookie.parse(cookies, {\n\t\t// Don't escape any values.\n\t\tdecode: (value) => value,\n\t});\n};\n\nexport class PrismicAuthManager {\n\t// TODO: Automatically scope the manager to the current Slice Machine\n\t// project? If not, this internal state can be removed.\n\tscopedDirectory: string;\n\n\tconstructor({\n\t\tscopedDirectory = os.homedir(),\n\t}: PrismicAuthManagerConstructorArgs = {}) {\n\t\tthis.scopedDirectory = scopedDirectory;\n\t}\n\n\t// TODO: Make the `cookies` argument more explicit. What are these\n\t// mysterious cookies?\n\tasync login(args: PrismicAuthManagerLoginArgs): Promise<void> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\t// Set the auth's URL base to the current base at runtime.\n\t\tauthState.base = API_ENDPOINTS.PrismicWroom;\n\t\tauthState.cookies = {\n\t\t\t...authState.cookies,\n\t\t\t...parseCookies(args.cookies.join(COOKIE_SEPARATOR)),\n\t\t};\n\n\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\tconst authenticationToken = authState.cookies[AUTH_COOKIE_KEY];\n\t\t\tconst profile = await this._getProfileForAuthenticationToken({\n\t\t\t\tauthenticationToken,\n\t\t\t});\n\n\t\t\tauthState.shortId = profile.shortId;\n\t\t\tauthState.intercomHash = profile.intercomHash;\n\t\t}\n\n\t\tawait this._writePersistedAuthState(authState);\n\t}\n\n\tasync getLoginSessionInfo(): Promise<PrismicAuthManagerGetLoginSessionInfoReturnType> {\n\t\t// Pick a random port, with a preference for historic `5555`\n\t\tconst port = await getPort({ port: 5555 });\n\n\t\tconst url = new URL(\n\t\t\t`./dashboard/cli/login?source=slice-machine&port=${port}`,\n\t\t\tAPI_ENDPOINTS.PrismicWroom,\n\t\t).toString();\n\n\t\treturn {\n\t\t\tport,\n\t\t\turl,\n\t\t};\n\t}\n\n\tasync nodeLoginSession(\n\t\targs: PrismicAuthManagerNodeLoginSessionArgs,\n\t): Promise<void> {\n\t\treturn new Promise<void>(async (resolve) => {\n\t\t\t// Timeout attempt after 3 minutes\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tserver.close();\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Login timeout, server did not receive a response within a 3-minute delay\",\n\t\t\t\t);\n\t\t\t}, 180_000);\n\n\t\t\tconst app = h3.createApp();\n\t\t\tapp.use(h3.fromNodeMiddleware(cors()));\n\t\t\tapp.use(\n\t\t\t\th3.fromNodeMiddleware(\n\t\t\t\t\tcreatePrismicAuthManagerMiddleware({\n\t\t\t\t\t\tprismicAuthManager: this,\n\t\t\t\t\t\tonLoginCallback() {\n\t\t\t\t\t\t\t// Cleanup process and resolve\n\t\t\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\t\t\tserver.close();\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\n\t\t\t// Start server\n\t\t\tconst server = http.createServer(h3.toNodeListener(app));\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tserver.once(\"listening\", () => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t\tserver.listen(args.port);\n\t\t\t});\n\n\t\t\tif (args.onListenCallback) {\n\t\t\t\targs.onListenCallback();\n\t\t\t}\n\t\t});\n\t}\n\n\tasync logout(): Promise<void> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\t// Remove all Prismic cookies, short ID, and Intercom hash\n\t\t// associated with the currently logged in user.\n\t\tauthState.cookies = {};\n\t\tauthState.shortId = undefined;\n\t\tauthState.intercomHash = undefined;\n\n\t\tawait this._writePersistedAuthState(authState);\n\t}\n\n\tasync checkIsLoggedIn(): Promise<boolean> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\tconst url = new URL(\"./validate\", API_ENDPOINTS.PrismicAuthentication);\n\t\t\turl.searchParams.set(\"token\", authState.cookies[AUTH_COOKIE_KEY]);\n\n\t\t\tlet res;\n\t\t\ttry {\n\t\t\t\tres = await fetch(url.toString(), {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"User-Agent\": SLICE_MACHINE_USER_AGENT,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\t// Noop, we return if `res` is not defined.\n\t\t\t}\n\n\t\t\tif (!res || !res.ok) {\n\t\t\t\tawait this.logout();\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync getAuthenticationCookies(): Promise<\n\t\tPrismicAuthState[\"cookies\"] &\n\t\t\tRequired<\n\t\t\t\tPick<\n\t\t\t\t\tPrismicAuthState[\"cookies\"],\n\t\t\t\t\ttypeof AUTH_COOKIE_KEY | typeof SESSION_COOKIE_KEY\n\t\t\t\t>\n\t\t\t>\n\t> {\n\t\tconst isLoggedIn = await this.checkIsLoggedIn();\n\n\t\tif (isLoggedIn) {\n\t\t\tconst authState = await this._readPersistedAuthState();\n\n\t\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\t\treturn authState.cookies;\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error(\"Not logged in.\");\n\t}\n\n\tasync getAuthenticationToken(): Promise<string> {\n\t\tconst cookies = await this.getAuthenticationCookies();\n\n\t\treturn cookies[AUTH_COOKIE_KEY];\n\t}\n\n\tasync refreshAuthenticationToken(): Promise<void> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\tconst url = new URL(\n\t\t\t\t\"./refreshtoken\",\n\t\t\t\tAPI_ENDPOINTS.PrismicAuthentication,\n\t\t\t);\n\t\t\turl.searchParams.set(\"token\", authState.cookies[AUTH_COOKIE_KEY]);\n\n\t\t\tconst res = await fetch(url.toString(), {\n\t\t\t\theaders: {\n\t\t\t\t\t\"User-Agent\": SLICE_MACHINE_USER_AGENT,\n\t\t\t\t},\n\t\t\t});\n\t\t\tconst text = await res.text();\n\n\t\t\tif (res.ok) {\n\t\t\t\tauthState.cookies[AUTH_COOKIE_KEY] = text;\n\n\t\t\t\tawait this._writePersistedAuthState(authState);\n\t\t\t} else {\n\t\t\t\tthrow new InternalError(\"Failed to refresh authentication token.\");\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new UnauthenticatedError();\n\t\t}\n\t}\n\n\tasync getProfile(): Promise<PrismicUserProfile> {\n\t\tconst authenticationToken = await this.getAuthenticationToken();\n\n\t\treturn await this._getProfileForAuthenticationToken({\n\t\t\tauthenticationToken,\n\t\t});\n\t}\n\n\tprivate async _getProfileForAuthenticationToken(\n\t\targs: GetProfileForAuthenticationTokenArgs,\n\t): Promise<PrismicUserProfile> {\n\t\tconst url = new URL(\"./profile\", API_ENDPOINTS.PrismicUser);\n\t\tconst res = await fetch(url.toString(), {\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${args.authenticationToken}`,\n\t\t\t\t\"User-Agent\": SLICE_MACHINE_USER_AGENT,\n\t\t\t},\n\t\t});\n\t\tconst json = await res.json();\n\n\t\tif (res.ok) {\n\t\t\tconst { value: profile, error } = decode(PrismicUserProfile, json);\n\n\t\t\tif (error) {\n\t\t\t\tthrow new UnexpectedDataError(\n\t\t\t\t\t\"Received invalid data from the Prismic user service.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn profile;\n\t\t} else {\n\t\t\tthrow new InternalError(\n\t\t\t\t\"Failed to retrieve profile from the Prismic user service.\",\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate async _readPersistedAuthState(): Promise<PrismicAuthState> {\n\t\tconst authStateFilePath = this._getPersistedAuthStateFilePath();\n\n\t\tlet authStateFileContents: string = JSON.stringify({});\n\t\tlet rawAuthState: Record<string, unknown> = {};\n\n\t\ttry {\n\t\t\tauthStateFileContents = await fs.readFile(authStateFilePath, \"utf8\");\n\t\t\trawAuthState = JSON.parse(authStateFileContents);\n\t\t} catch {\n\t\t\t// Write a default persisted state if it doesn't already exist.\n\n\t\t\trawAuthState = {\n\t\t\t\t...DEFAULT_PERSISTED_AUTH_STATE,\n\t\t\t\tcookies: serializeCookies(DEFAULT_PERSISTED_AUTH_STATE.cookies),\n\t\t\t};\n\t\t\tauthStateFileContents = JSON.stringify(rawAuthState, null, \"\\t\");\n\n\t\t\tawait fs.mkdir(path.dirname(authStateFilePath), { recursive: true });\n\t\t\tawait fs.writeFile(authStateFilePath, authStateFileContents);\n\t\t}\n\n\t\t// Decode cookies into a record for convenience.\n\t\tif (typeof rawAuthState.cookies === \"string\") {\n\t\t\trawAuthState.cookies = parseCookies(rawAuthState.cookies);\n\t\t}\n\n\t\tconst { value: authState, error } = decode(PrismicAuthState, rawAuthState);\n\n\t\tif (error) {\n\t\t\tthrow new UnexpectedDataError(\"Prismic authentication state is invalid.\");\n\t\t}\n\n\t\treturn authState;\n\t}\n\n\tprivate async _writePersistedAuthState(\n\t\tauthState: PrismicAuthState,\n\t): Promise<void> {\n\t\tconst authStateFilePath = this._getPersistedAuthStateFilePath();\n\n\t\tconst preparedAuthState = {\n\t\t\t...authState,\n\t\t\tcookies: serializeCookies(authState.cookies),\n\t\t};\n\n\t\ttry {\n\t\t\tawait fs.writeFile(\n\t\t\t\tauthStateFilePath,\n\t\t\t\tJSON.stringify(preparedAuthState, null, 2),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new InternalError(\n\t\t\t\t\"Failed to write Prismic authentication state to the file system.\",\n\t\t\t\t{\n\t\t\t\t\tcause: error,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate _getPersistedAuthStateFilePath(): string {\n\t\treturn path.resolve(this.scopedDirectory, PERSISTED_AUTH_STATE_FILE_NAME);\n\t}\n}\n"],"names":["t","os","API_ENDPOINTS","getPort","h3","createPrismicAuthManagerMiddleware","http","resolve","fetch","SLICE_MACHINE_USER_AGENT","InternalError","UnauthenticatedError","decode","UnexpectedDataError","fs","serializeCookies","path"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAE3B,MAAM,iCAAiC;AACvC,MAAM,+BAAiD;AAAA,EACtD,MAAM;AAAA,EACN,SAAS,CAAE;;AAGZ,MAAM,mBAAmBA,aAAE,aAAa;AAAA,EACvCA,aAAE,KAAK;AAAA,IACN,MAAMA,aAAE;AAAA,IACR,SAASA,aAAE,aAAa;AAAA,MACvBA,aAAE,QAAQ;AAAA,QACT,CAAC,eAAe,GAAGA,aAAE;AAAA,QACrB,SAASA,aAAE;AAAA,MAAA,CACX;AAAA,MACDA,aAAE,OAAOA,aAAE,QAAQA,aAAE,MAAM;AAAA,IAAA,CAC3B;AAAA,EAAA,CACD;AAAA,EACDA,aAAE,QAAQ;AAAA,IACT,SAASA,aAAE;AAAA,IACX,cAAcA,aAAE;AAAA,IAChB,kBAAkBA,aAAE;AAAA,IACpB,SAASA,aAAE;AAAA,EAAA,CACX;AACD,CAAA;AAGD,MAAM,qBAAqBA,aAAE,MAC5BA,aAAE,KAAK;AAAA,EACN,QAAQA,aAAE;AAAA,EACV,SAASA,aAAE;AAAA,E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AAA,IAAA;AAGxC,QAAA;AACG,YAAAD,cAAG,UACR,mBACA,KAAK,UAAU,mBAAmB,MAAM,CAAC,CAAC;AAAA,aAEnC;AACF,YAAA,IAAIJ,qBACT,oEACA;AAAA,QACC,OAAO;AAAA,MAAA,CACP;AAAA,IAEF;AAAA,EACF;AAAA,EAEQ,iCAA8B;AACrC,WAAOM,gBAAK,QAAQ,KAAK,iBAAiB,8BAA8B;AAAA,EACzE;AACA;;"}
|
|
1
|
+
{"version":3,"file":"PrismicAuthManager.cjs","sources":["../../../src/auth/PrismicAuthManager.ts"],"sourcesContent":["import * as t from \"io-ts\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport * as os from \"node:os\";\nimport * as http from \"node:http\";\n\nimport * as h3 from \"h3\";\nimport fetch from \"../lib/fetch\";\nimport cookie from \"cookie\";\nimport cors from \"cors\";\nimport getPort from \"get-port\";\n\nimport { decode } from \"../lib/decode\";\nimport { serializeCookies } from \"../lib/serializeCookies\";\n\nimport { API_ENDPOINTS } from \"../constants/API_ENDPOINTS\";\nimport { SLICE_MACHINE_USER_AGENT } from \"../constants/SLICE_MACHINE_USER_AGENT\";\nimport { createPrismicAuthManagerMiddleware } from \"./createPrismicAuthManagerMiddleware\";\nimport {\n\tInternalError,\n\tUnauthenticatedError,\n\tUnexpectedDataError,\n} from \"../errors\";\n\nconst COOKIE_SEPARATOR = \"; \";\nconst AUTH_COOKIE_KEY = \"prismic-auth\";\nconst SESSION_COOKIE_KEY = \"SESSION\";\n\nconst PERSISTED_AUTH_STATE_FILE_NAME = \".prismic\";\nconst DEFAULT_PERSISTED_AUTH_STATE: PrismicAuthState = {\n\tbase: \"https://prismic.io\",\n\tcookies: {},\n};\n\nconst PrismicAuthState = t.intersection([\n\tt.type({\n\t\tbase: t.string,\n\t\tcookies: t.intersection([\n\t\t\tt.partial({\n\t\t\t\t[AUTH_COOKIE_KEY]: t.string,\n\t\t\t\tSESSION: t.string,\n\t\t\t}),\n\t\t\tt.record(t.string, t.string),\n\t\t]),\n\t}),\n\tt.partial({\n\t\tshortId: t.string,\n\t\tintercomHash: t.string,\n\t\toauthAccessToken: t.string,\n\t\tauthUrl: t.string,\n\t}),\n]);\nexport type PrismicAuthState = t.TypeOf<typeof PrismicAuthState>;\n\nconst PrismicUserProfile = t.exact(\n\tt.type({\n\t\tuserId: t.string,\n\t\tshortId: t.string,\n\t\tintercomHash: t.string,\n\t\temail: t.string,\n\t\tfirstName: t.string,\n\t\tlastName: t.string,\n\t}),\n);\nexport type PrismicUserProfile = t.TypeOf<typeof PrismicUserProfile>;\n\ntype PrismicAuthManagerConstructorArgs = {\n\tscopedDirectory?: string;\n};\n\ntype PrismicAuthManagerLoginArgs = {\n\temail: string;\n\tcookies: string[];\n};\n\ntype PrismicAuthManagerGetLoginSessionInfoReturnType = {\n\tport: number;\n\turl: string;\n};\n\ntype PrismicAuthManagerNodeLoginSessionArgs = {\n\tport: number;\n\tonListenCallback?: () => void;\n};\n\ntype GetProfileForAuthenticationTokenArgs = {\n\tauthenticationToken: string;\n};\n\nconst checkHasAuthenticationToken = (\n\tauthState: PrismicAuthState,\n): authState is PrismicAuthState & {\n\tcookies: Required<\n\t\tPick<\n\t\t\tPrismicAuthState[\"cookies\"],\n\t\t\ttypeof AUTH_COOKIE_KEY | typeof SESSION_COOKIE_KEY\n\t\t>\n\t>;\n} => {\n\treturn Boolean(\n\t\tauthState.cookies[AUTH_COOKIE_KEY] && authState.cookies[SESSION_COOKIE_KEY],\n\t);\n};\n\nconst parseCookies = (cookies: string): Record<string, string> => {\n\treturn cookie.parse(cookies, {\n\t\t// Don't escape any values.\n\t\tdecode: (value) => value,\n\t});\n};\n\nexport class PrismicAuthManager {\n\t// TODO: Automatically scope the manager to the current Slice Machine\n\t// project? If not, this internal state can be removed.\n\tscopedDirectory: string;\n\n\tconstructor({\n\t\tscopedDirectory = os.homedir(),\n\t}: PrismicAuthManagerConstructorArgs = {}) {\n\t\tthis.scopedDirectory = scopedDirectory;\n\t}\n\n\t// TODO: Make the `cookies` argument more explicit. What are these\n\t// mysterious cookies?\n\tasync login(args: PrismicAuthManagerLoginArgs): Promise<void> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\t// Set the auth's URL base to the current base at runtime.\n\t\tauthState.base = API_ENDPOINTS.PrismicWroom;\n\t\tauthState.cookies = {\n\t\t\t...authState.cookies,\n\t\t\t...parseCookies(args.cookies.join(COOKIE_SEPARATOR)),\n\t\t};\n\n\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\tconst authenticationToken = authState.cookies[AUTH_COOKIE_KEY];\n\t\t\tconst profile = await this._getProfileForAuthenticationToken({\n\t\t\t\tauthenticationToken,\n\t\t\t});\n\n\t\t\tauthState.shortId = profile.shortId;\n\t\t\tauthState.intercomHash = profile.intercomHash;\n\t\t}\n\n\t\tawait this._writePersistedAuthState(authState);\n\t}\n\n\tasync getLoginSessionInfo(): Promise<PrismicAuthManagerGetLoginSessionInfoReturnType> {\n\t\t// Pick a random port, with a preference for historic `5555`\n\t\tconst port = await getPort({ port: 5555 });\n\n\t\tconst url = new URL(\n\t\t\t`./dashboard/cli/login?source=slice-machine&port=${port}`,\n\t\t\tAPI_ENDPOINTS.PrismicWroom,\n\t\t).toString();\n\n\t\treturn {\n\t\t\tport,\n\t\t\turl,\n\t\t};\n\t}\n\n\tasync nodeLoginSession(\n\t\targs: PrismicAuthManagerNodeLoginSessionArgs,\n\t): Promise<void> {\n\t\treturn new Promise<void>(async (resolve) => {\n\t\t\t// Timeout attempt after 3 minutes\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tserver.close();\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Login timeout, server did not receive a response within a 3-minute delay\",\n\t\t\t\t);\n\t\t\t}, 180_000);\n\n\t\t\tconst app = h3.createApp();\n\t\t\tapp.use(h3.fromNodeMiddleware(cors()));\n\t\t\tapp.use(\n\t\t\t\th3.fromNodeMiddleware(\n\t\t\t\t\tcreatePrismicAuthManagerMiddleware({\n\t\t\t\t\t\tprismicAuthManager: this,\n\t\t\t\t\t\tonLoginCallback() {\n\t\t\t\t\t\t\t// Cleanup process and resolve\n\t\t\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\t\t\tserver.close();\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\n\t\t\t// Start server\n\t\t\tconst server = http.createServer(h3.toNodeListener(app));\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tserver.once(\"listening\", () => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t\tserver.listen(args.port);\n\t\t\t});\n\n\t\t\tif (args.onListenCallback) {\n\t\t\t\targs.onListenCallback();\n\t\t\t}\n\t\t});\n\t}\n\n\tasync logout(): Promise<void> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\t// Remove all Prismic cookies, short ID, and Intercom hash\n\t\t// associated with the currently logged in user.\n\t\tauthState.cookies = {};\n\t\tauthState.shortId = undefined;\n\t\tauthState.intercomHash = undefined;\n\n\t\tawait this._writePersistedAuthState(authState);\n\t}\n\n\tasync checkIsLoggedIn(): Promise<boolean> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\tconst url = new URL(\"./validate\", API_ENDPOINTS.PrismicAuthentication);\n\t\t\turl.searchParams.set(\"token\", authState.cookies[AUTH_COOKIE_KEY]);\n\n\t\t\tlet res;\n\t\t\ttry {\n\t\t\t\tres = await fetch(url.toString(), {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"User-Agent\": SLICE_MACHINE_USER_AGENT,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\t// Noop, we return if `res` is not defined.\n\t\t\t}\n\n\t\t\tif (!res || !res.ok) {\n\t\t\t\tawait this.logout();\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync getAuthenticationCookies(): Promise<\n\t\tPrismicAuthState[\"cookies\"] &\n\t\t\tRequired<\n\t\t\t\tPick<\n\t\t\t\t\tPrismicAuthState[\"cookies\"],\n\t\t\t\t\ttypeof AUTH_COOKIE_KEY | typeof SESSION_COOKIE_KEY\n\t\t\t\t>\n\t\t\t>\n\t> {\n\t\tconst isLoggedIn = await this.checkIsLoggedIn();\n\n\t\tif (isLoggedIn) {\n\t\t\tconst authState = await this._readPersistedAuthState();\n\n\t\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\t\treturn authState.cookies;\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error(\"Not logged in.\");\n\t}\n\n\tasync getAuthenticationToken(): Promise<string> {\n\t\tconst cookies = await this.getAuthenticationCookies();\n\n\t\treturn cookies[AUTH_COOKIE_KEY];\n\t}\n\n\tasync refreshAuthenticationToken(): Promise<void> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\tconst url = new URL(\n\t\t\t\t\"./refreshtoken\",\n\t\t\t\tAPI_ENDPOINTS.PrismicAuthentication,\n\t\t\t);\n\t\t\turl.searchParams.set(\"token\", authState.cookies[AUTH_COOKIE_KEY]);\n\n\t\t\tconst res = await fetch(url.toString(), {\n\t\t\t\theaders: {\n\t\t\t\t\t\"User-Agent\": SLICE_MACHINE_USER_AGENT,\n\t\t\t\t},\n\t\t\t});\n\t\t\tconst text = await res.text();\n\n\t\t\tif (res.ok) {\n\t\t\t\tauthState.cookies[AUTH_COOKIE_KEY] = text;\n\n\t\t\t\tawait this._writePersistedAuthState(authState);\n\t\t\t} else {\n\t\t\t\tthrow new InternalError(\"Failed to refresh authentication token.\", {\n\t\t\t\t\tcause: text,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new UnauthenticatedError();\n\t\t}\n\t}\n\n\tasync getProfile(): Promise<PrismicUserProfile> {\n\t\tconst authenticationToken = await this.getAuthenticationToken();\n\n\t\treturn await this._getProfileForAuthenticationToken({\n\t\t\tauthenticationToken,\n\t\t});\n\t}\n\n\tprivate async _getProfileForAuthenticationToken(\n\t\targs: GetProfileForAuthenticationTokenArgs,\n\t): Promise<PrismicUserProfile> {\n\t\tconst url = new URL(\"./profile\", API_ENDPOINTS.PrismicUser);\n\t\tconst res = await fetch(url.toString(), {\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${args.authenticationToken}`,\n\t\t\t\t\"User-Agent\": SLICE_MACHINE_USER_AGENT,\n\t\t\t},\n\t\t});\n\n\t\tif (res.ok) {\n\t\t\tconst json = await res.json();\n\t\t\tconst { value: profile, error } = decode(PrismicUserProfile, json);\n\n\t\t\tif (error) {\n\t\t\t\tthrow new UnexpectedDataError(\n\t\t\t\t\t\"Received invalid data from the Prismic user service.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn profile;\n\t\t} else {\n\t\t\tconst text = await res.text();\n\t\t\tthrow new InternalError(\n\t\t\t\t\"Failed to retrieve profile from the Prismic user service.\",\n\t\t\t\t{\n\t\t\t\t\tcause: text,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate async _readPersistedAuthState(): Promise<PrismicAuthState> {\n\t\tconst authStateFilePath = this._getPersistedAuthStateFilePath();\n\n\t\tlet authStateFileContents: string = JSON.stringify({});\n\t\tlet rawAuthState: Record<string, unknown> = {};\n\n\t\ttry {\n\t\t\tauthStateFileContents = await fs.readFile(authStateFilePath, \"utf8\");\n\t\t\trawAuthState = JSON.parse(authStateFileContents);\n\t\t} catch {\n\t\t\t// Write a default persisted state if it doesn't already exist.\n\n\t\t\trawAuthState = {\n\t\t\t\t...DEFAULT_PERSISTED_AUTH_STATE,\n\t\t\t\tcookies: serializeCookies(DEFAULT_PERSISTED_AUTH_STATE.cookies),\n\t\t\t};\n\t\t\tauthStateFileContents = JSON.stringify(rawAuthState, null, \"\\t\");\n\n\t\t\tawait fs.mkdir(path.dirname(authStateFilePath), { recursive: true });\n\t\t\tawait fs.writeFile(authStateFilePath, authStateFileContents);\n\t\t}\n\n\t\t// Decode cookies into a record for convenience.\n\t\tif (typeof rawAuthState.cookies === \"string\") {\n\t\t\trawAuthState.cookies = parseCookies(rawAuthState.cookies);\n\t\t}\n\n\t\tconst { value: authState, error } = decode(PrismicAuthState, rawAuthState);\n\n\t\tif (error) {\n\t\t\tthrow new UnexpectedDataError(\"Prismic authentication state is invalid.\");\n\t\t}\n\n\t\treturn authState;\n\t}\n\n\tprivate async _writePersistedAuthState(\n\t\tauthState: PrismicAuthState,\n\t): Promise<void> {\n\t\tconst authStateFilePath = this._getPersistedAuthStateFilePath();\n\n\t\tconst preparedAuthState = {\n\t\t\t...authState,\n\t\t\tcookies: serializeCookies(authState.cookies),\n\t\t};\n\n\t\ttry {\n\t\t\tawait fs.writeFile(\n\t\t\t\tauthStateFilePath,\n\t\t\t\tJSON.stringify(preparedAuthState, null, 2),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new InternalError(\n\t\t\t\t\"Failed to write Prismic authentication state to the file system.\",\n\t\t\t\t{\n\t\t\t\t\tcause: error,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate _getPersistedAuthStateFilePath(): string {\n\t\treturn path.resolve(this.scopedDirectory, PERSISTED_AUTH_STATE_FILE_NAME);\n\t}\n}\n"],"names":["t","os","API_ENDPOINTS","getPort","h3","createPrismicAuthManagerMiddleware","http","resolve","fetch","SLICE_MACHINE_USER_AGENT","InternalError","UnauthenticatedError","decode","UnexpectedDataError","fs","serializeCookies","path"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAE3B,MAAM,iCAAiC;AACvC,MAAM,+BAAiD;AAAA,EACtD,MAAM;AAAA,EACN,SAAS,CAAE;;AAGZ,MAAM,mBAAmBA,aAA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AA,iBAAiB,6BAA6B,OAAO;AAAA,MAAA;AAE/D,8BAAwB,KAAK,UAAU,cAAc,MAAM,GAAI;AAEzD,YAAAD,cAAG,MAAME,gBAAK,QAAQ,iBAAiB,GAAG,EAAE,WAAW,KAAA,CAAM;AAC7D,YAAAF,cAAG,UAAU,mBAAmB,qBAAqB;AAAA,IAC3D;AAGG,QAAA,OAAO,aAAa,YAAY,UAAU;AAChC,mBAAA,UAAU,aAAa,aAAa,OAAO;AAAA,IACxD;AAED,UAAM,EAAE,OAAO,WAAW,MAAU,IAAAF,cAAO,kBAAkB,YAAY;AAEzE,QAAI,OAAO;AACJ,YAAA,IAAIC,OAAAA,oBAAoB,0CAA0C;AAAA,IACxE;AAEM,WAAA;AAAA,EACR;AAAA,EAEQ,MAAM,yBACb,WAA2B;AAErB,UAAA,oBAAoB,KAAK;AAE/B,UAAM,oBAAoB;AAAA,MACzB,GAAG;AAAA,MACH,SAASE,iBAAAA,iBAAiB,UAAU,OAAO;AAAA,IAAA;AAGxC,QAAA;AACG,YAAAD,cAAG,UACR,mBACA,KAAK,UAAU,mBAAmB,MAAM,CAAC,CAAC;AAAA,aAEnC;AACF,YAAA,IAAIJ,qBACT,oEACA;AAAA,QACC,OAAO;AAAA,MAAA,CACP;AAAA,IAEF;AAAA,EACF;AAAA,EAEQ,iCAA8B;AACrC,WAAOM,gBAAK,QAAQ,KAAK,iBAAiB,8BAA8B;AAAA,EACzE;AACA;;"}
|
|
@@ -184,7 +184,9 @@ class PrismicAuthManager {
|
|
|
184
184
|
authState.cookies[AUTH_COOKIE_KEY] = text;
|
|
185
185
|
await this._writePersistedAuthState(authState);
|
|
186
186
|
} else {
|
|
187
|
-
throw new InternalError("Failed to refresh authentication token."
|
|
187
|
+
throw new InternalError("Failed to refresh authentication token.", {
|
|
188
|
+
cause: text
|
|
189
|
+
});
|
|
188
190
|
}
|
|
189
191
|
} else {
|
|
190
192
|
throw new UnauthenticatedError();
|
|
@@ -204,15 +206,18 @@ class PrismicAuthManager {
|
|
|
204
206
|
"User-Agent": SLICE_MACHINE_USER_AGENT
|
|
205
207
|
}
|
|
206
208
|
});
|
|
207
|
-
const json = await res.json();
|
|
208
209
|
if (res.ok) {
|
|
210
|
+
const json = await res.json();
|
|
209
211
|
const { value: profile, error } = decode(PrismicUserProfile, json);
|
|
210
212
|
if (error) {
|
|
211
213
|
throw new UnexpectedDataError("Received invalid data from the Prismic user service.");
|
|
212
214
|
}
|
|
213
215
|
return profile;
|
|
214
216
|
} else {
|
|
215
|
-
|
|
217
|
+
const text = await res.text();
|
|
218
|
+
throw new InternalError("Failed to retrieve profile from the Prismic user service.", {
|
|
219
|
+
cause: text
|
|
220
|
+
});
|
|
216
221
|
}
|
|
217
222
|
}
|
|
218
223
|
async _readPersistedAuthState() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PrismicAuthManager.js","sources":["../../../src/auth/PrismicAuthManager.ts"],"sourcesContent":["import * as t from \"io-ts\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport * as os from \"node:os\";\nimport * as http from \"node:http\";\n\nimport * as h3 from \"h3\";\nimport fetch from \"../lib/fetch\";\nimport cookie from \"cookie\";\nimport cors from \"cors\";\nimport getPort from \"get-port\";\n\nimport { decode } from \"../lib/decode\";\nimport { serializeCookies } from \"../lib/serializeCookies\";\n\nimport { API_ENDPOINTS } from \"../constants/API_ENDPOINTS\";\nimport { SLICE_MACHINE_USER_AGENT } from \"../constants/SLICE_MACHINE_USER_AGENT\";\nimport { createPrismicAuthManagerMiddleware } from \"./createPrismicAuthManagerMiddleware\";\nimport {\n\tInternalError,\n\tUnauthenticatedError,\n\tUnexpectedDataError,\n} from \"../errors\";\n\nconst COOKIE_SEPARATOR = \"; \";\nconst AUTH_COOKIE_KEY = \"prismic-auth\";\nconst SESSION_COOKIE_KEY = \"SESSION\";\n\nconst PERSISTED_AUTH_STATE_FILE_NAME = \".prismic\";\nconst DEFAULT_PERSISTED_AUTH_STATE: PrismicAuthState = {\n\tbase: \"https://prismic.io\",\n\tcookies: {},\n};\n\nconst PrismicAuthState = t.intersection([\n\tt.type({\n\t\tbase: t.string,\n\t\tcookies: t.intersection([\n\t\t\tt.partial({\n\t\t\t\t[AUTH_COOKIE_KEY]: t.string,\n\t\t\t\tSESSION: t.string,\n\t\t\t}),\n\t\t\tt.record(t.string, t.string),\n\t\t]),\n\t}),\n\tt.partial({\n\t\tshortId: t.string,\n\t\tintercomHash: t.string,\n\t\toauthAccessToken: t.string,\n\t\tauthUrl: t.string,\n\t}),\n]);\nexport type PrismicAuthState = t.TypeOf<typeof PrismicAuthState>;\n\nconst PrismicUserProfile = t.exact(\n\tt.type({\n\t\tuserId: t.string,\n\t\tshortId: t.string,\n\t\tintercomHash: t.string,\n\t\temail: t.string,\n\t\tfirstName: t.string,\n\t\tlastName: t.string,\n\t}),\n);\nexport type PrismicUserProfile = t.TypeOf<typeof PrismicUserProfile>;\n\ntype PrismicAuthManagerConstructorArgs = {\n\tscopedDirectory?: string;\n};\n\ntype PrismicAuthManagerLoginArgs = {\n\temail: string;\n\tcookies: string[];\n};\n\ntype PrismicAuthManagerGetLoginSessionInfoReturnType = {\n\tport: number;\n\turl: string;\n};\n\ntype PrismicAuthManagerNodeLoginSessionArgs = {\n\tport: number;\n\tonListenCallback?: () => void;\n};\n\ntype GetProfileForAuthenticationTokenArgs = {\n\tauthenticationToken: string;\n};\n\nconst checkHasAuthenticationToken = (\n\tauthState: PrismicAuthState,\n): authState is PrismicAuthState & {\n\tcookies: Required<\n\t\tPick<\n\t\t\tPrismicAuthState[\"cookies\"],\n\t\t\ttypeof AUTH_COOKIE_KEY | typeof SESSION_COOKIE_KEY\n\t\t>\n\t>;\n} => {\n\treturn Boolean(\n\t\tauthState.cookies[AUTH_COOKIE_KEY] && authState.cookies[SESSION_COOKIE_KEY],\n\t);\n};\n\nconst parseCookies = (cookies: string): Record<string, string> => {\n\treturn cookie.parse(cookies, {\n\t\t// Don't escape any values.\n\t\tdecode: (value) => value,\n\t});\n};\n\nexport class PrismicAuthManager {\n\t// TODO: Automatically scope the manager to the current Slice Machine\n\t// project? If not, this internal state can be removed.\n\tscopedDirectory: string;\n\n\tconstructor({\n\t\tscopedDirectory = os.homedir(),\n\t}: PrismicAuthManagerConstructorArgs = {}) {\n\t\tthis.scopedDirectory = scopedDirectory;\n\t}\n\n\t// TODO: Make the `cookies` argument more explicit. What are these\n\t// mysterious cookies?\n\tasync login(args: PrismicAuthManagerLoginArgs): Promise<void> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\t// Set the auth's URL base to the current base at runtime.\n\t\tauthState.base = API_ENDPOINTS.PrismicWroom;\n\t\tauthState.cookies = {\n\t\t\t...authState.cookies,\n\t\t\t...parseCookies(args.cookies.join(COOKIE_SEPARATOR)),\n\t\t};\n\n\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\tconst authenticationToken = authState.cookies[AUTH_COOKIE_KEY];\n\t\t\tconst profile = await this._getProfileForAuthenticationToken({\n\t\t\t\tauthenticationToken,\n\t\t\t});\n\n\t\t\tauthState.shortId = profile.shortId;\n\t\t\tauthState.intercomHash = profile.intercomHash;\n\t\t}\n\n\t\tawait this._writePersistedAuthState(authState);\n\t}\n\n\tasync getLoginSessionInfo(): Promise<PrismicAuthManagerGetLoginSessionInfoReturnType> {\n\t\t// Pick a random port, with a preference for historic `5555`\n\t\tconst port = await getPort({ port: 5555 });\n\n\t\tconst url = new URL(\n\t\t\t`./dashboard/cli/login?source=slice-machine&port=${port}`,\n\t\t\tAPI_ENDPOINTS.PrismicWroom,\n\t\t).toString();\n\n\t\treturn {\n\t\t\tport,\n\t\t\turl,\n\t\t};\n\t}\n\n\tasync nodeLoginSession(\n\t\targs: PrismicAuthManagerNodeLoginSessionArgs,\n\t): Promise<void> {\n\t\treturn new Promise<void>(async (resolve) => {\n\t\t\t// Timeout attempt after 3 minutes\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tserver.close();\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Login timeout, server did not receive a response within a 3-minute delay\",\n\t\t\t\t);\n\t\t\t}, 180_000);\n\n\t\t\tconst app = h3.createApp();\n\t\t\tapp.use(h3.fromNodeMiddleware(cors()));\n\t\t\tapp.use(\n\t\t\t\th3.fromNodeMiddleware(\n\t\t\t\t\tcreatePrismicAuthManagerMiddleware({\n\t\t\t\t\t\tprismicAuthManager: this,\n\t\t\t\t\t\tonLoginCallback() {\n\t\t\t\t\t\t\t// Cleanup process and resolve\n\t\t\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\t\t\tserver.close();\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\n\t\t\t// Start server\n\t\t\tconst server = http.createServer(h3.toNodeListener(app));\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tserver.once(\"listening\", () => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t\tserver.listen(args.port);\n\t\t\t});\n\n\t\t\tif (args.onListenCallback) {\n\t\t\t\targs.onListenCallback();\n\t\t\t}\n\t\t});\n\t}\n\n\tasync logout(): Promise<void> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\t// Remove all Prismic cookies, short ID, and Intercom hash\n\t\t// associated with the currently logged in user.\n\t\tauthState.cookies = {};\n\t\tauthState.shortId = undefined;\n\t\tauthState.intercomHash = undefined;\n\n\t\tawait this._writePersistedAuthState(authState);\n\t}\n\n\tasync checkIsLoggedIn(): Promise<boolean> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\tconst url = new URL(\"./validate\", API_ENDPOINTS.PrismicAuthentication);\n\t\t\turl.searchParams.set(\"token\", authState.cookies[AUTH_COOKIE_KEY]);\n\n\t\t\tlet res;\n\t\t\ttry {\n\t\t\t\tres = await fetch(url.toString(), {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"User-Agent\": SLICE_MACHINE_USER_AGENT,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\t// Noop, we return if `res` is not defined.\n\t\t\t}\n\n\t\t\tif (!res || !res.ok) {\n\t\t\t\tawait this.logout();\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync getAuthenticationCookies(): Promise<\n\t\tPrismicAuthState[\"cookies\"] &\n\t\t\tRequired<\n\t\t\t\tPick<\n\t\t\t\t\tPrismicAuthState[\"cookies\"],\n\t\t\t\t\ttypeof AUTH_COOKIE_KEY | typeof SESSION_COOKIE_KEY\n\t\t\t\t>\n\t\t\t>\n\t> {\n\t\tconst isLoggedIn = await this.checkIsLoggedIn();\n\n\t\tif (isLoggedIn) {\n\t\t\tconst authState = await this._readPersistedAuthState();\n\n\t\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\t\treturn authState.cookies;\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error(\"Not logged in.\");\n\t}\n\n\tasync getAuthenticationToken(): Promise<string> {\n\t\tconst cookies = await this.getAuthenticationCookies();\n\n\t\treturn cookies[AUTH_COOKIE_KEY];\n\t}\n\n\tasync refreshAuthenticationToken(): Promise<void> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\tconst url = new URL(\n\t\t\t\t\"./refreshtoken\",\n\t\t\t\tAPI_ENDPOINTS.PrismicAuthentication,\n\t\t\t);\n\t\t\turl.searchParams.set(\"token\", authState.cookies[AUTH_COOKIE_KEY]);\n\n\t\t\tconst res = await fetch(url.toString(), {\n\t\t\t\theaders: {\n\t\t\t\t\t\"User-Agent\": SLICE_MACHINE_USER_AGENT,\n\t\t\t\t},\n\t\t\t});\n\t\t\tconst text = await res.text();\n\n\t\t\tif (res.ok) {\n\t\t\t\tauthState.cookies[AUTH_COOKIE_KEY] = text;\n\n\t\t\t\tawait this._writePersistedAuthState(authState);\n\t\t\t} else {\n\t\t\t\tthrow new InternalError(\"Failed to refresh authentication token.\");\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new UnauthenticatedError();\n\t\t}\n\t}\n\n\tasync getProfile(): Promise<PrismicUserProfile> {\n\t\tconst authenticationToken = await this.getAuthenticationToken();\n\n\t\treturn await this._getProfileForAuthenticationToken({\n\t\t\tauthenticationToken,\n\t\t});\n\t}\n\n\tprivate async _getProfileForAuthenticationToken(\n\t\targs: GetProfileForAuthenticationTokenArgs,\n\t): Promise<PrismicUserProfile> {\n\t\tconst url = new URL(\"./profile\", API_ENDPOINTS.PrismicUser);\n\t\tconst res = await fetch(url.toString(), {\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${args.authenticationToken}`,\n\t\t\t\t\"User-Agent\": SLICE_MACHINE_USER_AGENT,\n\t\t\t},\n\t\t});\n\t\tconst json = await res.json();\n\n\t\tif (res.ok) {\n\t\t\tconst { value: profile, error } = decode(PrismicUserProfile, json);\n\n\t\t\tif (error) {\n\t\t\t\tthrow new UnexpectedDataError(\n\t\t\t\t\t\"Received invalid data from the Prismic user service.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn profile;\n\t\t} else {\n\t\t\tthrow new InternalError(\n\t\t\t\t\"Failed to retrieve profile from the Prismic user service.\",\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate async _readPersistedAuthState(): Promise<PrismicAuthState> {\n\t\tconst authStateFilePath = this._getPersistedAuthStateFilePath();\n\n\t\tlet authStateFileContents: string = JSON.stringify({});\n\t\tlet rawAuthState: Record<string, unknown> = {};\n\n\t\ttry {\n\t\t\tauthStateFileContents = await fs.readFile(authStateFilePath, \"utf8\");\n\t\t\trawAuthState = JSON.parse(authStateFileContents);\n\t\t} catch {\n\t\t\t// Write a default persisted state if it doesn't already exist.\n\n\t\t\trawAuthState = {\n\t\t\t\t...DEFAULT_PERSISTED_AUTH_STATE,\n\t\t\t\tcookies: serializeCookies(DEFAULT_PERSISTED_AUTH_STATE.cookies),\n\t\t\t};\n\t\t\tauthStateFileContents = JSON.stringify(rawAuthState, null, \"\\t\");\n\n\t\t\tawait fs.mkdir(path.dirname(authStateFilePath), { recursive: true });\n\t\t\tawait fs.writeFile(authStateFilePath, authStateFileContents);\n\t\t}\n\n\t\t// Decode cookies into a record for convenience.\n\t\tif (typeof rawAuthState.cookies === \"string\") {\n\t\t\trawAuthState.cookies = parseCookies(rawAuthState.cookies);\n\t\t}\n\n\t\tconst { value: authState, error } = decode(PrismicAuthState, rawAuthState);\n\n\t\tif (error) {\n\t\t\tthrow new UnexpectedDataError(\"Prismic authentication state is invalid.\");\n\t\t}\n\n\t\treturn authState;\n\t}\n\n\tprivate async _writePersistedAuthState(\n\t\tauthState: PrismicAuthState,\n\t): Promise<void> {\n\t\tconst authStateFilePath = this._getPersistedAuthStateFilePath();\n\n\t\tconst preparedAuthState = {\n\t\t\t...authState,\n\t\t\tcookies: serializeCookies(authState.cookies),\n\t\t};\n\n\t\ttry {\n\t\t\tawait fs.writeFile(\n\t\t\t\tauthStateFilePath,\n\t\t\t\tJSON.stringify(preparedAuthState, null, 2),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new InternalError(\n\t\t\t\t\"Failed to write Prismic authentication state to the file system.\",\n\t\t\t\t{\n\t\t\t\t\tcause: error,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate _getPersistedAuthStateFilePath(): string {\n\t\treturn path.resolve(this.scopedDirectory, PERSISTED_AUTH_STATE_FILE_NAME);\n\t}\n}\n"],"names":["getPort","resolve"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAE3B,MAAM,iCAAiC;AACvC,MAAM,+BAAiD;AAAA,EACtD,MAAM;AAAA,EACN,SAAS,CAAE;;AAGZ,MAAM,mBAAmB,EAAE,aAAa;AAAA,EACvC,EAAE,KAAK;AAAA,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A,UAAU,aAAa,aAAa,OAAO;AAAA,IACxD;AAED,UAAM,EAAE,OAAO,WAAW,MAAU,IAAA,OAAO,kBAAkB,YAAY;AAEzE,QAAI,OAAO;AACJ,YAAA,IAAI,oBAAoB,0CAA0C;AAAA,IACxE;AAEM,WAAA;AAAA,EACR;AAAA,EAEQ,MAAM,yBACb,WAA2B;AAErB,UAAA,oBAAoB,KAAK;AAE/B,UAAM,oBAAoB;AAAA,MACzB,GAAG;AAAA,MACH,SAAS,iBAAiB,UAAU,OAAO;AAAA,IAAA;AAGxC,QAAA;AACG,YAAA,GAAG,UACR,mBACA,KAAK,UAAU,mBAAmB,MAAM,CAAC,CAAC;AAAA,aAEnC;AACF,YAAA,IAAI,cACT,oEACA;AAAA,QACC,OAAO;AAAA,MAAA,CACP;AAAA,IAEF;AAAA,EACF;AAAA,EAEQ,iCAA8B;AACrC,WAAO,KAAK,QAAQ,KAAK,iBAAiB,8BAA8B;AAAA,EACzE;AACA;"}
|
|
1
|
+
{"version":3,"file":"PrismicAuthManager.js","sources":["../../../src/auth/PrismicAuthManager.ts"],"sourcesContent":["import * as t from \"io-ts\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport * as os from \"node:os\";\nimport * as http from \"node:http\";\n\nimport * as h3 from \"h3\";\nimport fetch from \"../lib/fetch\";\nimport cookie from \"cookie\";\nimport cors from \"cors\";\nimport getPort from \"get-port\";\n\nimport { decode } from \"../lib/decode\";\nimport { serializeCookies } from \"../lib/serializeCookies\";\n\nimport { API_ENDPOINTS } from \"../constants/API_ENDPOINTS\";\nimport { SLICE_MACHINE_USER_AGENT } from \"../constants/SLICE_MACHINE_USER_AGENT\";\nimport { createPrismicAuthManagerMiddleware } from \"./createPrismicAuthManagerMiddleware\";\nimport {\n\tInternalError,\n\tUnauthenticatedError,\n\tUnexpectedDataError,\n} from \"../errors\";\n\nconst COOKIE_SEPARATOR = \"; \";\nconst AUTH_COOKIE_KEY = \"prismic-auth\";\nconst SESSION_COOKIE_KEY = \"SESSION\";\n\nconst PERSISTED_AUTH_STATE_FILE_NAME = \".prismic\";\nconst DEFAULT_PERSISTED_AUTH_STATE: PrismicAuthState = {\n\tbase: \"https://prismic.io\",\n\tcookies: {},\n};\n\nconst PrismicAuthState = t.intersection([\n\tt.type({\n\t\tbase: t.string,\n\t\tcookies: t.intersection([\n\t\t\tt.partial({\n\t\t\t\t[AUTH_COOKIE_KEY]: t.string,\n\t\t\t\tSESSION: t.string,\n\t\t\t}),\n\t\t\tt.record(t.string, t.string),\n\t\t]),\n\t}),\n\tt.partial({\n\t\tshortId: t.string,\n\t\tintercomHash: t.string,\n\t\toauthAccessToken: t.string,\n\t\tauthUrl: t.string,\n\t}),\n]);\nexport type PrismicAuthState = t.TypeOf<typeof PrismicAuthState>;\n\nconst PrismicUserProfile = t.exact(\n\tt.type({\n\t\tuserId: t.string,\n\t\tshortId: t.string,\n\t\tintercomHash: t.string,\n\t\temail: t.string,\n\t\tfirstName: t.string,\n\t\tlastName: t.string,\n\t}),\n);\nexport type PrismicUserProfile = t.TypeOf<typeof PrismicUserProfile>;\n\ntype PrismicAuthManagerConstructorArgs = {\n\tscopedDirectory?: string;\n};\n\ntype PrismicAuthManagerLoginArgs = {\n\temail: string;\n\tcookies: string[];\n};\n\ntype PrismicAuthManagerGetLoginSessionInfoReturnType = {\n\tport: number;\n\turl: string;\n};\n\ntype PrismicAuthManagerNodeLoginSessionArgs = {\n\tport: number;\n\tonListenCallback?: () => void;\n};\n\ntype GetProfileForAuthenticationTokenArgs = {\n\tauthenticationToken: string;\n};\n\nconst checkHasAuthenticationToken = (\n\tauthState: PrismicAuthState,\n): authState is PrismicAuthState & {\n\tcookies: Required<\n\t\tPick<\n\t\t\tPrismicAuthState[\"cookies\"],\n\t\t\ttypeof AUTH_COOKIE_KEY | typeof SESSION_COOKIE_KEY\n\t\t>\n\t>;\n} => {\n\treturn Boolean(\n\t\tauthState.cookies[AUTH_COOKIE_KEY] && authState.cookies[SESSION_COOKIE_KEY],\n\t);\n};\n\nconst parseCookies = (cookies: string): Record<string, string> => {\n\treturn cookie.parse(cookies, {\n\t\t// Don't escape any values.\n\t\tdecode: (value) => value,\n\t});\n};\n\nexport class PrismicAuthManager {\n\t// TODO: Automatically scope the manager to the current Slice Machine\n\t// project? If not, this internal state can be removed.\n\tscopedDirectory: string;\n\n\tconstructor({\n\t\tscopedDirectory = os.homedir(),\n\t}: PrismicAuthManagerConstructorArgs = {}) {\n\t\tthis.scopedDirectory = scopedDirectory;\n\t}\n\n\t// TODO: Make the `cookies` argument more explicit. What are these\n\t// mysterious cookies?\n\tasync login(args: PrismicAuthManagerLoginArgs): Promise<void> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\t// Set the auth's URL base to the current base at runtime.\n\t\tauthState.base = API_ENDPOINTS.PrismicWroom;\n\t\tauthState.cookies = {\n\t\t\t...authState.cookies,\n\t\t\t...parseCookies(args.cookies.join(COOKIE_SEPARATOR)),\n\t\t};\n\n\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\tconst authenticationToken = authState.cookies[AUTH_COOKIE_KEY];\n\t\t\tconst profile = await this._getProfileForAuthenticationToken({\n\t\t\t\tauthenticationToken,\n\t\t\t});\n\n\t\t\tauthState.shortId = profile.shortId;\n\t\t\tauthState.intercomHash = profile.intercomHash;\n\t\t}\n\n\t\tawait this._writePersistedAuthState(authState);\n\t}\n\n\tasync getLoginSessionInfo(): Promise<PrismicAuthManagerGetLoginSessionInfoReturnType> {\n\t\t// Pick a random port, with a preference for historic `5555`\n\t\tconst port = await getPort({ port: 5555 });\n\n\t\tconst url = new URL(\n\t\t\t`./dashboard/cli/login?source=slice-machine&port=${port}`,\n\t\t\tAPI_ENDPOINTS.PrismicWroom,\n\t\t).toString();\n\n\t\treturn {\n\t\t\tport,\n\t\t\turl,\n\t\t};\n\t}\n\n\tasync nodeLoginSession(\n\t\targs: PrismicAuthManagerNodeLoginSessionArgs,\n\t): Promise<void> {\n\t\treturn new Promise<void>(async (resolve) => {\n\t\t\t// Timeout attempt after 3 minutes\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tserver.close();\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Login timeout, server did not receive a response within a 3-minute delay\",\n\t\t\t\t);\n\t\t\t}, 180_000);\n\n\t\t\tconst app = h3.createApp();\n\t\t\tapp.use(h3.fromNodeMiddleware(cors()));\n\t\t\tapp.use(\n\t\t\t\th3.fromNodeMiddleware(\n\t\t\t\t\tcreatePrismicAuthManagerMiddleware({\n\t\t\t\t\t\tprismicAuthManager: this,\n\t\t\t\t\t\tonLoginCallback() {\n\t\t\t\t\t\t\t// Cleanup process and resolve\n\t\t\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\t\t\tserver.close();\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\n\t\t\t// Start server\n\t\t\tconst server = http.createServer(h3.toNodeListener(app));\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tserver.once(\"listening\", () => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t\tserver.listen(args.port);\n\t\t\t});\n\n\t\t\tif (args.onListenCallback) {\n\t\t\t\targs.onListenCallback();\n\t\t\t}\n\t\t});\n\t}\n\n\tasync logout(): Promise<void> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\t// Remove all Prismic cookies, short ID, and Intercom hash\n\t\t// associated with the currently logged in user.\n\t\tauthState.cookies = {};\n\t\tauthState.shortId = undefined;\n\t\tauthState.intercomHash = undefined;\n\n\t\tawait this._writePersistedAuthState(authState);\n\t}\n\n\tasync checkIsLoggedIn(): Promise<boolean> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\tconst url = new URL(\"./validate\", API_ENDPOINTS.PrismicAuthentication);\n\t\t\turl.searchParams.set(\"token\", authState.cookies[AUTH_COOKIE_KEY]);\n\n\t\t\tlet res;\n\t\t\ttry {\n\t\t\t\tres = await fetch(url.toString(), {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"User-Agent\": SLICE_MACHINE_USER_AGENT,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\t// Noop, we return if `res` is not defined.\n\t\t\t}\n\n\t\t\tif (!res || !res.ok) {\n\t\t\t\tawait this.logout();\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync getAuthenticationCookies(): Promise<\n\t\tPrismicAuthState[\"cookies\"] &\n\t\t\tRequired<\n\t\t\t\tPick<\n\t\t\t\t\tPrismicAuthState[\"cookies\"],\n\t\t\t\t\ttypeof AUTH_COOKIE_KEY | typeof SESSION_COOKIE_KEY\n\t\t\t\t>\n\t\t\t>\n\t> {\n\t\tconst isLoggedIn = await this.checkIsLoggedIn();\n\n\t\tif (isLoggedIn) {\n\t\t\tconst authState = await this._readPersistedAuthState();\n\n\t\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\t\treturn authState.cookies;\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error(\"Not logged in.\");\n\t}\n\n\tasync getAuthenticationToken(): Promise<string> {\n\t\tconst cookies = await this.getAuthenticationCookies();\n\n\t\treturn cookies[AUTH_COOKIE_KEY];\n\t}\n\n\tasync refreshAuthenticationToken(): Promise<void> {\n\t\tconst authState = await this._readPersistedAuthState();\n\n\t\tif (checkHasAuthenticationToken(authState)) {\n\t\t\tconst url = new URL(\n\t\t\t\t\"./refreshtoken\",\n\t\t\t\tAPI_ENDPOINTS.PrismicAuthentication,\n\t\t\t);\n\t\t\turl.searchParams.set(\"token\", authState.cookies[AUTH_COOKIE_KEY]);\n\n\t\t\tconst res = await fetch(url.toString(), {\n\t\t\t\theaders: {\n\t\t\t\t\t\"User-Agent\": SLICE_MACHINE_USER_AGENT,\n\t\t\t\t},\n\t\t\t});\n\t\t\tconst text = await res.text();\n\n\t\t\tif (res.ok) {\n\t\t\t\tauthState.cookies[AUTH_COOKIE_KEY] = text;\n\n\t\t\t\tawait this._writePersistedAuthState(authState);\n\t\t\t} else {\n\t\t\t\tthrow new InternalError(\"Failed to refresh authentication token.\", {\n\t\t\t\t\tcause: text,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new UnauthenticatedError();\n\t\t}\n\t}\n\n\tasync getProfile(): Promise<PrismicUserProfile> {\n\t\tconst authenticationToken = await this.getAuthenticationToken();\n\n\t\treturn await this._getProfileForAuthenticationToken({\n\t\t\tauthenticationToken,\n\t\t});\n\t}\n\n\tprivate async _getProfileForAuthenticationToken(\n\t\targs: GetProfileForAuthenticationTokenArgs,\n\t): Promise<PrismicUserProfile> {\n\t\tconst url = new URL(\"./profile\", API_ENDPOINTS.PrismicUser);\n\t\tconst res = await fetch(url.toString(), {\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${args.authenticationToken}`,\n\t\t\t\t\"User-Agent\": SLICE_MACHINE_USER_AGENT,\n\t\t\t},\n\t\t});\n\n\t\tif (res.ok) {\n\t\t\tconst json = await res.json();\n\t\t\tconst { value: profile, error } = decode(PrismicUserProfile, json);\n\n\t\t\tif (error) {\n\t\t\t\tthrow new UnexpectedDataError(\n\t\t\t\t\t\"Received invalid data from the Prismic user service.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn profile;\n\t\t} else {\n\t\t\tconst text = await res.text();\n\t\t\tthrow new InternalError(\n\t\t\t\t\"Failed to retrieve profile from the Prismic user service.\",\n\t\t\t\t{\n\t\t\t\t\tcause: text,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate async _readPersistedAuthState(): Promise<PrismicAuthState> {\n\t\tconst authStateFilePath = this._getPersistedAuthStateFilePath();\n\n\t\tlet authStateFileContents: string = JSON.stringify({});\n\t\tlet rawAuthState: Record<string, unknown> = {};\n\n\t\ttry {\n\t\t\tauthStateFileContents = await fs.readFile(authStateFilePath, \"utf8\");\n\t\t\trawAuthState = JSON.parse(authStateFileContents);\n\t\t} catch {\n\t\t\t// Write a default persisted state if it doesn't already exist.\n\n\t\t\trawAuthState = {\n\t\t\t\t...DEFAULT_PERSISTED_AUTH_STATE,\n\t\t\t\tcookies: serializeCookies(DEFAULT_PERSISTED_AUTH_STATE.cookies),\n\t\t\t};\n\t\t\tauthStateFileContents = JSON.stringify(rawAuthState, null, \"\\t\");\n\n\t\t\tawait fs.mkdir(path.dirname(authStateFilePath), { recursive: true });\n\t\t\tawait fs.writeFile(authStateFilePath, authStateFileContents);\n\t\t}\n\n\t\t// Decode cookies into a record for convenience.\n\t\tif (typeof rawAuthState.cookies === \"string\") {\n\t\t\trawAuthState.cookies = parseCookies(rawAuthState.cookies);\n\t\t}\n\n\t\tconst { value: authState, error } = decode(PrismicAuthState, rawAuthState);\n\n\t\tif (error) {\n\t\t\tthrow new UnexpectedDataError(\"Prismic authentication state is invalid.\");\n\t\t}\n\n\t\treturn authState;\n\t}\n\n\tprivate async _writePersistedAuthState(\n\t\tauthState: PrismicAuthState,\n\t): Promise<void> {\n\t\tconst authStateFilePath = this._getPersistedAuthStateFilePath();\n\n\t\tconst preparedAuthState = {\n\t\t\t...authState,\n\t\t\tcookies: serializeCookies(authState.cookies),\n\t\t};\n\n\t\ttry {\n\t\t\tawait fs.writeFile(\n\t\t\t\tauthStateFilePath,\n\t\t\t\tJSON.stringify(preparedAuthState, null, 2),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new InternalError(\n\t\t\t\t\"Failed to write Prismic authentication state to the file system.\",\n\t\t\t\t{\n\t\t\t\t\tcause: error,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate _getPersistedAuthStateFilePath(): string {\n\t\treturn path.resolve(this.scopedDirectory, PERSISTED_AUTH_STATE_FILE_NAME);\n\t}\n}\n"],"names":["getPort","resolve"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwBA,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A;AAAA,QACd,GAAG;AAAA,QACH,SAAS,iBAAiB,6BAA6B,OAAO;AAAA,MAAA;AAE/D,8BAAwB,KAAK,UAAU,cAAc,MAAM,GAAI;AAEzD,YAAA,GAAG,MAAM,KAAK,QAAQ,iBAAiB,GAAG,EAAE,WAAW,KAAA,CAAM;AAC7D,YAAA,GAAG,UAAU,mBAAmB,qBAAqB;AAAA,IAC3D;AAGG,QAAA,OAAO,aAAa,YAAY,UAAU;AAChC,mBAAA,UAAU,aAAa,aAAa,OAAO;AAAA,IACxD;AAED,UAAM,EAAE,OAAO,WAAW,MAAU,IAAA,OAAO,kBAAkB,YAAY;AAEzE,QAAI,OAAO;AACJ,YAAA,IAAI,oBAAoB,0CAA0C;AAAA,IACxE;AAEM,WAAA;AAAA,EACR;AAAA,EAEQ,MAAM,yBACb,WAA2B;AAErB,UAAA,oBAAoB,KAAK;AAE/B,UAAM,oBAAoB;AAAA,MACzB,GAAG;AAAA,MACH,SAAS,iBAAiB,UAAU,OAAO;AAAA,IAAA;AAGxC,QAAA;AACG,YAAA,GAAG,UACR,mBACA,KAAK,UAAU,mBAAmB,MAAM,CAAC,CAAC;AAAA,aAEnC;AACF,YAAA,IAAI,cACT,oEACA;AAAA,QACC,OAAO;AAAA,MAAA,CACP;AAAA,IAEF;AAAA,EACF;AAAA,EAEQ,iCAA8B;AACrC,WAAO,KAAK,QAAQ,KAAK,iBAAiB,8BAA8B;AAAA,EACzE;AACA;"}
|
|
@@ -40,7 +40,10 @@ const fetchAllGitHubReleases = async (args) => {
|
|
|
40
40
|
}
|
|
41
41
|
return value;
|
|
42
42
|
} else {
|
|
43
|
-
|
|
43
|
+
const text = await res.text();
|
|
44
|
+
throw new Error(`Invalid GitHub Release response.`, {
|
|
45
|
+
cause: text
|
|
46
|
+
});
|
|
44
47
|
}
|
|
45
48
|
};
|
|
46
49
|
const fetchGitHubReleaseByVersion = async (args) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetchGitHubReleaseBodyForRelease.cjs","sources":["../../../src/lib/fetchGitHubReleaseBodyForRelease.ts"],"sourcesContent":["import * as t from \"io-ts\";\nimport fetch from \"./fetch\";\nimport pLimit from \"p-limit\";\n\nimport { decode } from \"./decode\";\n\nconst GITHUB_JSON_ACCEPT_HEADER = \"application/vnd.github+json\";\n\n/**\n * A minimally defined codec for GitHub release metadata.\n *\n * @see https://docs.github.com/en/rest/releases/releases#get-a-release-by-tag-name\n */\nconst GitHubReleaseMetadata = t.type({\n\tname: t.string,\n\tbody: t.union([t.null, t.string]),\n});\nexport type GitHubReleaseMetadata = t.TypeOf<typeof GitHubReleaseMetadata>;\n\ntype FetchAllGitHubReleasesArgs = {\n\trepositoryOwner: string;\n\trepositoryName: string;\n};\n\nconst fetchAllGitHubReleases = async (\n\targs: FetchAllGitHubReleasesArgs,\n): Promise<GitHubReleaseMetadata[]> => {\n\tconst res = await fetch(\n\t\t`https://api.github.com/repos/${args.repositoryOwner}/${args.repositoryName}/releases`,\n\t\t{\n\t\t\theaders: {\n\t\t\t\tAccept: GITHUB_JSON_ACCEPT_HEADER,\n\t\t\t},\n\t\t},\n\t);\n\n\tif (res.ok) {\n\t\tconst json = await res.json();\n\n\t\tconst { value, error } = decode(t.array(GitHubReleaseMetadata), json);\n\n\t\tif (error) {\n\t\t\tthrow new Error(`Invalid GitHub Release response.`, { cause: error });\n\t\t}\n\n\t\treturn value;\n\t} else {\n\t\tthrow new Error(`Invalid GitHub Release response
|
|
1
|
+
{"version":3,"file":"fetchGitHubReleaseBodyForRelease.cjs","sources":["../../../src/lib/fetchGitHubReleaseBodyForRelease.ts"],"sourcesContent":["import * as t from \"io-ts\";\nimport fetch from \"./fetch\";\nimport pLimit from \"p-limit\";\n\nimport { decode } from \"./decode\";\n\nconst GITHUB_JSON_ACCEPT_HEADER = \"application/vnd.github+json\";\n\n/**\n * A minimally defined codec for GitHub release metadata.\n *\n * @see https://docs.github.com/en/rest/releases/releases#get-a-release-by-tag-name\n */\nconst GitHubReleaseMetadata = t.type({\n\tname: t.string,\n\tbody: t.union([t.null, t.string]),\n});\nexport type GitHubReleaseMetadata = t.TypeOf<typeof GitHubReleaseMetadata>;\n\ntype FetchAllGitHubReleasesArgs = {\n\trepositoryOwner: string;\n\trepositoryName: string;\n};\n\nconst fetchAllGitHubReleases = async (\n\targs: FetchAllGitHubReleasesArgs,\n): Promise<GitHubReleaseMetadata[]> => {\n\tconst res = await fetch(\n\t\t`https://api.github.com/repos/${args.repositoryOwner}/${args.repositoryName}/releases`,\n\t\t{\n\t\t\theaders: {\n\t\t\t\tAccept: GITHUB_JSON_ACCEPT_HEADER,\n\t\t\t},\n\t\t},\n\t);\n\n\tif (res.ok) {\n\t\tconst json = await res.json();\n\n\t\tconst { value, error } = decode(t.array(GitHubReleaseMetadata), json);\n\n\t\tif (error) {\n\t\t\tthrow new Error(`Invalid GitHub Release response.`, { cause: error });\n\t\t}\n\n\t\treturn value;\n\t} else {\n\t\tconst text = await res.text();\n\t\tthrow new Error(`Invalid GitHub Release response.`, {\n\t\t\tcause: text,\n\t\t});\n\t}\n};\n\ntype FetchGitHubReleaseByVersionArgs = {\n\trepositoryOwner: string;\n\trepositoryName: string;\n\tpackageName?: string;\n\tversion: string;\n};\n\nconst fetchGitHubReleaseByVersion = async (\n\targs: FetchGitHubReleaseByVersionArgs,\n): Promise<GitHubReleaseMetadata | undefined> => {\n\tlet url: string;\n\n\tif (args.packageName) {\n\t\turl = `https://api.github.com/repos/${args.repositoryOwner}/${args.repositoryName}/releases/tags/${args.packageName}@${args.version}`;\n\t} else {\n\t\turl = `https://api.github.com/repos/${args.repositoryOwner}/${args.repositoryName}/releases/tags/${args.version}`;\n\t}\n\n\tconst res = await fetch(url, {\n\t\theaders: {\n\t\t\tAccept: GITHUB_JSON_ACCEPT_HEADER,\n\t\t},\n\t});\n\n\tif (res.ok) {\n\t\tconst json = await res.json();\n\n\t\tconst { value, error } = decode(GitHubReleaseMetadata, json);\n\n\t\tif (error) {\n\t\t\tthrow new Error(`Invalid GitHub Release response.`, { cause: error });\n\t\t}\n\n\t\treturn value;\n\t}\n};\n\ntype FetchGitHubReleaseBodyForReleaseArgs = {\n\trepositoryOwner: string;\n\trepositoryName: string;\n\tpackageName?: string;\n\tversion: string;\n\tcache?: Record<string, GitHubReleaseMetadata | undefined>;\n};\n\nconst _fetchGitHubReleaseBodyForRelease = async (\n\targs: FetchGitHubReleaseBodyForReleaseArgs,\n): Promise<string | undefined> => {\n\tconst cache = args.cache || {};\n\n\tif (Object.keys(cache).length < 1) {\n\t\tconst releases = await fetchAllGitHubReleases({\n\t\t\trepositoryOwner: args.repositoryOwner,\n\t\t\trepositoryName: args.repositoryName,\n\t\t});\n\n\t\tfor (const release of releases) {\n\t\t\tcache[release.name] = release;\n\t\t}\n\t}\n\n\tif (args.version in cache) {\n\t\tconst release = cache[args.version];\n\n\t\treturn release?.body ?? undefined;\n\t} else {\n\t\ttry {\n\t\t\tconst version = await fetchGitHubReleaseByVersion({\n\t\t\t\trepositoryOwner: args.repositoryOwner,\n\t\t\t\trepositoryName: args.repositoryName,\n\t\t\t\tpackageName: args.packageName,\n\t\t\t\tversion: args.version,\n\t\t\t});\n\n\t\t\tcache[args.version] = version;\n\n\t\t\treturn version?.body ?? undefined;\n\t\t} catch {\n\t\t\tcache[args.version] = undefined;\n\n\t\t\treturn undefined;\n\t\t}\n\t}\n};\n\nconst limit = pLimit(1);\n\nexport const fetchGitHubReleaseBodyForRelease = async (\n\t...args: Parameters<typeof _fetchGitHubReleaseBodyForRelease>\n): ReturnType<typeof _fetchGitHubReleaseBodyForRelease> => {\n\treturn await limit(() => _fetchGitHubReleaseBodyForRelease(...args));\n};\n"],"names":["t","fetch","decode","pLimit"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAM,4BAA4B;AAOlC,MAAM,wBAAwBA,aAAE,KAAK;AAAA,EACpC,MAAMA,aAAE;AAAA,EACR,MAAMA,aAAE,MAAM,CAACA,aAAE,MAAMA,aAAE,MAAM,C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BAAuB;AAAA,MAC7C,iBAAiB,KAAK;AAAA,MACtB,gBAAgB,KAAK;AAAA,IAAA,CACrB;AAED,eAAW,WAAW,UAAU;AACzB,YAAA,QAAQ,IAAI,IAAI;AAAA,IACtB;AAAA,EACD;AAEG,MAAA,KAAK,WAAW,OAAO;AACpB,UAAA,UAAU,MAAM,KAAK,OAAO;AAElC,YAAO,mCAAS,SAAQ;AAAA,EAAA,OAClB;AACF,QAAA;AACG,YAAA,UAAU,MAAM,4BAA4B;AAAA,QACjD,iBAAiB,KAAK;AAAA,QACtB,gBAAgB,KAAK;AAAA,QACrB,aAAa,KAAK;AAAA,QAClB,SAAS,KAAK;AAAA,MAAA,CACd;AAEK,YAAA,KAAK,OAAO,IAAI;AAEtB,cAAO,mCAAS,SAAQ;AAAA,IAAA,QACvB;AACK,YAAA,KAAK,OAAO,IAAI;AAEf,aAAA;AAAA,IACP;AAAA,EACD;AACF;AAEA,MAAM,QAAQC,MAAO,CAAC;AAET,MAAA,mCAAmC,UAC5C,SACsD;AACzD,SAAO,MAAM,MAAM,MAAM,kCAAkC,GAAG,IAAI,CAAC;AACpE;;"}
|
|
@@ -21,7 +21,10 @@ const fetchAllGitHubReleases = async (args) => {
|
|
|
21
21
|
}
|
|
22
22
|
return value;
|
|
23
23
|
} else {
|
|
24
|
-
|
|
24
|
+
const text = await res.text();
|
|
25
|
+
throw new Error(`Invalid GitHub Release response.`, {
|
|
26
|
+
cause: text
|
|
27
|
+
});
|
|
25
28
|
}
|
|
26
29
|
};
|
|
27
30
|
const fetchGitHubReleaseByVersion = async (args) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetchGitHubReleaseBodyForRelease.js","sources":["../../../src/lib/fetchGitHubReleaseBodyForRelease.ts"],"sourcesContent":["import * as t from \"io-ts\";\nimport fetch from \"./fetch\";\nimport pLimit from \"p-limit\";\n\nimport { decode } from \"./decode\";\n\nconst GITHUB_JSON_ACCEPT_HEADER = \"application/vnd.github+json\";\n\n/**\n * A minimally defined codec for GitHub release metadata.\n *\n * @see https://docs.github.com/en/rest/releases/releases#get-a-release-by-tag-name\n */\nconst GitHubReleaseMetadata = t.type({\n\tname: t.string,\n\tbody: t.union([t.null, t.string]),\n});\nexport type GitHubReleaseMetadata = t.TypeOf<typeof GitHubReleaseMetadata>;\n\ntype FetchAllGitHubReleasesArgs = {\n\trepositoryOwner: string;\n\trepositoryName: string;\n};\n\nconst fetchAllGitHubReleases = async (\n\targs: FetchAllGitHubReleasesArgs,\n): Promise<GitHubReleaseMetadata[]> => {\n\tconst res = await fetch(\n\t\t`https://api.github.com/repos/${args.repositoryOwner}/${args.repositoryName}/releases`,\n\t\t{\n\t\t\theaders: {\n\t\t\t\tAccept: GITHUB_JSON_ACCEPT_HEADER,\n\t\t\t},\n\t\t},\n\t);\n\n\tif (res.ok) {\n\t\tconst json = await res.json();\n\n\t\tconst { value, error } = decode(t.array(GitHubReleaseMetadata), json);\n\n\t\tif (error) {\n\t\t\tthrow new Error(`Invalid GitHub Release response.`, { cause: error });\n\t\t}\n\n\t\treturn value;\n\t} else {\n\t\tthrow new Error(`Invalid GitHub Release response
|
|
1
|
+
{"version":3,"file":"fetchGitHubReleaseBodyForRelease.js","sources":["../../../src/lib/fetchGitHubReleaseBodyForRelease.ts"],"sourcesContent":["import * as t from \"io-ts\";\nimport fetch from \"./fetch\";\nimport pLimit from \"p-limit\";\n\nimport { decode } from \"./decode\";\n\nconst GITHUB_JSON_ACCEPT_HEADER = \"application/vnd.github+json\";\n\n/**\n * A minimally defined codec for GitHub release metadata.\n *\n * @see https://docs.github.com/en/rest/releases/releases#get-a-release-by-tag-name\n */\nconst GitHubReleaseMetadata = t.type({\n\tname: t.string,\n\tbody: t.union([t.null, t.string]),\n});\nexport type GitHubReleaseMetadata = t.TypeOf<typeof GitHubReleaseMetadata>;\n\ntype FetchAllGitHubReleasesArgs = {\n\trepositoryOwner: string;\n\trepositoryName: string;\n};\n\nconst fetchAllGitHubReleases = async (\n\targs: FetchAllGitHubReleasesArgs,\n): Promise<GitHubReleaseMetadata[]> => {\n\tconst res = await fetch(\n\t\t`https://api.github.com/repos/${args.repositoryOwner}/${args.repositoryName}/releases`,\n\t\t{\n\t\t\theaders: {\n\t\t\t\tAccept: GITHUB_JSON_ACCEPT_HEADER,\n\t\t\t},\n\t\t},\n\t);\n\n\tif (res.ok) {\n\t\tconst json = await res.json();\n\n\t\tconst { value, error } = decode(t.array(GitHubReleaseMetadata), json);\n\n\t\tif (error) {\n\t\t\tthrow new Error(`Invalid GitHub Release response.`, { cause: error });\n\t\t}\n\n\t\treturn value;\n\t} else {\n\t\tconst text = await res.text();\n\t\tthrow new Error(`Invalid GitHub Release response.`, {\n\t\t\tcause: text,\n\t\t});\n\t}\n};\n\ntype FetchGitHubReleaseByVersionArgs = {\n\trepositoryOwner: string;\n\trepositoryName: string;\n\tpackageName?: string;\n\tversion: string;\n};\n\nconst fetchGitHubReleaseByVersion = async (\n\targs: FetchGitHubReleaseByVersionArgs,\n): Promise<GitHubReleaseMetadata | undefined> => {\n\tlet url: string;\n\n\tif (args.packageName) {\n\t\turl = `https://api.github.com/repos/${args.repositoryOwner}/${args.repositoryName}/releases/tags/${args.packageName}@${args.version}`;\n\t} else {\n\t\turl = `https://api.github.com/repos/${args.repositoryOwner}/${args.repositoryName}/releases/tags/${args.version}`;\n\t}\n\n\tconst res = await fetch(url, {\n\t\theaders: {\n\t\t\tAccept: GITHUB_JSON_ACCEPT_HEADER,\n\t\t},\n\t});\n\n\tif (res.ok) {\n\t\tconst json = await res.json();\n\n\t\tconst { value, error } = decode(GitHubReleaseMetadata, json);\n\n\t\tif (error) {\n\t\t\tthrow new Error(`Invalid GitHub Release response.`, { cause: error });\n\t\t}\n\n\t\treturn value;\n\t}\n};\n\ntype FetchGitHubReleaseBodyForReleaseArgs = {\n\trepositoryOwner: string;\n\trepositoryName: string;\n\tpackageName?: string;\n\tversion: string;\n\tcache?: Record<string, GitHubReleaseMetadata | undefined>;\n};\n\nconst _fetchGitHubReleaseBodyForRelease = async (\n\targs: FetchGitHubReleaseBodyForReleaseArgs,\n): Promise<string | undefined> => {\n\tconst cache = args.cache || {};\n\n\tif (Object.keys(cache).length < 1) {\n\t\tconst releases = await fetchAllGitHubReleases({\n\t\t\trepositoryOwner: args.repositoryOwner,\n\t\t\trepositoryName: args.repositoryName,\n\t\t});\n\n\t\tfor (const release of releases) {\n\t\t\tcache[release.name] = release;\n\t\t}\n\t}\n\n\tif (args.version in cache) {\n\t\tconst release = cache[args.version];\n\n\t\treturn release?.body ?? undefined;\n\t} else {\n\t\ttry {\n\t\t\tconst version = await fetchGitHubReleaseByVersion({\n\t\t\t\trepositoryOwner: args.repositoryOwner,\n\t\t\t\trepositoryName: args.repositoryName,\n\t\t\t\tpackageName: args.packageName,\n\t\t\t\tversion: args.version,\n\t\t\t});\n\n\t\t\tcache[args.version] = version;\n\n\t\t\treturn version?.body ?? undefined;\n\t\t} catch {\n\t\t\tcache[args.version] = undefined;\n\n\t\t\treturn undefined;\n\t\t}\n\t}\n};\n\nconst limit = pLimit(1);\n\nexport const fetchGitHubReleaseBodyForRelease = async (\n\t...args: Parameters<typeof _fetchGitHubReleaseBodyForRelease>\n): ReturnType<typeof _fetchGitHubReleaseBodyForRelease> => {\n\treturn await limit(() => _fetchGitHubReleaseBodyForRelease(...args));\n};\n"],"names":[],"mappings":";;;;AAMA,MAAM,4BAA4B;AAOlC,MAAM,wBAAwB,EAAE,KAAK;AAAA,EACpC,MAAM,EAAE;AAAA,EACR,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC;AAChC,CAAA;AAQD,MAAM,yBAAyB,OAC9B,SACqC;AACrC,QAAM,MAAM,MAAM,MACjB,gCAAgC,KAAK,mBAAmB,KAAK,2BAC7D;AAAA,IACC,SAAS;AAAA,MACR,QAAQ;AAAA,IACR;AAAA,EAAA,CACD;AAGF,MAAI,IAAI,IAAI;AACL,UAAA,OAAO,MAAM,IAAI;AAEjB,UAAA,E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AACF,QAAA;AACG,YAAA,UAAU,MAAM,4BAA4B;AAAA,QACjD,iBAAiB,KAAK;AAAA,QACtB,gBAAgB,KAAK;AAAA,QACrB,aAAa,KAAK;AAAA,QAClB,SAAS,KAAK;AAAA,MAAA,CACd;AAEK,YAAA,KAAK,OAAO,IAAI;AAEtB,cAAO,mCAAS,SAAQ;AAAA,IAAA,QACvB;AACK,YAAA,KAAK,OAAO,IAAI;AAEf,aAAA;AAAA,IACP;AAAA,EACD;AACF;AAEA,MAAM,QAAQ,OAAO,CAAC;AAET,MAAA,mCAAmC,UAC5C,SACsD;AACzD,SAAO,MAAM,MAAM,MAAM,kCAAkC,GAAG,IAAI,CAAC;AACpE;"}
|
|
@@ -19,7 +19,12 @@ const installDependencies = async (args) => {
|
|
|
19
19
|
commandArgs.push(...EXTRA_INSTALL_FLAGS[args.packageManager]);
|
|
20
20
|
const command = await ni.parseNi(args.packageManager, commandArgs);
|
|
21
21
|
if (!command) {
|
|
22
|
-
throw new Error("Failed to begin dependency installation (could not parse command)"
|
|
22
|
+
throw new Error("Failed to begin dependency installation (could not parse command)", {
|
|
23
|
+
cause: {
|
|
24
|
+
packageManager: args.packageManager,
|
|
25
|
+
dependencies: args.dependencies
|
|
26
|
+
}
|
|
27
|
+
});
|
|
23
28
|
}
|
|
24
29
|
const execaProcess = index.execaCommand(command, {
|
|
25
30
|
encoding: "utf-8",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"installDependencies.cjs","sources":["../../../src/lib/installDependencies.ts"],"sourcesContent":["import { parseNi } from \"@antfu/ni\";\nimport {\n\tExecaChildProcess,\n\texecaCommand,\n\tOptions as ExacaOptions,\n} from \"execa\";\n\nimport { PackageManager } from \"../types\";\n\nconst EXTRA_INSTALL_FLAGS: Record<PackageManager, string[]> = {\n\tnpm: [\"--color=always\", \"--loglevel=info\"], // Default: `--color=true --loglevel=notice`.\n\tpnpm: [], // Default: `--color=auto --loglevel=info`.\n\tyarn: [], // TODO: Add the correct options.\n\t\"yarn@berry\": [], // TODO: Add the correct options.\n\t\"pnpm@6\": [], // // TODO: Add the correct options.\n\tbun: [], // TODO: Add the correct options.\n};\n\ntype InstallDependenciesArgs = {\n\tpackageManager: PackageManager;\n\tdependencies: Record<string, string>;\n\tdev?: boolean;\n\texeca?: ExacaOptions;\n};\n\ntype InstallDependenciesReturnType = {\n\texecaProcess: ExecaChildProcess;\n};\n\nexport const installDependencies = async (\n\targs: InstallDependenciesArgs,\n): Promise<InstallDependenciesReturnType> => {\n\tconst commandArgs = Object.entries(args.dependencies).map(\n\t\t([pkg, range]) => `${pkg}@${range}`,\n\t);\n\n\tif (commandArgs.length && args.dev) {\n\t\tcommandArgs.unshift(\"-D\");\n\t}\n\n\tcommandArgs.push(...EXTRA_INSTALL_FLAGS[args.packageManager]);\n\n\tconst command = await parseNi(args.packageManager, commandArgs);\n\n\tif (!command) {\n\t\tthrow new Error(\n\t\t\t\"Failed to begin dependency installation (could not parse command)\",\n\t\t);\n\t}\n\n\tconst execaProcess = execaCommand(command, {\n\t\tencoding: \"utf-8\",\n\t\t...args.execa,\n\t});\n\n\treturn {\n\t\texecaProcess,\n\t};\n};\n"],"names":["parseNi","execaCommand"],"mappings":";;;;AASA,MAAM,sBAAwD;AAAA,EAC7D,KAAK,CAAC,kBAAkB,iBAAiB;AAAA,EACzC,MAAM,CAAE;AAAA,EACR,MAAM,CAAE;AAAA,EACR,cAAc,CAAE;AAAA,EAChB,UAAU,CAAE;AAAA,EACZ,KAAK,CAAE;AAAA;;AAcK,MAAA,sBAAsB,OAClC,SAC2C;AAC3C,QAAM,cAAc,OAAO,QAAQ,KAAK,YAAY,EAAE,IACrD,CAAC,CAAC,KAAK,KAAK,MAAM,GAAG,OAAO,OAAO;AAGhC,MAAA,YAAY,UAAU,KAAK,KAAK;AACnC,gBAAY,QAAQ,IAAI;AAAA,EACxB;AAED,cAAY,KAAK,GAAG,oBAAoB,KAAK,cAAc,CAAC;AAE5D,QAAM,UAAU,MAAMA,GAAQ,QAAA,KAAK,gBAAgB,WAAW;AAE9D,MAAI,CAAC,SAAS;AACP,UAAA,IAAI,MACT,
|
|
1
|
+
{"version":3,"file":"installDependencies.cjs","sources":["../../../src/lib/installDependencies.ts"],"sourcesContent":["import { parseNi } from \"@antfu/ni\";\nimport {\n\tExecaChildProcess,\n\texecaCommand,\n\tOptions as ExacaOptions,\n} from \"execa\";\n\nimport { PackageManager } from \"../types\";\n\nconst EXTRA_INSTALL_FLAGS: Record<PackageManager, string[]> = {\n\tnpm: [\"--color=always\", \"--loglevel=info\"], // Default: `--color=true --loglevel=notice`.\n\tpnpm: [], // Default: `--color=auto --loglevel=info`.\n\tyarn: [], // TODO: Add the correct options.\n\t\"yarn@berry\": [], // TODO: Add the correct options.\n\t\"pnpm@6\": [], // // TODO: Add the correct options.\n\tbun: [], // TODO: Add the correct options.\n};\n\ntype InstallDependenciesArgs = {\n\tpackageManager: PackageManager;\n\tdependencies: Record<string, string>;\n\tdev?: boolean;\n\texeca?: ExacaOptions;\n};\n\ntype InstallDependenciesReturnType = {\n\texecaProcess: ExecaChildProcess;\n};\n\nexport const installDependencies = async (\n\targs: InstallDependenciesArgs,\n): Promise<InstallDependenciesReturnType> => {\n\tconst commandArgs = Object.entries(args.dependencies).map(\n\t\t([pkg, range]) => `${pkg}@${range}`,\n\t);\n\n\tif (commandArgs.length && args.dev) {\n\t\tcommandArgs.unshift(\"-D\");\n\t}\n\n\tcommandArgs.push(...EXTRA_INSTALL_FLAGS[args.packageManager]);\n\n\tconst command = await parseNi(args.packageManager, commandArgs);\n\n\tif (!command) {\n\t\tthrow new Error(\n\t\t\t\"Failed to begin dependency installation (could not parse command)\",\n\t\t\t{\n\t\t\t\tcause: {\n\t\t\t\t\tpackageManager: args.packageManager,\n\t\t\t\t\tdependencies: args.dependencies,\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t}\n\n\tconst execaProcess = execaCommand(command, {\n\t\tencoding: \"utf-8\",\n\t\t...args.execa,\n\t});\n\n\treturn {\n\t\texecaProcess,\n\t};\n};\n"],"names":["parseNi","execaCommand"],"mappings":";;;;AASA,MAAM,sBAAwD;AAAA,EAC7D,KAAK,CAAC,kBAAkB,iBAAiB;AAAA,EACzC,MAAM,CAAE;AAAA,EACR,MAAM,CAAE;AAAA,EACR,cAAc,CAAE;AAAA,EAChB,UAAU,CAAE;AAAA,EACZ,KAAK,CAAE;AAAA;;AAcK,MAAA,sBAAsB,OAClC,SAC2C;AAC3C,QAAM,cAAc,OAAO,QAAQ,KAAK,YAAY,EAAE,IACrD,CAAC,CAAC,KAAK,KAAK,MAAM,GAAG,OAAO,OAAO;AAGhC,MAAA,YAAY,UAAU,KAAK,KAAK;AACnC,gBAAY,QAAQ,IAAI;AAAA,EACxB;AAED,cAAY,KAAK,GAAG,oBAAoB,KAAK,cAAc,CAAC;AAE5D,QAAM,UAAU,MAAMA,GAAQ,QAAA,KAAK,gBAAgB,WAAW;AAE9D,MAAI,CAAC,SAAS;AACP,UAAA,IAAI,MACT,qEACA;AAAA,MACC,OAAO;AAAA,QACN,gBAAgB,KAAK;AAAA,QACrB,cAAc,KAAK;AAAA,MACnB;AAAA,IAAA,CACD;AAAA,EAEF;AAEK,QAAA,eAAeC,mBAAa,SAAS;AAAA,IAC1C,UAAU;AAAA,IACV,GAAG,KAAK;AAAA,EAAA,CACR;AAEM,SAAA;AAAA,IACN;AAAA,EAAA;AAEF;;"}
|
|
@@ -17,7 +17,12 @@ const installDependencies = async (args) => {
|
|
|
17
17
|
commandArgs.push(...EXTRA_INSTALL_FLAGS[args.packageManager]);
|
|
18
18
|
const command = await parseNi(args.packageManager, commandArgs);
|
|
19
19
|
if (!command) {
|
|
20
|
-
throw new Error("Failed to begin dependency installation (could not parse command)"
|
|
20
|
+
throw new Error("Failed to begin dependency installation (could not parse command)", {
|
|
21
|
+
cause: {
|
|
22
|
+
packageManager: args.packageManager,
|
|
23
|
+
dependencies: args.dependencies
|
|
24
|
+
}
|
|
25
|
+
});
|
|
21
26
|
}
|
|
22
27
|
const execaProcess = execaCommand(command, {
|
|
23
28
|
encoding: "utf-8",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"installDependencies.js","sources":["../../../src/lib/installDependencies.ts"],"sourcesContent":["import { parseNi } from \"@antfu/ni\";\nimport {\n\tExecaChildProcess,\n\texecaCommand,\n\tOptions as ExacaOptions,\n} from \"execa\";\n\nimport { PackageManager } from \"../types\";\n\nconst EXTRA_INSTALL_FLAGS: Record<PackageManager, string[]> = {\n\tnpm: [\"--color=always\", \"--loglevel=info\"], // Default: `--color=true --loglevel=notice`.\n\tpnpm: [], // Default: `--color=auto --loglevel=info`.\n\tyarn: [], // TODO: Add the correct options.\n\t\"yarn@berry\": [], // TODO: Add the correct options.\n\t\"pnpm@6\": [], // // TODO: Add the correct options.\n\tbun: [], // TODO: Add the correct options.\n};\n\ntype InstallDependenciesArgs = {\n\tpackageManager: PackageManager;\n\tdependencies: Record<string, string>;\n\tdev?: boolean;\n\texeca?: ExacaOptions;\n};\n\ntype InstallDependenciesReturnType = {\n\texecaProcess: ExecaChildProcess;\n};\n\nexport const installDependencies = async (\n\targs: InstallDependenciesArgs,\n): Promise<InstallDependenciesReturnType> => {\n\tconst commandArgs = Object.entries(args.dependencies).map(\n\t\t([pkg, range]) => `${pkg}@${range}`,\n\t);\n\n\tif (commandArgs.length && args.dev) {\n\t\tcommandArgs.unshift(\"-D\");\n\t}\n\n\tcommandArgs.push(...EXTRA_INSTALL_FLAGS[args.packageManager]);\n\n\tconst command = await parseNi(args.packageManager, commandArgs);\n\n\tif (!command) {\n\t\tthrow new Error(\n\t\t\t\"Failed to begin dependency installation (could not parse command)\",\n\t\t);\n\t}\n\n\tconst execaProcess = execaCommand(command, {\n\t\tencoding: \"utf-8\",\n\t\t...args.execa,\n\t});\n\n\treturn {\n\t\texecaProcess,\n\t};\n};\n"],"names":[],"mappings":";;AASA,MAAM,sBAAwD;AAAA,EAC7D,KAAK,CAAC,kBAAkB,iBAAiB;AAAA,EACzC,MAAM,CAAE;AAAA,EACR,MAAM,CAAE;AAAA,EACR,cAAc,CAAE;AAAA,EAChB,UAAU,CAAE;AAAA,EACZ,KAAK,CAAE;AAAA;;AAcK,MAAA,sBAAsB,OAClC,SAC2C;AAC3C,QAAM,cAAc,OAAO,QAAQ,KAAK,YAAY,EAAE,IACrD,CAAC,CAAC,KAAK,KAAK,MAAM,GAAG,OAAO,OAAO;AAGhC,MAAA,YAAY,UAAU,KAAK,KAAK;AACnC,gBAAY,QAAQ,IAAI;AAAA,EACxB;AAED,cAAY,KAAK,GAAG,oBAAoB,KAAK,cAAc,CAAC;AAE5D,QAAM,UAAU,MAAM,QAAQ,KAAK,gBAAgB,WAAW;AAE9D,MAAI,CAAC,SAAS;AACP,UAAA,IAAI,MACT,
|
|
1
|
+
{"version":3,"file":"installDependencies.js","sources":["../../../src/lib/installDependencies.ts"],"sourcesContent":["import { parseNi } from \"@antfu/ni\";\nimport {\n\tExecaChildProcess,\n\texecaCommand,\n\tOptions as ExacaOptions,\n} from \"execa\";\n\nimport { PackageManager } from \"../types\";\n\nconst EXTRA_INSTALL_FLAGS: Record<PackageManager, string[]> = {\n\tnpm: [\"--color=always\", \"--loglevel=info\"], // Default: `--color=true --loglevel=notice`.\n\tpnpm: [], // Default: `--color=auto --loglevel=info`.\n\tyarn: [], // TODO: Add the correct options.\n\t\"yarn@berry\": [], // TODO: Add the correct options.\n\t\"pnpm@6\": [], // // TODO: Add the correct options.\n\tbun: [], // TODO: Add the correct options.\n};\n\ntype InstallDependenciesArgs = {\n\tpackageManager: PackageManager;\n\tdependencies: Record<string, string>;\n\tdev?: boolean;\n\texeca?: ExacaOptions;\n};\n\ntype InstallDependenciesReturnType = {\n\texecaProcess: ExecaChildProcess;\n};\n\nexport const installDependencies = async (\n\targs: InstallDependenciesArgs,\n): Promise<InstallDependenciesReturnType> => {\n\tconst commandArgs = Object.entries(args.dependencies).map(\n\t\t([pkg, range]) => `${pkg}@${range}`,\n\t);\n\n\tif (commandArgs.length && args.dev) {\n\t\tcommandArgs.unshift(\"-D\");\n\t}\n\n\tcommandArgs.push(...EXTRA_INSTALL_FLAGS[args.packageManager]);\n\n\tconst command = await parseNi(args.packageManager, commandArgs);\n\n\tif (!command) {\n\t\tthrow new Error(\n\t\t\t\"Failed to begin dependency installation (could not parse command)\",\n\t\t\t{\n\t\t\t\tcause: {\n\t\t\t\t\tpackageManager: args.packageManager,\n\t\t\t\t\tdependencies: args.dependencies,\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t}\n\n\tconst execaProcess = execaCommand(command, {\n\t\tencoding: \"utf-8\",\n\t\t...args.execa,\n\t});\n\n\treturn {\n\t\texecaProcess,\n\t};\n};\n"],"names":[],"mappings":";;AASA,MAAM,sBAAwD;AAAA,EAC7D,KAAK,CAAC,kBAAkB,iBAAiB;AAAA,EACzC,MAAM,CAAE;AAAA,EACR,MAAM,CAAE;AAAA,EACR,cAAc,CAAE;AAAA,EAChB,UAAU,CAAE;AAAA,EACZ,KAAK,CAAE;AAAA;;AAcK,MAAA,sBAAsB,OAClC,SAC2C;AAC3C,QAAM,cAAc,OAAO,QAAQ,KAAK,YAAY,EAAE,IACrD,CAAC,CAAC,KAAK,KAAK,MAAM,GAAG,OAAO,OAAO;AAGhC,MAAA,YAAY,UAAU,KAAK,KAAK;AACnC,gBAAY,QAAQ,IAAI;AAAA,EACxB;AAED,cAAY,KAAK,GAAG,oBAAoB,KAAK,cAAc,CAAC;AAE5D,QAAM,UAAU,MAAM,QAAQ,KAAK,gBAAgB,WAAW;AAE9D,MAAI,CAAC,SAAS;AACP,UAAA,IAAI,MACT,qEACA;AAAA,MACC,OAAO;AAAA,QACN,gBAAgB,KAAK;AAAA,QACrB,cAAc,KAAK;AAAA,MACnB;AAAA,IAAA,CACD;AAAA,EAEF;AAEK,QAAA,eAAe,aAAa,SAAS;AAAA,IAC1C,UAAU;AAAA,IACV,GAAG,KAAK;AAAA,EAAA,CACR;AAEM,SAAA;AAAA,IACN;AAAA,EAAA;AAEF;"}
|
|
@@ -129,7 +129,9 @@ class CustomTypesManager extends BaseManager.BaseManager {
|
|
|
129
129
|
if (error instanceof prismicCustomTypesClient__namespace.NotFoundError) {
|
|
130
130
|
await client.insertCustomType(model);
|
|
131
131
|
} else if (error instanceof prismicCustomTypesClient__namespace.ForbiddenError) {
|
|
132
|
-
throw new errors.UnauthorizedError("You do not have access to push types to this Prismic repository."
|
|
132
|
+
throw new errors.UnauthorizedError("You do not have access to push types to this Prismic repository.", {
|
|
133
|
+
cause: error
|
|
134
|
+
});
|
|
133
135
|
} else {
|
|
134
136
|
throw error;
|
|
135
137
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CustomTypesManager.cjs","sources":["../../../../src/managers/customTypes/CustomTypesManager.ts"],"sourcesContent":["import * as t from \"io-ts\";\nimport * as prismicCustomTypesClient from \"@prismicio/custom-types-client\";\nimport { CustomType } from \"@prismicio/types-internal/lib/customtypes\";\nimport {\n\tCallHookReturnType,\n\tCustomTypeCreateHook,\n\tCustomTypeCreateHookData,\n\tCustomTypeReadHookData,\n\tCustomTypeRenameHook,\n\tCustomTypeRenameHookData,\n\tCustomTypeUpdateHook,\n\tCustomTypeUpdateHookData,\n\tHookError,\n} from \"@slicemachine/plugin-kit\";\n\nimport { DecodeError } from \"../../lib/DecodeError\";\nimport { assertPluginsInitialized } from \"../../lib/assertPluginsInitialized\";\nimport { decodeHookResult } from \"../../lib/decodeHookResult\";\nimport fetch from \"../../lib/fetch\";\n\nimport { OnlyHookErrors } from \"../../types\";\nimport { API_ENDPOINTS } from \"../../constants/API_ENDPOINTS\";\nimport { SLICE_MACHINE_USER_AGENT } from \"../../constants/SLICE_MACHINE_USER_AGENT\";\nimport { UnauthorizedError } from \"../../errors\";\n\nimport { BaseManager } from \"../BaseManager\";\nimport { CustomTypeFormat } from \"./types\";\n\ntype SliceMachineManagerReadCustomTypeLibraryReturnType = {\n\tids: string[];\n\terrors: (DecodeError | HookError)[];\n};\n\ntype CustomTypesManagerReadAllCustomTypesArgs = {\n\tformat: CustomTypeFormat;\n};\n\ntype SliceMachineManagerReadAllCustomTypeReturnType = {\n\tmodels: { model: CustomType }[];\n\terrors: (DecodeError | HookError)[];\n};\n\ntype SliceMachineManagerReadCustomTypeReturnType = {\n\tmodel: CustomType | undefined;\n\terrors: (DecodeError | HookError)[];\n};\n\ntype SliceMachineManagerPushCustomTypeArgs = {\n\tid: string;\n\tuserAgent?: string;\n};\n\ntype SliceMachineManagerReadCustomTypeMocksConfigArgs = {\n\tcustomTypeID: string;\n};\n\ntype SliceMachineManagerReadCustomTypeMocksConfigArgsReturnType = {\n\t// TODO\n\tmocksConfig?: Record<string, unknown>;\n\terrors: HookError[];\n};\n\ntype SliceMachineManagerUpdateCustomTypeMocksConfigArgs = {\n\tcustomTypeID: string;\n\t// TODO\n\tmocksConfig: Record<string, unknown>;\n};\n\ntype SliceMachineManagerUpdateCustomTypeMocksConfigArgsReturnType = {\n\terrors: HookError[];\n};\n\ntype CustomTypesMachineManagerDeleteCustomTypeArgs = {\n\tid: string;\n};\n\ntype CustomTypesMachineManagerDeleteCustomTypeReturnType = {\n\terrors: (DecodeError | HookError)[];\n};\n\nexport class CustomTypesManager extends BaseManager {\n\tasync readCustomTypeLibrary(): Promise<SliceMachineManagerReadCustomTypeLibraryReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type-library:read\",\n\t\t\tundefined,\n\t\t);\n\t\tconst { data, errors } = decodeHookResult(\n\t\t\tt.type({\n\t\t\t\tids: t.array(t.string),\n\t\t\t}),\n\t\t\thookResult,\n\t\t);\n\n\t\treturn {\n\t\t\tids: data[0]?.ids || [],\n\t\t\terrors,\n\t\t};\n\t}\n\n\tasync readAllCustomTypes(\n\t\targs?: CustomTypesManagerReadAllCustomTypesArgs,\n\t): Promise<SliceMachineManagerReadAllCustomTypeReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst res: SliceMachineManagerReadAllCustomTypeReturnType = {\n\t\t\tmodels: [],\n\t\t\terrors: [],\n\t\t};\n\n\t\tconst { ids, errors } = await this.readCustomTypeLibrary();\n\t\tres.errors = [...res.errors, ...errors];\n\n\t\tif (ids) {\n\t\t\tfor (const id of ids) {\n\t\t\t\tconst { model, errors } = await this.readCustomType({ id });\n\t\t\t\tres.errors = [...res.errors, ...errors];\n\n\t\t\t\tif (model && (!args || args.format === model.format)) {\n\t\t\t\t\tres.models.push({ model });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tasync createCustomType(\n\t\targs: CustomTypeCreateHookData,\n\t): Promise<OnlyHookErrors<CallHookReturnType<CustomTypeCreateHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:create\",\n\t\t\targs,\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync readCustomType(\n\t\targs: CustomTypeReadHookData,\n\t): Promise<SliceMachineManagerReadCustomTypeReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:read\",\n\t\t\targs,\n\t\t);\n\t\tconst { data, errors } = decodeHookResult(\n\t\t\tt.type({\n\t\t\t\tmodel: CustomType,\n\t\t\t}),\n\t\t\thookResult,\n\t\t);\n\n\t\treturn {\n\t\t\tmodel: data[0]?.model,\n\t\t\terrors,\n\t\t};\n\t}\n\n\tasync updateCustomType(\n\t\targs: CustomTypeUpdateHookData,\n\t): Promise<OnlyHookErrors<CallHookReturnType<CustomTypeUpdateHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:update\",\n\t\t\targs,\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync renameCustomType(\n\t\targs: CustomTypeRenameHookData,\n\t): Promise<OnlyHookErrors<CallHookReturnType<CustomTypeRenameHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:rename\",\n\t\t\targs,\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync deleteCustomType(\n\t\targs: CustomTypesMachineManagerDeleteCustomTypeArgs,\n\t): Promise<CustomTypesMachineManagerDeleteCustomTypeReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst { model, errors: readCustomTypeErrors } = await this.readCustomType({\n\t\t\tid: args.id,\n\t\t});\n\n\t\tif (model) {\n\t\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\t\"custom-type:delete\",\n\t\t\t\t{ model },\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\terrors: hookResult.errors,\n\t\t\t};\n\t\t} else {\n\t\t\treturn {\n\t\t\t\terrors: readCustomTypeErrors,\n\t\t\t};\n\t\t}\n\t}\n\n\tasync pushCustomType(\n\t\targs: SliceMachineManagerPushCustomTypeArgs,\n\t): Promise<void> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst authenticationToken = await this.user.getAuthenticationToken();\n\t\tconst sliceMachineConfig = await this.project.getSliceMachineConfig();\n\n\t\t// TODO: Handle errors\n\t\tconst { model } = await this.readCustomType({ id: args.id });\n\n\t\tif (model) {\n\t\t\t// TODO: Create a single shared client.\n\t\t\tconst client = prismicCustomTypesClient.createClient({\n\t\t\t\tendpoint: API_ENDPOINTS.PrismicModels,\n\t\t\t\trepositoryName: sliceMachineConfig.repositoryName,\n\t\t\t\ttoken: authenticationToken,\n\t\t\t\tuserAgent: args.userAgent || SLICE_MACHINE_USER_AGENT,\n\t\t\t\tfetch,\n\t\t\t});\n\n\t\t\ttry {\n\t\t\t\t// Check if Custom Type already exists on the repository.\n\t\t\t\tawait client.getCustomTypeByID(args.id);\n\n\t\t\t\t// If it exists on the repository, update it.\n\t\t\t\tawait client.updateCustomType(model);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof prismicCustomTypesClient.NotFoundError) {\n\t\t\t\t\t// If it doesn't exist on the repository, insert it.\n\t\t\t\t\tawait client.insertCustomType(model);\n\t\t\t\t} else if (error instanceof prismicCustomTypesClient.ForbiddenError) {\n\t\t\t\t\tthrow new UnauthorizedError(\n\t\t\t\t\t\t\"You do not have access to push types to this Prismic repository.\",\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO: Remove\n\tasync readCustomTypeMocksConfig(\n\t\targs: SliceMachineManagerReadCustomTypeMocksConfigArgs,\n\t): Promise<SliceMachineManagerReadCustomTypeMocksConfigArgsReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:asset:read\",\n\t\t\t{\n\t\t\t\tcustomTypeID: args.customTypeID,\n\t\t\t\tassetID: \"mocks.config.json\",\n\t\t\t},\n\t\t);\n\t\tconst data = hookResult.data[0]?.data;\n\n\t\t// TODO: Validate the returned data.\n\n\t\tif (data) {\n\t\t\treturn {\n\t\t\t\tmocksConfig: JSON.parse(data.toString()),\n\t\t\t\terrors: hookResult.errors,\n\t\t\t};\n\t\t} else {\n\t\t\treturn {\n\t\t\t\tmocksConfig: undefined,\n\t\t\t\terrors: hookResult.errors,\n\t\t\t};\n\t\t}\n\t}\n\n\t// TODO: Remove\n\tasync updateCustomTypeMocksConfig(\n\t\targs: SliceMachineManagerUpdateCustomTypeMocksConfigArgs,\n\t): Promise<SliceMachineManagerUpdateCustomTypeMocksConfigArgsReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:asset:update\",\n\t\t\t{\n\t\t\t\tcustomTypeID: args.customTypeID,\n\t\t\t\tasset: {\n\t\t\t\t\tid: \"mocks.config.json\",\n\t\t\t\t\tdata: Buffer.from(JSON.stringify(args.mocksConfig, null, \"\\t\")),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync fetchRemoteCustomTypes(): Promise<CustomType[]> {\n\t\tconst authenticationToken = await this.user.getAuthenticationToken();\n\t\tconst sliceMachineConfig = await this.project.getSliceMachineConfig();\n\n\t\tconst client = prismicCustomTypesClient.createClient({\n\t\t\tendpoint: API_ENDPOINTS.PrismicModels,\n\t\t\trepositoryName: sliceMachineConfig.repositoryName,\n\t\t\ttoken: authenticationToken,\n\t\t\tuserAgent: SLICE_MACHINE_USER_AGENT,\n\t\t\tfetch,\n\t\t});\n\n\t\treturn await client.getAllCustomTypes();\n\t}\n}\n"],"names":["BaseManager","assertPluginsInitialized","errors","decodeHookResult","t","CustomType","prismicCustomTypesClient","API_ENDPOINTS","SLICE_MACHINE_USER_AGENT","fetch","UnauthorizedError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFM,MAAO,2BAA2BA,YAAAA,YAAW;AAAA,EAClD,MAAM,wBAAqB;;AAC1BC,sDAAyB,KAAK,wBAAwB;AAEtD,UAAM,aAAa,MAAM,KAAK,yBAAyB,SACtD,4BACA,MAAS;AAEV,UAAM,EAAE,MAAM,QAAAC,QAAA,IAAWC,iBAAAA,iBACxBC,aAAE,KAAK;AAAA,MACN,KAAKA,aAAE,MAAMA,aAAE,MAAM;AAAA,IAAA,CACrB,GACD,UAAU;AAGJ,WAAA;AAAA,MACN,OAAK,UAAK,CAAC,MAAN,mBAAS,Q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WAAWC,yBAAA;AAAA,MAAA,OACXC,MAAA;AAAA,IAAA,CACA;AAEM,WAAA,MAAM,OAAO;EACrB;AACA;;"}
|
|
1
|
+
{"version":3,"file":"CustomTypesManager.cjs","sources":["../../../../src/managers/customTypes/CustomTypesManager.ts"],"sourcesContent":["import * as t from \"io-ts\";\nimport * as prismicCustomTypesClient from \"@prismicio/custom-types-client\";\nimport { CustomType } from \"@prismicio/types-internal/lib/customtypes\";\nimport {\n\tCallHookReturnType,\n\tCustomTypeCreateHook,\n\tCustomTypeCreateHookData,\n\tCustomTypeReadHookData,\n\tCustomTypeRenameHook,\n\tCustomTypeRenameHookData,\n\tCustomTypeUpdateHook,\n\tCustomTypeUpdateHookData,\n\tHookError,\n} from \"@slicemachine/plugin-kit\";\n\nimport { DecodeError } from \"../../lib/DecodeError\";\nimport { assertPluginsInitialized } from \"../../lib/assertPluginsInitialized\";\nimport { decodeHookResult } from \"../../lib/decodeHookResult\";\nimport fetch from \"../../lib/fetch\";\n\nimport { OnlyHookErrors } from \"../../types\";\nimport { API_ENDPOINTS } from \"../../constants/API_ENDPOINTS\";\nimport { SLICE_MACHINE_USER_AGENT } from \"../../constants/SLICE_MACHINE_USER_AGENT\";\nimport { UnauthorizedError } from \"../../errors\";\n\nimport { BaseManager } from \"../BaseManager\";\nimport { CustomTypeFormat } from \"./types\";\n\ntype SliceMachineManagerReadCustomTypeLibraryReturnType = {\n\tids: string[];\n\terrors: (DecodeError | HookError)[];\n};\n\ntype CustomTypesManagerReadAllCustomTypesArgs = {\n\tformat: CustomTypeFormat;\n};\n\ntype SliceMachineManagerReadAllCustomTypeReturnType = {\n\tmodels: { model: CustomType }[];\n\terrors: (DecodeError | HookError)[];\n};\n\ntype SliceMachineManagerReadCustomTypeReturnType = {\n\tmodel: CustomType | undefined;\n\terrors: (DecodeError | HookError)[];\n};\n\ntype SliceMachineManagerPushCustomTypeArgs = {\n\tid: string;\n\tuserAgent?: string;\n};\n\ntype SliceMachineManagerReadCustomTypeMocksConfigArgs = {\n\tcustomTypeID: string;\n};\n\ntype SliceMachineManagerReadCustomTypeMocksConfigArgsReturnType = {\n\t// TODO\n\tmocksConfig?: Record<string, unknown>;\n\terrors: HookError[];\n};\n\ntype SliceMachineManagerUpdateCustomTypeMocksConfigArgs = {\n\tcustomTypeID: string;\n\t// TODO\n\tmocksConfig: Record<string, unknown>;\n};\n\ntype SliceMachineManagerUpdateCustomTypeMocksConfigArgsReturnType = {\n\terrors: HookError[];\n};\n\ntype CustomTypesMachineManagerDeleteCustomTypeArgs = {\n\tid: string;\n};\n\ntype CustomTypesMachineManagerDeleteCustomTypeReturnType = {\n\terrors: (DecodeError | HookError)[];\n};\n\nexport class CustomTypesManager extends BaseManager {\n\tasync readCustomTypeLibrary(): Promise<SliceMachineManagerReadCustomTypeLibraryReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type-library:read\",\n\t\t\tundefined,\n\t\t);\n\t\tconst { data, errors } = decodeHookResult(\n\t\t\tt.type({\n\t\t\t\tids: t.array(t.string),\n\t\t\t}),\n\t\t\thookResult,\n\t\t);\n\n\t\treturn {\n\t\t\tids: data[0]?.ids || [],\n\t\t\terrors,\n\t\t};\n\t}\n\n\tasync readAllCustomTypes(\n\t\targs?: CustomTypesManagerReadAllCustomTypesArgs,\n\t): Promise<SliceMachineManagerReadAllCustomTypeReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst res: SliceMachineManagerReadAllCustomTypeReturnType = {\n\t\t\tmodels: [],\n\t\t\terrors: [],\n\t\t};\n\n\t\tconst { ids, errors } = await this.readCustomTypeLibrary();\n\t\tres.errors = [...res.errors, ...errors];\n\n\t\tif (ids) {\n\t\t\tfor (const id of ids) {\n\t\t\t\tconst { model, errors } = await this.readCustomType({ id });\n\t\t\t\tres.errors = [...res.errors, ...errors];\n\n\t\t\t\tif (model && (!args || args.format === model.format)) {\n\t\t\t\t\tres.models.push({ model });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tasync createCustomType(\n\t\targs: CustomTypeCreateHookData,\n\t): Promise<OnlyHookErrors<CallHookReturnType<CustomTypeCreateHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:create\",\n\t\t\targs,\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync readCustomType(\n\t\targs: CustomTypeReadHookData,\n\t): Promise<SliceMachineManagerReadCustomTypeReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:read\",\n\t\t\targs,\n\t\t);\n\t\tconst { data, errors } = decodeHookResult(\n\t\t\tt.type({\n\t\t\t\tmodel: CustomType,\n\t\t\t}),\n\t\t\thookResult,\n\t\t);\n\n\t\treturn {\n\t\t\tmodel: data[0]?.model,\n\t\t\terrors,\n\t\t};\n\t}\n\n\tasync updateCustomType(\n\t\targs: CustomTypeUpdateHookData,\n\t): Promise<OnlyHookErrors<CallHookReturnType<CustomTypeUpdateHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:update\",\n\t\t\targs,\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync renameCustomType(\n\t\targs: CustomTypeRenameHookData,\n\t): Promise<OnlyHookErrors<CallHookReturnType<CustomTypeRenameHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:rename\",\n\t\t\targs,\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync deleteCustomType(\n\t\targs: CustomTypesMachineManagerDeleteCustomTypeArgs,\n\t): Promise<CustomTypesMachineManagerDeleteCustomTypeReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst { model, errors: readCustomTypeErrors } = await this.readCustomType({\n\t\t\tid: args.id,\n\t\t});\n\n\t\tif (model) {\n\t\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\t\"custom-type:delete\",\n\t\t\t\t{ model },\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\terrors: hookResult.errors,\n\t\t\t};\n\t\t} else {\n\t\t\treturn {\n\t\t\t\terrors: readCustomTypeErrors,\n\t\t\t};\n\t\t}\n\t}\n\n\tasync pushCustomType(\n\t\targs: SliceMachineManagerPushCustomTypeArgs,\n\t): Promise<void> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst authenticationToken = await this.user.getAuthenticationToken();\n\t\tconst sliceMachineConfig = await this.project.getSliceMachineConfig();\n\n\t\t// TODO: Handle errors\n\t\tconst { model } = await this.readCustomType({ id: args.id });\n\n\t\tif (model) {\n\t\t\t// TODO: Create a single shared client.\n\t\t\tconst client = prismicCustomTypesClient.createClient({\n\t\t\t\tendpoint: API_ENDPOINTS.PrismicModels,\n\t\t\t\trepositoryName: sliceMachineConfig.repositoryName,\n\t\t\t\ttoken: authenticationToken,\n\t\t\t\tuserAgent: args.userAgent || SLICE_MACHINE_USER_AGENT,\n\t\t\t\tfetch,\n\t\t\t});\n\n\t\t\ttry {\n\t\t\t\t// Check if Custom Type already exists on the repository.\n\t\t\t\tawait client.getCustomTypeByID(args.id);\n\n\t\t\t\t// If it exists on the repository, update it.\n\t\t\t\tawait client.updateCustomType(model);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof prismicCustomTypesClient.NotFoundError) {\n\t\t\t\t\t// If it doesn't exist on the repository, insert it.\n\t\t\t\t\tawait client.insertCustomType(model);\n\t\t\t\t} else if (error instanceof prismicCustomTypesClient.ForbiddenError) {\n\t\t\t\t\tthrow new UnauthorizedError(\n\t\t\t\t\t\t\"You do not have access to push types to this Prismic repository.\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcause: error,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO: Remove\n\tasync readCustomTypeMocksConfig(\n\t\targs: SliceMachineManagerReadCustomTypeMocksConfigArgs,\n\t): Promise<SliceMachineManagerReadCustomTypeMocksConfigArgsReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:asset:read\",\n\t\t\t{\n\t\t\t\tcustomTypeID: args.customTypeID,\n\t\t\t\tassetID: \"mocks.config.json\",\n\t\t\t},\n\t\t);\n\t\tconst data = hookResult.data[0]?.data;\n\n\t\t// TODO: Validate the returned data.\n\n\t\tif (data) {\n\t\t\treturn {\n\t\t\t\tmocksConfig: JSON.parse(data.toString()),\n\t\t\t\terrors: hookResult.errors,\n\t\t\t};\n\t\t} else {\n\t\t\treturn {\n\t\t\t\tmocksConfig: undefined,\n\t\t\t\terrors: hookResult.errors,\n\t\t\t};\n\t\t}\n\t}\n\n\t// TODO: Remove\n\tasync updateCustomTypeMocksConfig(\n\t\targs: SliceMachineManagerUpdateCustomTypeMocksConfigArgs,\n\t): Promise<SliceMachineManagerUpdateCustomTypeMocksConfigArgsReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:asset:update\",\n\t\t\t{\n\t\t\t\tcustomTypeID: args.customTypeID,\n\t\t\t\tasset: {\n\t\t\t\t\tid: \"mocks.config.json\",\n\t\t\t\t\tdata: Buffer.from(JSON.stringify(args.mocksConfig, null, \"\\t\")),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync fetchRemoteCustomTypes(): Promise<CustomType[]> {\n\t\tconst authenticationToken = await this.user.getAuthenticationToken();\n\t\tconst sliceMachineConfig = await this.project.getSliceMachineConfig();\n\n\t\tconst client = prismicCustomTypesClient.createClient({\n\t\t\tendpoint: API_ENDPOINTS.PrismicModels,\n\t\t\trepositoryName: sliceMachineConfig.repositoryName,\n\t\t\ttoken: authenticationToken,\n\t\t\tuserAgent: SLICE_MACHINE_USER_AGENT,\n\t\t\tfetch,\n\t\t});\n\n\t\treturn await client.getAllCustomTypes();\n\t}\n}\n"],"names":["BaseManager","assertPluginsInitialized","errors","decodeHookResult","t","CustomType","prismicCustomTypesClient","API_ENDPOINTS","SLICE_MACHINE_USER_AGENT","fetch","UnauthorizedError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFM,MAAO,2BAA2BA,YAAAA,YAAW;AAAA,EAClD,MAAM,wBAAqB;;AAC1BC,sDAAyB,KAAK,wBAAwB;AAEtD,UAAM,aAAa,MAAM,KAAK,yBAAyB,SACtD,4BACA,MAAS;AAEV,UAAM,EAAE,MAAM,QAAAC,QAAA,IAAWC,iBAAAA,iBACxBC,aAAE,KAAK;AAAA,MACN,KAAKA,aAAE,MAAMA,aAAE,MAAM;AAAA,IAAA,CACrB,GACD,UAAU;AAGJ,WAAA;AAAA,MACN,OAAK,UAAK,CAAC,MAAN,mBAAS,QAAO,CAAE;AAAA,MACvB,QAAAF;AAAA,IAAA;AAAA,EAEF;AAAA,EAEA,MAAM,mBACL,MAA+C;AAE/CD,sDAAyB,KAAK,wBAAwB;AAEtD,UAAM,MAAsD;AAAA,MAC3D,QAAQ,CAAE;AAAA,MACV,QAAQ,CAAE;AAAA,IAAA;AAGX,UAAM,EAAE,KAAK,QAAAC,QAAA,IAAW,MAAM,KAAK,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BACL,MAAsD;;AAEtDT,sDAAyB,KAAK,wBAAwB;AAEtD,UAAM,aAAa,MAAM,KAAK,yBAAyB,SACtD,0BACA;AAAA,MACC,cAAc,KAAK;AAAA,MACnB,SAAS;AAAA,IAAA,CACT;AAEF,UAAM,QAAO,gBAAW,KAAK,CAAC,MAAjB,mBAAoB;AAIjC,QAAI,MAAM;AACF,aAAA;AAAA,QACN,aAAa,KAAK,MAAM,KAAK,UAAU;AAAA,QACvC,QAAQ,WAAW;AAAA,MAAA;AAAA,WAEd;AACC,aAAA;AAAA,QACN,aAAa;AAAA,QACb,QAAQ,WAAW;AAAA,MAAA;AAAA,IAEpB;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,4BACL,MAAwD;AAExDA,sDAAyB,KAAK,wBAAwB;AAEtD,UAAM,aAAa,MAAM,KAAK,yBAAyB,SACtD,4BACA;AAAA,MACC,cAAc,KAAK;AAAA,MACnB,OAAO;AAAA,QACN,IAAI;AAAA,QACJ,MAAM,OAAO,KAAK,KAAK,UAAU,KAAK,aAAa,MAAM,GAAI,CAAC;AAAA,MAC9D;AAAA,IAAA,CACD;AAGK,WAAA;AAAA,MACN,QAAQ,WAAW;AAAA,IAAA;AAAA,EAErB;AAAA,EAEA,MAAM,yBAAsB;AAC3B,UAAM,sBAAsB,MAAM,KAAK,KAAK,uBAAsB;AAClE,UAAM,qBAAqB,MAAM,KAAK,QAAQ,sBAAqB;AAE7D,UAAA,SAASK,oCAAyB,aAAa;AAAA,MACpD,UAAUC,cAAc,cAAA;AAAA,MACxB,gBAAgB,mBAAmB;AAAA,MACnC,OAAO;AAAA,MACP,WAAWC,yBAAA;AAAA,MAAA,OACXC,MAAA;AAAA,IAAA,CACA;AAEM,WAAA,MAAM,OAAO;EACrB;AACA;;"}
|
|
@@ -109,7 +109,9 @@ class CustomTypesManager extends BaseManager {
|
|
|
109
109
|
if (error instanceof prismicCustomTypesClient.NotFoundError) {
|
|
110
110
|
await client.insertCustomType(model);
|
|
111
111
|
} else if (error instanceof prismicCustomTypesClient.ForbiddenError) {
|
|
112
|
-
throw new UnauthorizedError("You do not have access to push types to this Prismic repository."
|
|
112
|
+
throw new UnauthorizedError("You do not have access to push types to this Prismic repository.", {
|
|
113
|
+
cause: error
|
|
114
|
+
});
|
|
113
115
|
} else {
|
|
114
116
|
throw error;
|
|
115
117
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CustomTypesManager.js","sources":["../../../../src/managers/customTypes/CustomTypesManager.ts"],"sourcesContent":["import * as t from \"io-ts\";\nimport * as prismicCustomTypesClient from \"@prismicio/custom-types-client\";\nimport { CustomType } from \"@prismicio/types-internal/lib/customtypes\";\nimport {\n\tCallHookReturnType,\n\tCustomTypeCreateHook,\n\tCustomTypeCreateHookData,\n\tCustomTypeReadHookData,\n\tCustomTypeRenameHook,\n\tCustomTypeRenameHookData,\n\tCustomTypeUpdateHook,\n\tCustomTypeUpdateHookData,\n\tHookError,\n} from \"@slicemachine/plugin-kit\";\n\nimport { DecodeError } from \"../../lib/DecodeError\";\nimport { assertPluginsInitialized } from \"../../lib/assertPluginsInitialized\";\nimport { decodeHookResult } from \"../../lib/decodeHookResult\";\nimport fetch from \"../../lib/fetch\";\n\nimport { OnlyHookErrors } from \"../../types\";\nimport { API_ENDPOINTS } from \"../../constants/API_ENDPOINTS\";\nimport { SLICE_MACHINE_USER_AGENT } from \"../../constants/SLICE_MACHINE_USER_AGENT\";\nimport { UnauthorizedError } from \"../../errors\";\n\nimport { BaseManager } from \"../BaseManager\";\nimport { CustomTypeFormat } from \"./types\";\n\ntype SliceMachineManagerReadCustomTypeLibraryReturnType = {\n\tids: string[];\n\terrors: (DecodeError | HookError)[];\n};\n\ntype CustomTypesManagerReadAllCustomTypesArgs = {\n\tformat: CustomTypeFormat;\n};\n\ntype SliceMachineManagerReadAllCustomTypeReturnType = {\n\tmodels: { model: CustomType }[];\n\terrors: (DecodeError | HookError)[];\n};\n\ntype SliceMachineManagerReadCustomTypeReturnType = {\n\tmodel: CustomType | undefined;\n\terrors: (DecodeError | HookError)[];\n};\n\ntype SliceMachineManagerPushCustomTypeArgs = {\n\tid: string;\n\tuserAgent?: string;\n};\n\ntype SliceMachineManagerReadCustomTypeMocksConfigArgs = {\n\tcustomTypeID: string;\n};\n\ntype SliceMachineManagerReadCustomTypeMocksConfigArgsReturnType = {\n\t// TODO\n\tmocksConfig?: Record<string, unknown>;\n\terrors: HookError[];\n};\n\ntype SliceMachineManagerUpdateCustomTypeMocksConfigArgs = {\n\tcustomTypeID: string;\n\t// TODO\n\tmocksConfig: Record<string, unknown>;\n};\n\ntype SliceMachineManagerUpdateCustomTypeMocksConfigArgsReturnType = {\n\terrors: HookError[];\n};\n\ntype CustomTypesMachineManagerDeleteCustomTypeArgs = {\n\tid: string;\n};\n\ntype CustomTypesMachineManagerDeleteCustomTypeReturnType = {\n\terrors: (DecodeError | HookError)[];\n};\n\nexport class CustomTypesManager extends BaseManager {\n\tasync readCustomTypeLibrary(): Promise<SliceMachineManagerReadCustomTypeLibraryReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type-library:read\",\n\t\t\tundefined,\n\t\t);\n\t\tconst { data, errors } = decodeHookResult(\n\t\t\tt.type({\n\t\t\t\tids: t.array(t.string),\n\t\t\t}),\n\t\t\thookResult,\n\t\t);\n\n\t\treturn {\n\t\t\tids: data[0]?.ids || [],\n\t\t\terrors,\n\t\t};\n\t}\n\n\tasync readAllCustomTypes(\n\t\targs?: CustomTypesManagerReadAllCustomTypesArgs,\n\t): Promise<SliceMachineManagerReadAllCustomTypeReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst res: SliceMachineManagerReadAllCustomTypeReturnType = {\n\t\t\tmodels: [],\n\t\t\terrors: [],\n\t\t};\n\n\t\tconst { ids, errors } = await this.readCustomTypeLibrary();\n\t\tres.errors = [...res.errors, ...errors];\n\n\t\tif (ids) {\n\t\t\tfor (const id of ids) {\n\t\t\t\tconst { model, errors } = await this.readCustomType({ id });\n\t\t\t\tres.errors = [...res.errors, ...errors];\n\n\t\t\t\tif (model && (!args || args.format === model.format)) {\n\t\t\t\t\tres.models.push({ model });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tasync createCustomType(\n\t\targs: CustomTypeCreateHookData,\n\t): Promise<OnlyHookErrors<CallHookReturnType<CustomTypeCreateHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:create\",\n\t\t\targs,\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync readCustomType(\n\t\targs: CustomTypeReadHookData,\n\t): Promise<SliceMachineManagerReadCustomTypeReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:read\",\n\t\t\targs,\n\t\t);\n\t\tconst { data, errors } = decodeHookResult(\n\t\t\tt.type({\n\t\t\t\tmodel: CustomType,\n\t\t\t}),\n\t\t\thookResult,\n\t\t);\n\n\t\treturn {\n\t\t\tmodel: data[0]?.model,\n\t\t\terrors,\n\t\t};\n\t}\n\n\tasync updateCustomType(\n\t\targs: CustomTypeUpdateHookData,\n\t): Promise<OnlyHookErrors<CallHookReturnType<CustomTypeUpdateHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:update\",\n\t\t\targs,\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync renameCustomType(\n\t\targs: CustomTypeRenameHookData,\n\t): Promise<OnlyHookErrors<CallHookReturnType<CustomTypeRenameHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:rename\",\n\t\t\targs,\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync deleteCustomType(\n\t\targs: CustomTypesMachineManagerDeleteCustomTypeArgs,\n\t): Promise<CustomTypesMachineManagerDeleteCustomTypeReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst { model, errors: readCustomTypeErrors } = await this.readCustomType({\n\t\t\tid: args.id,\n\t\t});\n\n\t\tif (model) {\n\t\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\t\"custom-type:delete\",\n\t\t\t\t{ model },\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\terrors: hookResult.errors,\n\t\t\t};\n\t\t} else {\n\t\t\treturn {\n\t\t\t\terrors: readCustomTypeErrors,\n\t\t\t};\n\t\t}\n\t}\n\n\tasync pushCustomType(\n\t\targs: SliceMachineManagerPushCustomTypeArgs,\n\t): Promise<void> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst authenticationToken = await this.user.getAuthenticationToken();\n\t\tconst sliceMachineConfig = await this.project.getSliceMachineConfig();\n\n\t\t// TODO: Handle errors\n\t\tconst { model } = await this.readCustomType({ id: args.id });\n\n\t\tif (model) {\n\t\t\t// TODO: Create a single shared client.\n\t\t\tconst client = prismicCustomTypesClient.createClient({\n\t\t\t\tendpoint: API_ENDPOINTS.PrismicModels,\n\t\t\t\trepositoryName: sliceMachineConfig.repositoryName,\n\t\t\t\ttoken: authenticationToken,\n\t\t\t\tuserAgent: args.userAgent || SLICE_MACHINE_USER_AGENT,\n\t\t\t\tfetch,\n\t\t\t});\n\n\t\t\ttry {\n\t\t\t\t// Check if Custom Type already exists on the repository.\n\t\t\t\tawait client.getCustomTypeByID(args.id);\n\n\t\t\t\t// If it exists on the repository, update it.\n\t\t\t\tawait client.updateCustomType(model);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof prismicCustomTypesClient.NotFoundError) {\n\t\t\t\t\t// If it doesn't exist on the repository, insert it.\n\t\t\t\t\tawait client.insertCustomType(model);\n\t\t\t\t} else if (error instanceof prismicCustomTypesClient.ForbiddenError) {\n\t\t\t\t\tthrow new UnauthorizedError(\n\t\t\t\t\t\t\"You do not have access to push types to this Prismic repository.\",\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO: Remove\n\tasync readCustomTypeMocksConfig(\n\t\targs: SliceMachineManagerReadCustomTypeMocksConfigArgs,\n\t): Promise<SliceMachineManagerReadCustomTypeMocksConfigArgsReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:asset:read\",\n\t\t\t{\n\t\t\t\tcustomTypeID: args.customTypeID,\n\t\t\t\tassetID: \"mocks.config.json\",\n\t\t\t},\n\t\t);\n\t\tconst data = hookResult.data[0]?.data;\n\n\t\t// TODO: Validate the returned data.\n\n\t\tif (data) {\n\t\t\treturn {\n\t\t\t\tmocksConfig: JSON.parse(data.toString()),\n\t\t\t\terrors: hookResult.errors,\n\t\t\t};\n\t\t} else {\n\t\t\treturn {\n\t\t\t\tmocksConfig: undefined,\n\t\t\t\terrors: hookResult.errors,\n\t\t\t};\n\t\t}\n\t}\n\n\t// TODO: Remove\n\tasync updateCustomTypeMocksConfig(\n\t\targs: SliceMachineManagerUpdateCustomTypeMocksConfigArgs,\n\t): Promise<SliceMachineManagerUpdateCustomTypeMocksConfigArgsReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:asset:update\",\n\t\t\t{\n\t\t\t\tcustomTypeID: args.customTypeID,\n\t\t\t\tasset: {\n\t\t\t\t\tid: \"mocks.config.json\",\n\t\t\t\t\tdata: Buffer.from(JSON.stringify(args.mocksConfig, null, \"\\t\")),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync fetchRemoteCustomTypes(): Promise<CustomType[]> {\n\t\tconst authenticationToken = await this.user.getAuthenticationToken();\n\t\tconst sliceMachineConfig = await this.project.getSliceMachineConfig();\n\n\t\tconst client = prismicCustomTypesClient.createClient({\n\t\t\tendpoint: API_ENDPOINTS.PrismicModels,\n\t\t\trepositoryName: sliceMachineConfig.repositoryName,\n\t\t\ttoken: authenticationToken,\n\t\t\tuserAgent: SLICE_MACHINE_USER_AGENT,\n\t\t\tfetch,\n\t\t});\n\n\t\treturn await client.getAllCustomTypes();\n\t}\n}\n"],"names":["errors"],"mappings":";;;;;;;;;;AAgFM,MAAO,2BAA2B,YAAW;AAAA,EAClD,MAAM,wBAAqB;;AAC1B,6BAAyB,KAAK,wBAAwB;AAEtD,UAAM,aAAa,MAAM,KAAK,yBAAyB,SACtD,4BACA,MAAS;AAEV,UAAM,EAAE,MAAM,OAAA,IAAW,iBACxB,EAAE,KAAK;AAAA,MACN,KAAK,EAAE,MAAM,EAAE,MAAM;AAAA,IAAA,CACrB,GACD,UAAU;AAGJ,WAAA;AAAA,MACN,OAAK,UAAK,CAAC,MAAN,mBAAS,QAAO,CAAE;AAAA,MACvB;AAAA,IAAA;AAAA,EAEF;AAAA,EAEA,MAAM,mBACL,MAA+C;AAE/C,6BAAyB,KAAK,wBAAwB;AAEtD,UAAM,MAAsD;AAAA,MAC3D,QAAQ,CAAE;AAAA,MACV,QAAQ,CAAE;AAAA,IAAA;AAGX,UAAM,EAAE,KAAK,OAAA,IAAW,MAAM,KAAK,sBAAqB;AACxD,QAAI,SAAS,CAAC,GAAG,IAAI,QAAQ,GAAG,MAAM;AAEtC,QAAI,KAAK;AACR,iBAAW,MA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AAoB;AAIjC,QAAI,MAAM;AACF,aAAA;AAAA,QACN,aAAa,KAAK,MAAM,KAAK,UAAU;AAAA,QACvC,QAAQ,WAAW;AAAA,MAAA;AAAA,WAEd;AACC,aAAA;AAAA,QACN,aAAa;AAAA,QACb,QAAQ,WAAW;AAAA,MAAA;AAAA,IAEpB;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,4BACL,MAAwD;AAExD,6BAAyB,KAAK,wBAAwB;AAEtD,UAAM,aAAa,MAAM,KAAK,yBAAyB,SACtD,4BACA;AAAA,MACC,cAAc,KAAK;AAAA,MACnB,OAAO;AAAA,QACN,IAAI;AAAA,QACJ,MAAM,OAAO,KAAK,KAAK,UAAU,KAAK,aAAa,MAAM,GAAI,CAAC;AAAA,MAC9D;AAAA,IAAA,CACD;AAGK,WAAA;AAAA,MACN,QAAQ,WAAW;AAAA,IAAA;AAAA,EAErB;AAAA,EAEA,MAAM,yBAAsB;AAC3B,UAAM,sBAAsB,MAAM,KAAK,KAAK,uBAAsB;AAClE,UAAM,qBAAqB,MAAM,KAAK,QAAQ,sBAAqB;AAE7D,UAAA,SAAS,yBAAyB,aAAa;AAAA,MACpD,UAAU,cAAc;AAAA,MACxB,gBAAgB,mBAAmB;AAAA,MACnC,OAAO;AAAA,MACP,WAAW;AAAA,MACX;AAAA,IAAA,CACA;AAEM,WAAA,MAAM,OAAO;EACrB;AACA;"}
|
|
1
|
+
{"version":3,"file":"CustomTypesManager.js","sources":["../../../../src/managers/customTypes/CustomTypesManager.ts"],"sourcesContent":["import * as t from \"io-ts\";\nimport * as prismicCustomTypesClient from \"@prismicio/custom-types-client\";\nimport { CustomType } from \"@prismicio/types-internal/lib/customtypes\";\nimport {\n\tCallHookReturnType,\n\tCustomTypeCreateHook,\n\tCustomTypeCreateHookData,\n\tCustomTypeReadHookData,\n\tCustomTypeRenameHook,\n\tCustomTypeRenameHookData,\n\tCustomTypeUpdateHook,\n\tCustomTypeUpdateHookData,\n\tHookError,\n} from \"@slicemachine/plugin-kit\";\n\nimport { DecodeError } from \"../../lib/DecodeError\";\nimport { assertPluginsInitialized } from \"../../lib/assertPluginsInitialized\";\nimport { decodeHookResult } from \"../../lib/decodeHookResult\";\nimport fetch from \"../../lib/fetch\";\n\nimport { OnlyHookErrors } from \"../../types\";\nimport { API_ENDPOINTS } from \"../../constants/API_ENDPOINTS\";\nimport { SLICE_MACHINE_USER_AGENT } from \"../../constants/SLICE_MACHINE_USER_AGENT\";\nimport { UnauthorizedError } from \"../../errors\";\n\nimport { BaseManager } from \"../BaseManager\";\nimport { CustomTypeFormat } from \"./types\";\n\ntype SliceMachineManagerReadCustomTypeLibraryReturnType = {\n\tids: string[];\n\terrors: (DecodeError | HookError)[];\n};\n\ntype CustomTypesManagerReadAllCustomTypesArgs = {\n\tformat: CustomTypeFormat;\n};\n\ntype SliceMachineManagerReadAllCustomTypeReturnType = {\n\tmodels: { model: CustomType }[];\n\terrors: (DecodeError | HookError)[];\n};\n\ntype SliceMachineManagerReadCustomTypeReturnType = {\n\tmodel: CustomType | undefined;\n\terrors: (DecodeError | HookError)[];\n};\n\ntype SliceMachineManagerPushCustomTypeArgs = {\n\tid: string;\n\tuserAgent?: string;\n};\n\ntype SliceMachineManagerReadCustomTypeMocksConfigArgs = {\n\tcustomTypeID: string;\n};\n\ntype SliceMachineManagerReadCustomTypeMocksConfigArgsReturnType = {\n\t// TODO\n\tmocksConfig?: Record<string, unknown>;\n\terrors: HookError[];\n};\n\ntype SliceMachineManagerUpdateCustomTypeMocksConfigArgs = {\n\tcustomTypeID: string;\n\t// TODO\n\tmocksConfig: Record<string, unknown>;\n};\n\ntype SliceMachineManagerUpdateCustomTypeMocksConfigArgsReturnType = {\n\terrors: HookError[];\n};\n\ntype CustomTypesMachineManagerDeleteCustomTypeArgs = {\n\tid: string;\n};\n\ntype CustomTypesMachineManagerDeleteCustomTypeReturnType = {\n\terrors: (DecodeError | HookError)[];\n};\n\nexport class CustomTypesManager extends BaseManager {\n\tasync readCustomTypeLibrary(): Promise<SliceMachineManagerReadCustomTypeLibraryReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type-library:read\",\n\t\t\tundefined,\n\t\t);\n\t\tconst { data, errors } = decodeHookResult(\n\t\t\tt.type({\n\t\t\t\tids: t.array(t.string),\n\t\t\t}),\n\t\t\thookResult,\n\t\t);\n\n\t\treturn {\n\t\t\tids: data[0]?.ids || [],\n\t\t\terrors,\n\t\t};\n\t}\n\n\tasync readAllCustomTypes(\n\t\targs?: CustomTypesManagerReadAllCustomTypesArgs,\n\t): Promise<SliceMachineManagerReadAllCustomTypeReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst res: SliceMachineManagerReadAllCustomTypeReturnType = {\n\t\t\tmodels: [],\n\t\t\terrors: [],\n\t\t};\n\n\t\tconst { ids, errors } = await this.readCustomTypeLibrary();\n\t\tres.errors = [...res.errors, ...errors];\n\n\t\tif (ids) {\n\t\t\tfor (const id of ids) {\n\t\t\t\tconst { model, errors } = await this.readCustomType({ id });\n\t\t\t\tres.errors = [...res.errors, ...errors];\n\n\t\t\t\tif (model && (!args || args.format === model.format)) {\n\t\t\t\t\tres.models.push({ model });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tasync createCustomType(\n\t\targs: CustomTypeCreateHookData,\n\t): Promise<OnlyHookErrors<CallHookReturnType<CustomTypeCreateHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:create\",\n\t\t\targs,\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync readCustomType(\n\t\targs: CustomTypeReadHookData,\n\t): Promise<SliceMachineManagerReadCustomTypeReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:read\",\n\t\t\targs,\n\t\t);\n\t\tconst { data, errors } = decodeHookResult(\n\t\t\tt.type({\n\t\t\t\tmodel: CustomType,\n\t\t\t}),\n\t\t\thookResult,\n\t\t);\n\n\t\treturn {\n\t\t\tmodel: data[0]?.model,\n\t\t\terrors,\n\t\t};\n\t}\n\n\tasync updateCustomType(\n\t\targs: CustomTypeUpdateHookData,\n\t): Promise<OnlyHookErrors<CallHookReturnType<CustomTypeUpdateHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:update\",\n\t\t\targs,\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync renameCustomType(\n\t\targs: CustomTypeRenameHookData,\n\t): Promise<OnlyHookErrors<CallHookReturnType<CustomTypeRenameHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:rename\",\n\t\t\targs,\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync deleteCustomType(\n\t\targs: CustomTypesMachineManagerDeleteCustomTypeArgs,\n\t): Promise<CustomTypesMachineManagerDeleteCustomTypeReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst { model, errors: readCustomTypeErrors } = await this.readCustomType({\n\t\t\tid: args.id,\n\t\t});\n\n\t\tif (model) {\n\t\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\t\"custom-type:delete\",\n\t\t\t\t{ model },\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\terrors: hookResult.errors,\n\t\t\t};\n\t\t} else {\n\t\t\treturn {\n\t\t\t\terrors: readCustomTypeErrors,\n\t\t\t};\n\t\t}\n\t}\n\n\tasync pushCustomType(\n\t\targs: SliceMachineManagerPushCustomTypeArgs,\n\t): Promise<void> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst authenticationToken = await this.user.getAuthenticationToken();\n\t\tconst sliceMachineConfig = await this.project.getSliceMachineConfig();\n\n\t\t// TODO: Handle errors\n\t\tconst { model } = await this.readCustomType({ id: args.id });\n\n\t\tif (model) {\n\t\t\t// TODO: Create a single shared client.\n\t\t\tconst client = prismicCustomTypesClient.createClient({\n\t\t\t\tendpoint: API_ENDPOINTS.PrismicModels,\n\t\t\t\trepositoryName: sliceMachineConfig.repositoryName,\n\t\t\t\ttoken: authenticationToken,\n\t\t\t\tuserAgent: args.userAgent || SLICE_MACHINE_USER_AGENT,\n\t\t\t\tfetch,\n\t\t\t});\n\n\t\t\ttry {\n\t\t\t\t// Check if Custom Type already exists on the repository.\n\t\t\t\tawait client.getCustomTypeByID(args.id);\n\n\t\t\t\t// If it exists on the repository, update it.\n\t\t\t\tawait client.updateCustomType(model);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof prismicCustomTypesClient.NotFoundError) {\n\t\t\t\t\t// If it doesn't exist on the repository, insert it.\n\t\t\t\t\tawait client.insertCustomType(model);\n\t\t\t\t} else if (error instanceof prismicCustomTypesClient.ForbiddenError) {\n\t\t\t\t\tthrow new UnauthorizedError(\n\t\t\t\t\t\t\"You do not have access to push types to this Prismic repository.\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcause: error,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO: Remove\n\tasync readCustomTypeMocksConfig(\n\t\targs: SliceMachineManagerReadCustomTypeMocksConfigArgs,\n\t): Promise<SliceMachineManagerReadCustomTypeMocksConfigArgsReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:asset:read\",\n\t\t\t{\n\t\t\t\tcustomTypeID: args.customTypeID,\n\t\t\t\tassetID: \"mocks.config.json\",\n\t\t\t},\n\t\t);\n\t\tconst data = hookResult.data[0]?.data;\n\n\t\t// TODO: Validate the returned data.\n\n\t\tif (data) {\n\t\t\treturn {\n\t\t\t\tmocksConfig: JSON.parse(data.toString()),\n\t\t\t\terrors: hookResult.errors,\n\t\t\t};\n\t\t} else {\n\t\t\treturn {\n\t\t\t\tmocksConfig: undefined,\n\t\t\t\terrors: hookResult.errors,\n\t\t\t};\n\t\t}\n\t}\n\n\t// TODO: Remove\n\tasync updateCustomTypeMocksConfig(\n\t\targs: SliceMachineManagerUpdateCustomTypeMocksConfigArgs,\n\t): Promise<SliceMachineManagerUpdateCustomTypeMocksConfigArgsReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"custom-type:asset:update\",\n\t\t\t{\n\t\t\t\tcustomTypeID: args.customTypeID,\n\t\t\t\tasset: {\n\t\t\t\t\tid: \"mocks.config.json\",\n\t\t\t\t\tdata: Buffer.from(JSON.stringify(args.mocksConfig, null, \"\\t\")),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync fetchRemoteCustomTypes(): Promise<CustomType[]> {\n\t\tconst authenticationToken = await this.user.getAuthenticationToken();\n\t\tconst sliceMachineConfig = await this.project.getSliceMachineConfig();\n\n\t\tconst client = prismicCustomTypesClient.createClient({\n\t\t\tendpoint: API_ENDPOINTS.PrismicModels,\n\t\t\trepositoryName: sliceMachineConfig.repositoryName,\n\t\t\ttoken: authenticationToken,\n\t\t\tuserAgent: SLICE_MACHINE_USER_AGENT,\n\t\t\tfetch,\n\t\t});\n\n\t\treturn await client.getAllCustomTypes();\n\t}\n}\n"],"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,QAAQ,WAAW;AAAA,IAAA;AAAA,EAErB;AAAA,EAEA,MAAM,yBAAsB;AAC3B,UAAM,sBAAsB,MAAM,KAAK,KAAK,uBAAsB;AAClE,UAAM,qBAAqB,MAAM,KAAK,QAAQ,sBAAqB;AAE7D,UAAA,SAAS,yBAAyB,aAAa;AAAA,MACpD,UAAU,cAAc;AAAA,MACxB,gBAAgB,mBAAmB;AAAA,MACnC,OAAO;AAAA,MACP,WAAW;AAAA,MACX;AAAA,IAAA,CACA;AAEM,WAAA,MAAM,OAAO;EACrB;AACA;"}
|
|
@@ -40,15 +40,16 @@ class PrismicRepositoryManager extends BaseManager.BaseManager {
|
|
|
40
40
|
async readAll() {
|
|
41
41
|
const url = new URL("./repositories", API_ENDPOINTS.API_ENDPOINTS.PrismicUser);
|
|
42
42
|
const res = await this._fetch({ url });
|
|
43
|
-
const json = await res.json();
|
|
44
43
|
if (res.ok) {
|
|
44
|
+
const json = await res.json();
|
|
45
45
|
const { value: repositories, error } = decode.decode(t__namespace.array(types.PrismicRepository), json);
|
|
46
46
|
if (error) {
|
|
47
47
|
throw new Error(`Failed to decode repositories: ${error.errors.join(", ")}`);
|
|
48
48
|
}
|
|
49
49
|
return repositories;
|
|
50
50
|
} else {
|
|
51
|
-
|
|
51
|
+
const text = await res.text();
|
|
52
|
+
throw new Error(`Failed to read repositories`, { cause: text });
|
|
52
53
|
}
|
|
53
54
|
}
|
|
54
55
|
// Should this be in manager? It's one of the few sync method
|
|
@@ -301,7 +302,9 @@ class PrismicRepositoryManager extends BaseManager.BaseManager {
|
|
|
301
302
|
const text = await response.text();
|
|
302
303
|
throw new Error(text);
|
|
303
304
|
default:
|
|
304
|
-
throw new Error(`Unexpected status code ${response.status}
|
|
305
|
+
throw new Error(`Unexpected status code ${response.status}`, {
|
|
306
|
+
cause: await response.text()
|
|
307
|
+
});
|
|
305
308
|
}
|
|
306
309
|
} catch (err) {
|
|
307
310
|
console.error("An error happened while pushing your changes");
|