Skip to content

add typescript for gatsby-source-vtex - #1

Closed
tlgimenes wants to merge 2 commits into
masterfrom
feature/add-typescript
Closed

tlgimenes wants to merge 2 commits into
masterfrom
feature/add-typescript

Conversation

@tlgimenes

Copy link
Copy Markdown
Contributor

as title says, removes babel and uses tsc for gatsby-source-vtex. Also, adds the missing types

Comment thread gatsby-source-vtex/src/gatsby-node.ts Resolved
@tlgimenes

Copy link
Copy Markdown
Contributor Author

closing this since #2 already covers this one

@tlgimenes tlgimenes closed this Jun 18, 2020
@tlgimenes
tlgimenes deleted the feature/add-typescript branch June 18, 2020 03:56
eduardoformiga added a commit that referenced this pull request Aug 5, 2025
## What's the purpose of this pull request?

This PR aims to implement the refresh cookie logic to maintain the user
logged in.

## How does it work?

First, we are using the `refreshAfter` prop from the session to store
the time when we can call the refresh token route again.
After the login, some cookies are set in the response for the production
URL: `VtexIdclientAutCookie_<account>` (access token), and the refresh
token cookie in a specific path that we must call in the frontend.

The workflow calls the refresh token request in the frontend (httpOnly),
under three conditions, during the validate session mutation:
1. `tokenExistAndIsFirstRefreshTokenRequest`— The login has been made,
but we need to call the refresh token request at least once to get the
`refreshAfter` for the first time.
2. `tokenNotExistAndRefreshAfterExistAndIsExpired`— When the access
token expires, the browser clears it, so the access token no longer
exists. However, as we have the `refreshAfter` from the previous request
to the refresh token route, we know when to call it again after the
refreshAfter time.
3. `tokenExpiredAndRefreshAfterIsNullOrExpired` - just a fallback that
double-checks the internal expires (claim) prop from the JWT token using
the cookie, not the cookie expiration that the browser tasks care.


## How to test it?

1 - The `refreshToken` flag must be true in `discovery.config`.
2 - You need to ask the identity team (open a support ticket) to enable
the refresh token feature and set a time, like 7 days.
(`b2bfaststoredev` account is set to 7 days)
3 - Use a production URL like
https://b2bfaststore.vtexfaststore.com/login to login.
4 - After login, the cookies should be set, and you can see a first
`/webstore` request in devtools with the `refreshAfter` in the response,
which will be stored in the session.
5—After 1 day, just double-check if this request is made again and if
you will continue logged.

## References

- [FastStore refresh token
doc](https://docs.google.com/document/d/1ctMH7P5hCwvoRtlqtXWevUdmXYmtjeCTkxN-xsOZYi8/edit?tab=t.0#heading=h.hysy5010uuws)
-
https://developers.vtex.com/docs/guides/refresh-token-flow-for-headless-implementations
-
https://developers.vtex.com/docs/api-reference/vtex-id-api#post-/api/vtexid/refreshtoken/webstore
- slack threads with videos:
[#1](https://vtex.slack.com/archives/C03L3CRCDC4/p1753797589142619),
[#2](https://vtex.slack.com/archives/C03L3CRCDC4/p1754314094298059).
lemagnetic added a commit that referenced this pull request Jul 1, 2026
## What's the purpose of this pull request?

Store developers on Content Platform (CP) had to run `vtex content
generate-schema` and `upload-schema` manually, easy to get wrong and a
recurring source of support tickets. This PR extends `cms-sync` to
detect `contentSource.type` in `discovery.config.js` and run the right
flow in one command: legacy Headless CMS unchanged, CP with generate +
upload built in.

When `experimental.enableFaststoreMyAccount` is on, CP mode also merges
the core My Account CMS schemas (kept out of the published base / Schema
Registry) into the same generated schema so merchants don't have to copy
JSONC by hand.

**Jira:**
[SFS-3243](https://vtex-dev.atlassian.net/jira/software/c/projects/SFS/boards/1051?selectedIssue=SFS-3243)

## How it works?

**Content-source detection**

- Reads the store's own `discovery.config.js` at `basePath` (not
`.faststore` tmp).
- `contentSource.type` absent or `CMS` → legacy flow unchanged
(`generate` + `mergeCMSFiles` + `vtex cms sync`).
- `CP` → CP flow: pre-flight, then `generate-schema` (no `-l`) and
`upload-schema`.
- Unknown `type` → fail fast with a clear error.
- Logs detected mode at startup (`CMS` vs `CP`).

**CP flow**

- **Pre-flight first** (`utils/vtex.ts`, `assertVtexReadyForAccount`):
checks `vtex --version` (installed) and `vtex whoami` (logged in,
account matches `api.storeId` case-insensitively). Fails fast with an
install / `vtex login <account>` / `vtex switch <account>` hint — avoids
the toolbelt stalling on a login prompt.
- Uses existing `cms/faststore/components` and/or `pages` when present;
fails if neither exists (before any toolbelt call).
- All directory and `-o` paths are passed **relative to the store root**
— the toolbelt resolves them against the cwd, so absolute paths would be
doubled into `<store>/<store>/…` and fail with `ENOENT`.
- `generate-schema`/`upload-schema` run **synchronously, in order, and
interactively** (`runCommandSync` with `stdio: 'inherit'`):
`generate-schema` has no `--yes` and prompts to confirm overriding a
base definition; `upload-schema` prompts for the version to publish.
`--dry-run` stops after generation.

**My Account merge (opt-in)**

- When `experimental.enableFaststoreMyAccount === true` in CP mode:
- **File-level merge** of the core My Account JSONC
(`coreCMSDir/my-account/{components,pages}`) with the store's own
`cms/faststore/{components,pages}` into a staging dir with exactly two
subdirs (`components`, `pages`), created under the store's
**`.faststore`** folder. Core is copied first, the store's files on top
→ store wins on name collision.
- These two merged dirs **replace** the store dirs as the two positional
args to a single `generate-schema` (`generate-schema` accepts only two
positional dirs, so the merge has to be at the file level).
  - Announces the merge in the log.
  - Removes the staging dir in `finally` (success, dry-run, or failure).
  - Proceeds even if the store has no own `components`/`pages`.
  - Fails fast if core My Account schemas are missing.

**Package scope:** `@faststore/cli` (`cms-sync.ts`,
`utils/cp-schema.ts`, `utils/config.ts`, new `utils/vtex.ts`,
`utils/runCommandSync.ts` interactive flag) + docs in
`packages/core/README.md` and `packages/cli/AGENTS.md`.

```mermaid
flowchart TD
    A([faststore cms-sync PATH --dry-run]) --> B["basePath = getBasePath(PATH ?? cwd)"]
    B --> E["storeConfig = discovery.config.js em basePath (ou null)"]
    E --> F["resolveContentSource(storeConfig?.contentSource?.type)"]

    F --> G{"type (uppercase)"}
    G -- "undefined / 'CMS'" --> H["source = CMS"]
    G -- "'CP'" --> I["source = CP"]
    G -- "outro (ex: 'WORDPRESS')" --> X1["logger.error<br/>Unsupported contentSource.type"]:::err
    X1 --> X2([process.exit 1]):::exit

    H --> LOG["logger.info — Detected contentSource ... + ação"]
    I --> LOG
    LOG --> SW{"switch(source)"}

    %% ===== Legacy CMS =====
    SW -- CMS --> L1["runLegacySync"]
    L1 --> L3["generate({ setup }) + mergeCMSFiles(basePath)"]
    L3 --> L5{"--dry-run?"}
    L5 -- sim --> L6([return — sem sync]):::ok
    L5 -- não --> L7["spawn('vtex cms sync <project>',<br/>cwd = .faststore tmpDir)"]
    L7 --> L8([fim]):::ok

    %% ===== CP =====
    SW -- CP --> PF["assertVtexReadyForAccount(api.storeId)<br/>vtex --version + vtex whoami"]
    PF -- "ausente / deslogado / conta errada" --> XPF["logger.error<br/>install / vtex login / vtex switch"]:::err
    XPF --> XPF2([process.exit 1]):::exit
    PF -- ok --> P3{"isMyAccountEnabled?"}

    P3 -- sim --> M1["logger.info — Merging My Account ..."]
    M1 --> M3{"coreCMSDir/my-account<br/>existe?"}
    M3 -- não --> X3["logger.error — core My Account não encontrado"]:::err
    X3 --> X4([process.exit 1]):::exit
    M3 -- sim --> M4["prepareMyAccountMergeDir:<br/>mkdtemp em .faststore;<br/>cpSync core + loja (loja vence)"]
    M4 --> M5["dirs = [merge/components, merge/pages]<br/>(relativos; substituem dirs da loja)"]
    M5 --> P4

    P3 -- não --> PD["dirs = getExistingCpDirs(basePath)<br/>(subset relativo de components/pages)"]
    PD --> P4{"dirs.length === 0?"}
    P4 -- sim --> X5["errorNoCustomization()"]:::err
    X5 --> X6([process.exit 1]):::exit
    P4 -- não --> P5["schemaOut = cms/faststore/schema.json (relativo)"]

    P5 --> T1["try: generateAndUploadSchema"]
    T1 --> G1["runCommandSync (interactive)<br/>vtex content generate-schema &lt;dirs&gt; -o schemaOut<br/>(sem -l, cwd = basePath)<br/>prompt: confirmar override do base"]
    G1 --> G2{"--dry-run?"}
    G2 -- sim --> G3["return (sem upload)"]
    G2 -- não --> G4["runCommandSync (interactive)<br/>vtex content upload-schema schemaOut<br/>prompt: versão a publicar"]
    G3 --> FIN["finally"]
    G4 --> FIN
    T1 -. erro do toolbelt .-> FIN
    FIN --> FZ{"merge criado?"}
    FZ -- sim --> FC["cleanupMyAccountMergeDir(mergeDir)<br/>rmSync recursive/force"]
    FZ -- não --> FE([fim]):::ok
    FC --> FE

    classDef err fill:#5c1a1a,stroke:#ff6b6b,color:#fff;
    classDef exit fill:#3a0d0d,stroke:#ff6b6b,color:#fff;
    classDef ok fill:#10391f,stroke:#3ddc84,color:#fff;

```

## How to test it?

**Legacy CMS (regression)**

1. Store with `contentSource: { type: 'CMS' }` (or no `contentSource`).
2. Run `pnpm faststore cms-sync` — expect merge + `vtex cms sync` as
before.
3. Run with `--dry-run` — expect no `vtex cms sync`.

**CP — customizations only**

1. Set `contentSource: { type: 'CP' }` in `discovery.config.js`.
2. Add schemas under `cms/faststore/components/` and/or `pages/`.
3. Run `pnpm faststore cms-sync` — expect `generate-schema` (no `-l`)
then `upload-schema`.
4. Run with `--dry-run` — schema generated, no upload.
5. Remove both dirs — expect exit 1 with "No CMS customization found".

**CP pre-flight**

1. With the `vtex` toolbelt not installed → exit 1 with an install hint.
2. Logged out → exit 1 with `vtex login <account>`.
3. Logged into a different account than `api.storeId` → exit 1 with
`vtex switch <account>`.
4. Logged into the matching account → flow proceeds.

**CP + My Account**

1. Set `contentSource: { type: 'CP' }` and `experimental: {
enableFaststoreMyAccount: true }`.
2. Run `pnpm faststore cms-sync` — log mentions the My Account merge;
the generated schema includes the store's components/content-types
**and** the My Account ones.
3. Repeat with no store `components`/`pages` — should still generate
from the core My Account schemas.
4. Repeat with `--dry-run` — generate only; staging dir under
`.faststore` cleaned up.
5. With flag off — My Account must not be included (same as CP-only
case).

**End-to-end validation (`brandless` store)**

Validated against a real CP store:

- `yarn cms-sync --dry-run` → generates `cms/faststore/schema.json`
containing the store's `Banner example` component, the `landingPage`
content-type, and the 14 core My Account components + 6 content-types
(confirmed answering the `landingPage` base-override prompt).
- `yarn cms-sync` → answered the override prompt, picked the version
(`4.22.0`), confirmed the upload → `Schema uploaded successfully with ID
[email protected]`.

**Automated**

```sh
cd packages/cli && pnpm test   # matrix #1–#14 + pre-flight #15–#18
pnpm lint
```

## References

-
[SFS-3243](https://vtex-dev.atlassian.net/jira/software/c/projects/SFS/boards/1051?selectedIssue=SFS-3243)
- Spec: `specs/005-cms-sync-content-source/`


[SFS-3243]:
https://vtex-dev.atlassian.net/browse/SFS-3243?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
[SFS-3243]:
https://vtex-dev.atlassian.net/browse/SFS-3243?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants