@sanity/workbench-cli 2.15.2 → 2.16.1
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/_exports/_internal_worker_bus.d.ts +3 -3
- package/dist/_exports/_internal_worker_bus.js +1 -1
- package/dist/_exports/_internal_worker_bus.js.map +1 -1
- package/dist/_exports/build.d.ts +3 -3
- package/dist/_exports/{contract-C4Y6gi-b.d.ts → contract-WrU3aOYd.d.ts} +9 -6
- package/dist/_exports/deploy.d.ts +3 -3
- package/dist/_exports/dev.d.ts +1 -1
- package/dist/_exports/index.d.ts +5 -4
- package/dist/_exports/index.js +1 -1
- package/dist/_exports/index.js.map +1 -1
- package/dist/_exports/{resolveWorkbenchConfig-CgKD8AJ7.d.ts → resolveWorkbenchConfig-JRi01VJM.d.ts} +2 -2
- package/dist/_exports/{summarizeInterfaces-CeV5Umpj.d.ts → summarizeInterfaces-CpCUSMrz.d.ts} +6 -6
- package/dist/_exports/undeploy.d.ts +2 -2
- package/dist/_exports/{defineService-DPZwNN6_.d.ts → webWorker-TWUbh0uo.d.ts} +63 -39
- package/dist/actions/build/artifact.js +2 -2
- package/dist/actions/build/artifact.js.map +1 -1
- package/dist/actions/build/render-remote.js +11 -5
- package/dist/actions/build/render-remote.js.map +1 -1
- package/dist/actions/build/views/artifact.js +7 -5
- package/dist/actions/build/views/artifact.js.map +1 -1
- package/dist/actions/build/vite/optimize-deps.js +2 -2
- package/dist/actions/build/vite/optimize-deps.js.map +1 -1
- package/dist/actions/build/vite/plugin.js +2 -2
- package/dist/actions/build/vite/plugin.js.map +1 -1
- package/dist/actions/build/vite/plugins/plugin-sanity-environment.js +1 -0
- package/dist/actions/build/vite/plugins/plugin-sanity-environment.js.map +1 -1
- package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js +2 -2
- package/dist/actions/build/vite/plugins/plugin-sanity-extension-artifacts.js.map +1 -1
- package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js +5 -2
- package/dist/actions/build/vite/plugins/plugin-sanity-federation-runtime.js.map +1 -1
- package/dist/actions/build/{services → webWorkers}/artifact.js +28 -27
- package/dist/actions/build/webWorkers/artifact.js.map +1 -0
- package/dist/actions/build/{services → webWorkers}/workerBus.js +1 -1
- package/dist/actions/build/webWorkers/workerBus.js.map +1 -0
- package/dist/actions/deploy/deployWorkbenchApp.js +7 -14
- package/dist/actions/deploy/deployWorkbenchApp.js.map +1 -1
- package/dist/actions/deploy/getWorkbench.js.map +1 -1
- package/dist/actions/deploy/summarizeInterfaces.js +3 -3
- package/dist/actions/deploy/summarizeInterfaces.js.map +1 -1
- package/dist/actions/dev/appServerSupervisor.js +2 -2
- package/dist/actions/dev/appServerSupervisor.js.map +1 -1
- package/dist/actions/dev/exposesSetId.js +1 -1
- package/dist/actions/dev/exposesSetId.js.map +1 -1
- package/dist/actions/dev/registry.js +14 -4
- package/dist/actions/dev/registry.js.map +1 -1
- package/dist/actions/dev/startWorkbenchDev.js +1 -1
- package/dist/actions/dev/startWorkbenchDev.js.map +1 -1
- package/dist/contract.js +8 -8
- package/dist/contract.js.map +1 -1
- package/dist/defineApp.js +2 -2
- package/dist/defineApp.js.map +1 -1
- package/dist/defineView.js +2 -2
- package/dist/defineView.js.map +1 -1
- package/dist/deriveInterfaces.js.map +1 -1
- package/dist/webWorker.js +20 -0
- package/dist/webWorker.js.map +1 -0
- package/package.json +11 -11
- package/dist/actions/build/services/artifact.js.map +0 -1
- package/dist/actions/build/services/workerBus.js.map +0 -1
- package/dist/defineService.js +0 -52
- package/dist/defineService.js.map +0 -1
package/dist/defineApp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/defineApp.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\nimport {APP_SLUG_PATTERN} from './appSlug.js'\nimport {DockSchema, InterfaceDeclarationSchema, ServiceDeclarationSchema} from './contract.js'\n\n/**\n * Dashboard visibility values. Mirrors `APP_VISIBILITIES` in `@sanity/cli-core`\n * (which can't be imported here — pulling the barrel into this lean module bloats\n * the config-load path). Kept in sync by a type test in `defineApp.test.ts`.\n */\nconst APP_VISIBILITIES = ['default', 'unlisted', 'disabled'] as const\n\n/**\n * Internal application discriminator. Sanity-owned singleton apps only;\n * validated by the schema but excluded from the public `DefineAppInput` type.\n */\nconst ApplicationType = z.enum(['coreApp', 'studio', 'canvas', 'dashboard'])\n\n/**\n * Runtime-validation schema for `defineApplication`.\n * @internal\n */\nexport const DefineAppInputSchema = z\n .object({\n /**\n * Internal — Sanity-owned singleton apps only. Validated here but excluded\n * from the public `DefineAppInput` type.\n * @internal\n */\n applicationType: z.optional(ApplicationType),\n /** Default placement inherited by window views. */\n dock: z.optional(DockSchema),\n /**\n * App entrypoint module. Defaults to `./src/App.tsx` when omitted. The build\n * derives the app's navigable `app` view from it. SDK apps only — setting it\n * on a studio is rejected (studio app views are not yet implemented).\n */\n entry: z.optional(z.string(\"must be a path to the app's entry file\")),\n /**\n * Path to an `.svg` file, relative to the project root. Other file types are\n * rejected. Wins over manifest/studio icon.\n */\n icon: z.optional(\n z.string().check(z.regex(/\\.svg$/i, 'App `icon` must be a path to an .svg file')),\n ),\n /** Sanity-owned app deployed once and installed per org. @internal */\n isSingleton: z.optional(z.boolean()),\n /**\n * Stable identity, distinct from the `slug` address. Defaults to `slug` when\n * omitted. Identity keys — the build id and derived interface ids — are built\n * from this, so renaming the slug no longer changes identity.\n */\n name: z.optional(\n z\n .string()\n .check(\n z.regex(\n APP_SLUG_PATTERN,\n 'App `name` must be lowercase alphanumerics and hyphens, starting with a letter and ending with an alphanumeric',\n ),\n ),\n ),\n /** Organization that owns the app — it runs in and deploys to this organization's Dashboard. */\n organizationId: z.string(\n \"App `organizationId` is required — pass the owning organization's ID to `defineApplication`\",\n ),\n slug: z\n .string('App `slug` is required — the hostname the application is created at on deploy')\n .check(\n z.regex(\n APP_SLUG_PATTERN,\n 'App `slug` must be lowercase alphanumerics and hyphens, starting with a letter and ending with an alphanumeric',\n ),\n ),\n /** User-facing app title. Wins over studio.config.ts title on merge. */\n title: z.string(),\n /** Views the app exposes (e.g. a window, dock panels, and tiles). */\n views: z.optional(z.array(InterfaceDeclarationSchema, 'must be an array of views')),\n /** Dashboard visibility of the app. Defaults to `default` when omitted. */\n visibility: z.optional(z.enum(APP_VISIBILITIES)),\n /** Background web workers the app runs. */\n webWorkers: z.optional(z.array(ServiceDeclarationSchema, 'must be an array of web workers')),\n })\n .check(\n z.refine((input) => {\n const names = [\n ...(input.entry === undefined ? [] : [input.name ?? input.slug]),\n ...(input.views ?? []).map((view) => view.name),\n ...(input.webWorkers ?? []).map((webWorker) => webWorker.name),\n ]\n return new Set(names).size === names.length\n }, '`name` must be unique across views and web workers. Rename one of the duplicates.'),\n // Studio app views are not implemented yet. A studio that declares `entry`\n // (the SDK app-view entrypoint) is rejected here rather than silently\n // generating one; studios keep navigating via their existing render path.\n z.refine((input) => !(input.applicationType === 'studio' && input.entry !== undefined), {\n error: 'App views for studios are not implemented yet',\n path: ['entry'],\n }),\n )\n\n/**\n * User-facing input for `defineApplication`. Excludes the internal\n * `applicationType` and `isSingleton`.\n * @public\n */\nexport type DefineAppInput = Omit<\n z.output<typeof DefineAppInputSchema>,\n 'applicationType' | 'isSingleton'\n>\n\n/**\n * Nominal brand the CLI discriminates on to enable the workbench build/deploy\n * codepath. Registered via `Symbol.for` so the marker survives module-realm\n * boundaries — `@sanity/cli-core` re-derives the same global symbol with\n * `Symbol.for` rather than importing it, so it stays internal to this module.\n */\nconst WORKBENCH_APP: unique symbol = Symbol.for('sanity.workbench.defineApp')\n\n/**\n * The branded result of `defineApplication`. Carries the same fields as the\n * input plus the internal brand — users only ever see `DefineAppInput`.\n * @public\n */\nexport type DefineAppResult = DefineAppInput & {readonly [WORKBENCH_APP]: true}\n\n/**\n * A branded app as the CLI reads it — the full schema shape, including the\n * internal fields `DefineAppInput` omits. Schema-derived so the narrowing\n * can't drift from what the schema validates.\n * @public\n */\nexport type WorkbenchApp = DefineAppResult & z.output<typeof DefineAppInputSchema>\n\n/**\n * Whether `app` is a branded `defineApplication(...)` result — the sole\n * workbench opt-in.\n * @public\n */\nexport function isWorkbenchApp(app: unknown): app is WorkbenchApp {\n return typeof app === 'object' && app !== null && WORKBENCH_APP in app\n}\n\n/**\n * Declare a Sanity Dashboard application. Identity at runtime — returns the same\n * object reference, tagged with the Dashboard brand. Field validation (the\n * `slug` pattern etc.) runs at build time in the CLI via `DefineAppInputSchema`;\n * this helper stays a thin, pure identity wrapper.\n * @public\n */\nexport function defineApplication(input: DefineAppInput): DefineAppResult {\n return Object.defineProperty(input, WORKBENCH_APP, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n }) as DefineAppResult\n}\n\n/**\n * One custom field a media library exposes. `src` default-exports a `defineField(...)` schema type.\n * @public\n */\nexport interface MediaLibraryField {\n /** Unique within the media library. */\n name: string\n src: string\n title: string\n\n /** Readable outside the owning organization. */\n public?: boolean\n}\n\n/**\n * Sanity-owned singleton, so authors don't name or title the app — only `organizationId` is required.\n * @public\n */\nexport interface DefineMediaLibraryInput {\n /** Organization that owns the media library — the CLI runs and deploys against it. */\n organizationId: string\n\n fields?: MediaLibraryField[]\n}\n\n/**\n * Nominal brand the CLI discriminates a config on. A config is *not* an app: it\n * carries no `slug`/`title`/application identity, only a target `appType`, its\n * owning `organizationId`, and its `fields`. Registered via `Symbol.for` so the\n * marker survives module-realm boundaries — `@sanity/cli-core` re-derives the\n * same global symbol rather than importing it.\n */\nconst WORKBENCH_CONFIG: unique symbol = Symbol.for('sanity.workbench.defineConfig')\n\n/**\n * A branded workbench config as the CLI reads it: bound to its target app by\n * `appType`, not carrying its own app identity. The deploy/undeploy/build paths\n * discriminate it via {@link isWorkbenchConfig}.\n * @public\n */\nexport interface WorkbenchConfig {\n appType: 'media-library'\n fields: MediaLibraryField[]\n organizationId: string\n readonly [WORKBENCH_CONFIG]: true\n}\n\n/**\n * Whether `app` is a branded `unstable_defineMediaLibrary(...)` config — a\n * config-carrier rather than an app. Configs live in `cliConfig.app` alongside\n * apps but resolve through `resolveWorkbenchConfig`, not `resolveWorkbenchApp`.\n * @public\n */\nexport function isWorkbenchConfig(app: unknown): app is WorkbenchConfig {\n return typeof app === 'object' && app !== null && WORKBENCH_CONFIG in app\n}\n\n/**\n * Declare the Sanity Media Library config. The Media Library is a Sanity-owned\n * singleton, so this is not an app — it carries no slug or title, only the\n * target `appType`, its owning organization, and the `fields` it contributes to\n * the installation's config.\n * @public\n */\nexport function unstable_defineMediaLibrary(input: DefineMediaLibraryInput): WorkbenchConfig {\n return Object.defineProperty(\n {appType: 'media-library', fields: input.fields ?? [], organizationId: input.organizationId},\n WORKBENCH_CONFIG,\n {configurable: false, enumerable: false, value: true, writable: false},\n ) as WorkbenchConfig\n}\n"],"names":["z","APP_SLUG_PATTERN","DockSchema","InterfaceDeclarationSchema","ServiceDeclarationSchema","APP_VISIBILITIES","ApplicationType","enum","DefineAppInputSchema","object","applicationType","optional","dock","entry","string","icon","check","regex","isSingleton","boolean","name","organizationId","slug","title","views","array","visibility","webWorkers","refine","input","names","undefined","map","view","webWorker","Set","size","length","error","path","WORKBENCH_APP","Symbol","for","isWorkbenchApp","app","defineApplication","Object","defineProperty","configurable","enumerable","value","writable","WORKBENCH_CONFIG","isWorkbenchConfig","unstable_defineMediaLibrary","appType","fields"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B,SAAQC,gBAAgB,QAAO,eAAc;AAC7C,SAAQC,UAAU,EAAEC,0BAA0B,EAAEC,wBAAwB,QAAO,gBAAe;AAE9F;;;;CAIC,GACD,MAAMC,mBAAmB;IAAC;IAAW;IAAY;CAAW;AAE5D;;;CAGC,GACD,MAAMC,kBAAkBN,EAAEO,IAAI,CAAC;IAAC;IAAW;IAAU;IAAU;CAAY;AAE3E;;;CAGC,GACD,OAAO,MAAMC,uBAAuBR,EACjCS,MAAM,CAAC;IACN;;;;KAIC,GACDC,iBAAiBV,EAAEW,QAAQ,CAACL;I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AMO,MAAM;AAC7C,GAAG,sFACH,2EAA2E;AAC3E,sEAAsE;AACtE,0EAA0E;AAC1ErC,EAAE4B,MAAM,CAAC,CAACC,QAAU,CAAEA,CAAAA,MAAMnB,eAAe,KAAK,YAAYmB,MAAMhB,KAAK,KAAKkB,SAAQ,GAAI;IACtFO,OAAO;IACPC,MAAM;QAAC;KAAQ;AACjB,IACD;AAYH;;;;;CAKC,GACD,MAAMC,gBAA+BC,OAAOC,GAAG,CAAC;AAiBhD;;;;CAIC,GACD,OAAO,SAASC,eAAeC,GAAY;IACzC,OAAO,OAAOA,QAAQ,YAAYA,QAAQ,QAAQJ,iBAAiBI;AACrE;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,kBAAkBhB,KAAqB;IACrD,OAAOiB,OAAOC,cAAc,CAAClB,OAAOW,eAAe;QACjDQ,cAAc;QACdC,YAAY;QACZC,OAAO;QACPC,UAAU;IACZ;AACF;AA2BA;;;;;;CAMC,GACD,MAAMC,mBAAkCX,OAAOC,GAAG,CAAC;AAenD;;;;;CAKC,GACD,OAAO,SAASW,kBAAkBT,GAAY;IAC5C,OAAO,OAAOA,QAAQ,YAAYA,QAAQ,QAAQQ,oBAAoBR;AACxE;AAEA;;;;;;CAMC,GACD,OAAO,SAASU,4BAA4BzB,KAA8B;IACxE,OAAOiB,OAAOC,cAAc,CAC1B;QAACQ,SAAS;QAAiBC,QAAQ3B,MAAM2B,MAAM,IAAI,EAAE;QAAEnC,gBAAgBQ,MAAMR,cAAc;IAAA,GAC3F+B,kBACA;QAACJ,cAAc;QAAOC,YAAY;QAAOC,OAAO;QAAMC,UAAU;IAAK;AAEzE"}
|
|
1
|
+
{"version":3,"sources":["../src/defineApp.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\nimport {APP_SLUG_PATTERN} from './appSlug.js'\nimport {DockSchema, InterfaceDeclarationSchema, WebWorkerDeclarationSchema} from './contract.js'\n\n/**\n * Dashboard visibility values. Mirrors `APP_VISIBILITIES` in `@sanity/cli-core`\n * (which can't be imported here — pulling the barrel into this lean module bloats\n * the config-load path). Kept in sync by a type test in `defineApp.test.ts`.\n */\nconst APP_VISIBILITIES = ['default', 'unlisted', 'disabled'] as const\n\n/**\n * Internal application discriminator. Sanity-owned singleton apps only;\n * validated by the schema but excluded from the public `DefineAppInput` type.\n */\nconst ApplicationType = z.enum(['coreApp', 'studio', 'canvas', 'dashboard'])\n\n/**\n * Runtime-validation schema for `defineApplication`.\n * @internal\n */\nexport const DefineAppInputSchema = z\n .object({\n /**\n * Internal — Sanity-owned singleton apps only. Validated here but excluded\n * from the public `DefineAppInput` type.\n * @internal\n */\n applicationType: z.optional(ApplicationType),\n /** Default placement inherited by window views. */\n dock: z.optional(DockSchema),\n /**\n * App entrypoint module. Defaults to `./src/App.tsx` when omitted. The build\n * derives the app's navigable `app` view from it. SDK apps only — setting it\n * on a studio is rejected (studio app views are not yet implemented).\n */\n entry: z.optional(z.string(\"must be a path to the app's entry file\")),\n /**\n * Path to an `.svg` file, relative to the project root. Other file types are\n * rejected. Wins over manifest/studio icon.\n */\n icon: z.optional(\n z.string().check(z.regex(/\\.svg$/i, 'App `icon` must be a path to an .svg file')),\n ),\n /** Sanity-owned app deployed once and installed per org. @internal */\n isSingleton: z.optional(z.boolean()),\n /**\n * Stable identity, distinct from the `slug` address. Defaults to `slug` when\n * omitted. Identity keys — the build id and derived interface ids — are built\n * from this, so renaming the slug no longer changes identity.\n */\n name: z.optional(\n z\n .string()\n .check(\n z.regex(\n APP_SLUG_PATTERN,\n 'App `name` must be lowercase alphanumerics and hyphens, starting with a letter and ending with an alphanumeric',\n ),\n ),\n ),\n /** Organization that owns the app — it runs in and deploys to this organization's Dashboard. */\n organizationId: z.string(\n \"App `organizationId` is required — pass the owning organization's ID to `defineApplication`\",\n ),\n slug: z\n .string('App `slug` is required — the hostname the application is created at on deploy')\n .check(\n z.regex(\n APP_SLUG_PATTERN,\n 'App `slug` must be lowercase alphanumerics and hyphens, starting with a letter and ending with an alphanumeric',\n ),\n ),\n /** User-facing app title. Wins over studio.config.ts title on merge. */\n title: z.string(),\n /** Views the app exposes (e.g. a window, dock panels, and tiles). */\n views: z.optional(z.array(InterfaceDeclarationSchema, 'must be an array of views')),\n /** Dashboard visibility of the app. Defaults to `default` when omitted. */\n visibility: z.optional(z.enum(APP_VISIBILITIES)),\n /** Background web workers the app runs. */\n webWorkers: z.optional(z.array(WebWorkerDeclarationSchema, 'must be an array of web workers')),\n })\n .check(\n z.refine((input) => {\n const names = [\n ...(input.entry === undefined ? [] : [input.name ?? input.slug]),\n ...(input.views ?? []).map((view) => view.name),\n ...(input.webWorkers ?? []).map((webWorker) => webWorker.name),\n ]\n return new Set(names).size === names.length\n }, '`name` must be unique across views and web workers. Rename one of the duplicates.'),\n // Studio app views are not implemented yet. A studio that declares `entry`\n // (the SDK app-view entrypoint) is rejected here rather than silently\n // generating one; studios keep navigating via their existing render path.\n z.refine((input) => !(input.applicationType === 'studio' && input.entry !== undefined), {\n error: 'App views for studios are not implemented yet',\n path: ['entry'],\n }),\n )\n\n/**\n * User-facing input for `defineApplication`. Excludes the internal\n * `applicationType` and `isSingleton`.\n * @public\n */\nexport type DefineAppInput = Omit<\n z.output<typeof DefineAppInputSchema>,\n 'applicationType' | 'isSingleton'\n>\n\n/**\n * Nominal brand the CLI discriminates on to enable the workbench build/deploy\n * codepath. Registered via `Symbol.for` so the marker survives module-realm\n * boundaries — `@sanity/cli-core` re-derives the same global symbol with\n * `Symbol.for` rather than importing it, so it stays internal to this module.\n */\nconst WORKBENCH_APP: unique symbol = Symbol.for('sanity.workbench.defineApp')\n\n/**\n * The branded result of `defineApplication`. Carries the same fields as the\n * input plus the internal brand — users only ever see `DefineAppInput`.\n * @public\n */\nexport type DefineAppResult = DefineAppInput & {readonly [WORKBENCH_APP]: true}\n\n/**\n * A branded app as the CLI reads it — the full schema shape, including the\n * internal fields `DefineAppInput` omits. Schema-derived so the narrowing\n * can't drift from what the schema validates.\n * @public\n */\nexport type WorkbenchApp = DefineAppResult & z.output<typeof DefineAppInputSchema>\n\n/**\n * Whether `app` is a branded `defineApplication(...)` result — the sole\n * workbench opt-in.\n * @public\n */\nexport function isWorkbenchApp(app: unknown): app is WorkbenchApp {\n return typeof app === 'object' && app !== null && WORKBENCH_APP in app\n}\n\n/**\n * Declare a Sanity Dashboard application. Identity at runtime — returns the same\n * object reference, tagged with the Dashboard brand. Field validation (the\n * `slug` pattern etc.) runs at build time in the CLI via `DefineAppInputSchema`;\n * this helper stays a thin, pure identity wrapper.\n * @public\n */\nexport function defineApplication(input: DefineAppInput): DefineAppResult {\n return Object.defineProperty(input, WORKBENCH_APP, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n }) as DefineAppResult\n}\n\n/**\n * One custom field a media library exposes. `src` default-exports a `defineField(...)` schema type.\n * @public\n */\nexport interface MediaLibraryField {\n /** Unique within the media library. */\n name: string\n src: string\n title: string\n\n /** Readable outside the owning organization. */\n public?: boolean\n}\n\n/**\n * Sanity-owned singleton, so authors don't name or title the app — only `organizationId` is required.\n * @public\n */\nexport interface DefineMediaLibraryInput {\n /** Organization that owns the media library — the CLI runs and deploys against it. */\n organizationId: string\n\n fields?: MediaLibraryField[]\n}\n\n/**\n * Nominal brand the CLI discriminates a config on. A config is *not* an app: it\n * carries no `slug`/`title`/application identity, only a target `appType`, its\n * owning `organizationId`, and its `fields`. Registered via `Symbol.for` so the\n * marker survives module-realm boundaries — `@sanity/cli-core` re-derives the\n * same global symbol rather than importing it.\n */\nconst WORKBENCH_CONFIG: unique symbol = Symbol.for('sanity.workbench.defineConfig')\n\n/**\n * A branded workbench config as the CLI reads it: bound to its target app by\n * `appType`, not carrying its own app identity. The deploy/undeploy/build paths\n * discriminate it via {@link isWorkbenchConfig}.\n * @public\n */\nexport interface WorkbenchConfig {\n appType: 'media-library'\n fields: MediaLibraryField[]\n organizationId: string\n readonly [WORKBENCH_CONFIG]: true\n}\n\n/**\n * Whether `app` is a branded `unstable_defineMediaLibrary(...)` config — a\n * config-carrier rather than an app. Configs live in `cliConfig.app` alongside\n * apps but resolve through `resolveWorkbenchConfig`, not `resolveWorkbenchApp`.\n * @public\n */\nexport function isWorkbenchConfig(app: unknown): app is WorkbenchConfig {\n return typeof app === 'object' && app !== null && WORKBENCH_CONFIG in app\n}\n\n/**\n * Declare the Sanity Media Library config. The Media Library is a Sanity-owned\n * singleton, so this is not an app — it carries no slug or title, only the\n * target `appType`, its owning organization, and the `fields` it contributes to\n * the installation's config.\n * @public\n */\nexport function unstable_defineMediaLibrary(input: DefineMediaLibraryInput): WorkbenchConfig {\n return Object.defineProperty(\n {appType: 'media-library', fields: input.fields ?? [], organizationId: input.organizationId},\n WORKBENCH_CONFIG,\n {configurable: false, enumerable: false, value: true, writable: false},\n ) as WorkbenchConfig\n}\n"],"names":["z","APP_SLUG_PATTERN","DockSchema","InterfaceDeclarationSchema","WebWorkerDeclarationSchema","APP_VISIBILITIES","ApplicationType","enum","DefineAppInputSchema","object","applicationType","optional","dock","entry","string","icon","check","regex","isSingleton","boolean","name","organizationId","slug","title","views","array","visibility","webWorkers","refine","input","names","undefined","map","view","webWorker","Set","size","length","error","path","WORKBENCH_APP","Symbol","for","isWorkbenchApp","app","defineApplication","Object","defineProperty","configurable","enumerable","value","writable","WORKBENCH_CONFIG","isWorkbenchConfig","unstable_defineMediaLibrary","appType","fields"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B,SAAQC,gBAAgB,QAAO,eAAc;AAC7C,SAAQC,UAAU,EAAEC,0BAA0B,EAAEC,0BAA0B,QAAO,gBAAe;AAEhG;;;;CAIC,GACD,MAAMC,mBAAmB;IAAC;IAAW;IAAY;CAAW;AAE5D;;;CAGC,GACD,MAAMC,kBAAkBN,EAAEO,IAAI,CAAC;IAAC;IAAW;IAAU;IAAU;CAAY;AAE3E;;;CAGC,GACD,OAAO,MAAMC,uBAAuBR,EACjCS,MAAM,CAAC;IACN;;;;KAIC,GACDC,iBAAiBV,EAAEW,QAAQ,CAACL;IAC5B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MAAM;AAC7C,GAAG,sFACH,2EAA2E;AAC3E,sEAAsE;AACtE,0EAA0E;AAC1ErC,EAAE4B,MAAM,CAAC,CAACC,QAAU,CAAEA,CAAAA,MAAMnB,eAAe,KAAK,YAAYmB,MAAMhB,KAAK,KAAKkB,SAAQ,GAAI;IACtFO,OAAO;IACPC,MAAM;QAAC;KAAQ;AACjB,IACD;AAYH;;;;;CAKC,GACD,MAAMC,gBAA+BC,OAAOC,GAAG,CAAC;AAiBhD;;;;CAIC,GACD,OAAO,SAASC,eAAeC,GAAY;IACzC,OAAO,OAAOA,QAAQ,YAAYA,QAAQ,QAAQJ,iBAAiBI;AACrE;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,kBAAkBhB,KAAqB;IACrD,OAAOiB,OAAOC,cAAc,CAAClB,OAAOW,eAAe;QACjDQ,cAAc;QACdC,YAAY;QACZC,OAAO;QACPC,UAAU;IACZ;AACF;AA2BA;;;;;;CAMC,GACD,MAAMC,mBAAkCX,OAAOC,GAAG,CAAC;AAenD;;;;;CAKC,GACD,OAAO,SAASW,kBAAkBT,GAAY;IAC5C,OAAO,OAAOA,QAAQ,YAAYA,QAAQ,QAAQQ,oBAAoBR;AACxE;AAEA;;;;;;CAMC,GACD,OAAO,SAASU,4BAA4BzB,KAA8B;IACxE,OAAOiB,OAAOC,cAAc,CAC1B;QAACQ,SAAS;QAAiBC,QAAQ3B,MAAM2B,MAAM,IAAI,EAAE;QAAEnC,gBAAgBQ,MAAMR,cAAc;IAAA,GAC3F+B,kBACA;QAACJ,cAAc;QAAOC,YAAY;QAAOC,OAAO;QAAMC,UAAU;IAAK;AAEzE"}
|
package/dist/defineView.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { VIEW_CONTRACT_VERSION } from './contract.js';
|
|
2
1
|
/**
|
|
3
2
|
* Define a Sanity Dashboard view. The first argument narrows the component shape
|
|
4
3
|
* and the props each component receives — `"panel"` yields a `{title, panel}`
|
|
@@ -7,12 +6,13 @@ import { VIEW_CONTRACT_VERSION } from './contract.js';
|
|
|
7
6
|
* Returns the component(s) tagged with their surface and contract version, for
|
|
8
7
|
* the CLI build to generate render artifacts from. Used as the default export of
|
|
9
8
|
* a view's `src` file.
|
|
9
|
+
* @deprecated Default-export a plain React component from the view's `src` file instead.
|
|
10
10
|
* @public
|
|
11
11
|
*/ export function unstable_defineView(surface, components) {
|
|
12
12
|
return {
|
|
13
13
|
components,
|
|
14
14
|
surface,
|
|
15
|
-
version:
|
|
15
|
+
version: 1
|
|
16
16
|
};
|
|
17
17
|
}
|
|
18
18
|
|
package/dist/defineView.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/defineView.ts"],"sourcesContent":["import {type AssetSourceComponentProps} from '@sanity/types'\n\nimport {\n type TileSize,\n
|
|
1
|
+
{"version":3,"sources":["../src/defineView.ts"],"sourcesContent":["import {type AssetSourceComponentProps} from '@sanity/types'\n\nimport {\n type TileSize,\n type ViewComponent,\n type ViewComponentBaseProps,\n type ViewSurface,\n} from './contract.js'\n\n/** @public */\nexport type WindowViewProps = ViewComponentBaseProps<{\n name: string\n src: string\n surface: 'window'\n title: string\n}>\n\n/**\n * Props a panel component receives: its interface record, minus the\n * service-assigned `id`/`deployment_id` a local dev server can't provide. Mirrors\n * the `panel` record the workbench host renders from (the wire format owned by\n * `@sanity/workbench`); drift is guarded by the stamped contract version.\n * @public\n */\nexport type PanelViewProps = ViewComponentBaseProps<{\n name: string\n src: string\n surface: 'panel'\n title: string\n}>\n\n/**\n * The component slots a `panel` view exposes — each its own module-federation\n * island, typed with the panel props.\n * @public\n */\nexport interface PanelViewComponents {\n panel: ViewComponent<PanelViewProps>\n title: ViewComponent<PanelViewProps>\n}\n\n/**\n * A panel's view-component slot — the module-federation expose for one island.\n * @public\n */\nexport type PanelComponent = keyof PanelViewComponents\n\n/**\n * The component slots an `asset_source` view exposes — a single picker island,\n * typed with the studio asset-source props it renders behind. The props are\n * `@sanity/types`' `AssetSourceComponentProps` directly, so an authored picker\n * receives exactly what a studio `AssetSource.component` does.\n * @public\n */\nexport interface AssetSourceViewComponents {\n asset_source: ViewComponent<AssetSourceComponentProps>\n}\n\n/**\n * An asset source's view-component slot — the module-federation expose for its\n * one island.\n * @public\n */\nexport type AssetSourceComponent = keyof AssetSourceViewComponents\n\n/**\n * Props a tile component receives: its own interface record plus its footprint\n * `size`, so it can render per family. Mirrors the\n * `tile` record the dashboard host renders from; drift is guarded by the stamped\n * contract version. Placement `order` is host-only metadata, not surfaced here.\n * @public\n */\nexport type TileViewProps = ViewComponentBaseProps<{\n name: string\n size: TileSize\n src: string\n surface: 'tile'\n title: string\n}>\n\n/**\n * The component slot a `tile` view exposes — a single island, typed with the\n * tile props.\n * @public\n */\nexport interface TileViewComponents {\n tile: ViewComponent<TileViewProps>\n}\n\n/**\n * A tile's view-component slot — the module-federation expose for its one island.\n * @public\n */\nexport type TileComponent = keyof TileViewComponents\n\n/**\n * The components each view surface exposes.\n * @public\n */\nexport interface ViewComponentsBySurface {\n asset_source: AssetSourceViewComponents\n panel: PanelViewComponents\n tile: TileViewComponents\n window: ViewComponent<WindowViewProps>\n}\n\n/**\n * The result of `unstable_defineView`: the author's component(s), the view surface,\n * and the internal contract version the build artifact targets.\n * @public\n */\nexport interface DefinedView<TSurface extends ViewSurface = ViewSurface> {\n readonly components: ViewComponentsBySurface[TSurface]\n readonly surface: TSurface\n /** @internal */\n readonly version: 1\n}\n\n/**\n * Define a Sanity Dashboard view. The first argument narrows the component shape\n * and the props each component receives — `\"panel\"` yields a `{title, panel}`\n * record whose components are typed with the panel props.\n *\n * Returns the component(s) tagged with their surface and contract version, for\n * the CLI build to generate render artifacts from. Used as the default export of\n * a view's `src` file.\n * @deprecated Default-export a plain React component from the view's `src` file instead.\n * @public\n */\nexport function unstable_defineView<TSurface extends ViewSurface>(\n surface: TSurface,\n components: ViewComponentsBySurface[TSurface],\n): DefinedView<TSurface> {\n return {components, surface, version: 1}\n}\n"],"names":["unstable_defineView","surface","components","version"],"mappings":"AAsHA;;;;;;;;;;CAUC,GACD,OAAO,SAASA,oBACdC,OAAiB,EACjBC,UAA6C;IAE7C,OAAO;QAACA;QAAYD;QAASE,SAAS;IAAC;AACzC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/deriveInterfaces.ts"],"sourcesContent":["import {type CliConfig} from '@sanity/cli-core'\n\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from './actions/build/vite/constants.js'\nimport {\n type Dock,\n interfaceContractVersion,\n type InterfaceKind,\n interfaceModuleId,\n type PanelView,\n type TileInterfaceMetadata,\n type ViewPlacementMetadata,\n type WindowView,\n} from './contract.js'\nimport {isWorkbenchApp} from './defineApp.js'\n\n/** What a studio exposes as `./App` — the generated entry that renders `sanity.config.ts`. */\nconst GENERATED_ENTRY = `./${RUNTIME_DIR}/${FEDERATION_FILE_NAME}.jsx`\n\ninterface DerivedInterfaceBase {\n /** CLI-minted for a local interface; a deployed one gets its id from Brett. */\n id: string\n moduleId: string\n name: string\n src: string\n title: string\n\n version
|
|
1
|
+
{"version":3,"sources":["../src/deriveInterfaces.ts"],"sourcesContent":["import {type CliConfig} from '@sanity/cli-core'\n\nimport {FEDERATION_FILE_NAME, RUNTIME_DIR} from './actions/build/vite/constants.js'\nimport {\n type Dock,\n interfaceContractVersion,\n type InterfaceKind,\n interfaceModuleId,\n type PanelView,\n type TileInterfaceMetadata,\n type ViewPlacementMetadata,\n type WindowView,\n} from './contract.js'\nimport {isWorkbenchApp} from './defineApp.js'\n\n/** What a studio exposes as `./App` — the generated entry that renders `sanity.config.ts`. */\nconst GENERATED_ENTRY = `./${RUNTIME_DIR}/${FEDERATION_FILE_NAME}.jsx`\n\ninterface DerivedInterfaceBase {\n /** CLI-minted for a local interface; a deployed one gets its id from Brett. */\n id: string\n moduleId: string\n name: string\n src: string\n title: string\n\n version: string\n}\n\n/** @internal */\nexport type DerivedInterface =\n | (DerivedInterfaceBase & {metadata: null; surface: 'asset_source'})\n | (DerivedInterfaceBase & {metadata: null; type: 'worker'})\n | (DerivedInterfaceBase & {metadata: TileInterfaceMetadata; surface: 'tile'})\n | (DerivedInterfaceBase & {metadata: ViewPlacementMetadata | null; surface: 'panel'})\n | (DerivedInterfaceBase & {metadata: ViewPlacementMetadata | null; surface: 'window'})\n\n/**\n * `appTitle` titles the window where a deploy resolved one through `--title`;\n * dev takes it from the config.\n * @internal\n */\nexport function deriveInterfaces(\n app: CliConfig['app'],\n {appTitle, isApp}: {appTitle?: string; isApp: boolean},\n): DerivedInterface[] {\n if (!isWorkbenchApp(app)) return []\n\n // The schema rejects a *declared* studio with an `entry`; `isApp` is resolved\n // from the project, so a detected one only fails here.\n if (!isApp && app.entry !== undefined) {\n throw new Error('App views for studios are not implemented yet')\n }\n const entry = isApp ? app.entry : GENERATED_ENTRY\n\n // Identity, not address: interface ids and the window name key on `name`\n // (which defaults to `slug`, so existing apps derive byte-identical ids).\n const appName = app.name ?? app.slug\n\n const shared = (\n kind: InterfaceKind,\n declaration: {name: string; src: string; title: string},\n ) => ({\n id: `${appName}-${kind}-${declaration.name}`,\n moduleId: interfaceModuleId(kind, declaration.name),\n name: declaration.name,\n src: declaration.src,\n title: declaration.title,\n version: interfaceContractVersion(kind),\n })\n\n const placementMetadata = (\n dock?: Dock,\n surface: (PanelView | WindowView)['surface'] = 'window',\n ): ViewPlacementMetadata | null => {\n const group = surface === 'panel' ? undefined : (dock?.group ?? app.dock?.group)\n const order = dock?.order ?? app.dock?.order\n if (group === undefined && order === undefined) return null\n return {\n dock: {\n ...(group === undefined ? {} : {group}),\n ...(order === undefined ? {} : {order}),\n },\n }\n }\n\n return [\n ...(app.views ?? []).map((view): DerivedInterface => {\n if (view.surface === 'tile') {\n return {\n ...shared(view.surface, view),\n metadata:\n view.order === undefined ? {size: view.size} : {order: view.order, size: view.size},\n surface: view.surface,\n }\n }\n if (view.surface === 'panel' || view.surface === 'window') {\n return {\n ...shared(view.surface, view),\n metadata: placementMetadata(view.dock, view.surface),\n surface: view.surface,\n }\n }\n return {...shared(view.surface, view), metadata: null, surface: view.surface}\n }),\n ...(app.webWorkers ?? []).map((webWorker): DerivedInterface => ({\n ...shared('worker', webWorker),\n metadata: null,\n type: 'worker',\n })),\n ...(entry === undefined\n ? []\n : [\n {\n ...shared('window', {name: appName, src: entry, title: appTitle ?? app.title}),\n metadata: placementMetadata(),\n surface: 'window' as const,\n },\n ]),\n ]\n}\n"],"names":["FEDERATION_FILE_NAME","RUNTIME_DIR","interfaceContractVersion","interfaceModuleId","isWorkbenchApp","GENERATED_ENTRY","deriveInterfaces","app","appTitle","isApp","entry","undefined","Error","appName","name","slug","shared","kind","declaration","id","moduleId","src","title","version","placementMetadata","dock","surface","group","order","views","map","view","metadata","size","webWorkers","webWorker","type"],"mappings":"AAEA,SAAQA,oBAAoB,EAAEC,WAAW,QAAO,oCAAmC;AACnF,SAEEC,wBAAwB,EAExBC,iBAAiB,QAKZ,gBAAe;AACtB,SAAQC,cAAc,QAAO,iBAAgB;AAE7C,4FAA4F,GAC5F,MAAMC,kBAAkB,CAAC,EAAE,EAAEJ,YAAY,CAAC,EAAED,qBAAqB,IAAI,CAAC;AAqBtE;;;;CAIC,GACD,OAAO,SAASM,iBACdC,GAAqB,EACrB,EAACC,QAAQ,EAAEC,KAAK,EAAsC;IAEtD,IAAI,CAACL,eAAeG,MAAM,OAAO,EAAE;IAEnC,8EAA8E;IAC9E,uDAAuD;IACvD,IAAI,CAACE,SAASF,IAAIG,KAAK,KAAKC,WAAW;QACrC,MAAM,IAAIC,MAAM;IAClB;IACA,MAAMF,QAAQD,QAAQF,IAAIG,KAAK,GAAGL;IAElC,yEAAyE;IACzE,0EAA0E;IAC1E,MAAMQ,UAAUN,IAAIO,IAAI,IAAIP,IAAIQ,IAAI;IAEpC,MAAMC,SAAS,CACbC,MACAC,cACI,CAAA;YACJC,IAAI,GAAGN,QAAQ,CAAC,EAAEI,KAAK,CAAC,EAAEC,YAAYJ,IAAI,EAAE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AEC,UAAU;gBAAMN,SAASK,KAAKL,OAAO;YAAA;QAC9E;WACG,AAACnB,CAAAA,IAAI2B,UAAU,IAAI,EAAE,AAAD,EAAGJ,GAAG,CAAC,CAACK,YAAiC,CAAA;gBAC9D,GAAGnB,OAAO,UAAUmB,UAAU;gBAC9BH,UAAU;gBACVI,MAAM;YACR,CAAA;WACI1B,UAAUC,YACV,EAAE,GACF;YACE;gBACE,GAAGK,OAAO,UAAU;oBAACF,MAAMD;oBAASQ,KAAKX;oBAAOY,OAAOd,YAAYD,IAAIe,KAAK;gBAAA,EAAE;gBAC9EU,UAAUR;gBACVE,SAAS;YACX;SACD;KACN;AACH"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { WEB_WORKER_CONTRACT_VERSION } from './contract.js';
|
|
2
|
+
/**
|
|
3
|
+
* Define a Sanity Dashboard background service. The first argument narrows the
|
|
4
|
+
* callback shape — `"worker"` runs the callback inside a Web Worker with the
|
|
5
|
+
* bus described on {@link WebWorkerProps}.
|
|
6
|
+
*
|
|
7
|
+
* Identity at runtime: returns the callback tagged with its type and the contract
|
|
8
|
+
* version, for the CLI build to generate a worker artifact from. Used as the
|
|
9
|
+
* default export of a service's `src` file.
|
|
10
|
+
* @deprecated Default-export a plain function that receives {@link WebWorkerProps} from the web worker's `src` file instead.
|
|
11
|
+
* @public
|
|
12
|
+
*/ export function unstable_defineService(type, run) {
|
|
13
|
+
return {
|
|
14
|
+
run,
|
|
15
|
+
type,
|
|
16
|
+
version: WEB_WORKER_CONTRACT_VERSION
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=webWorker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/webWorker.ts"],"sourcesContent":["import {\n type EventTopic,\n type MessageBus,\n type MessageBusAbortOptions,\n type MessageBusMessage,\n type PayloadOf,\n type ReplyOf,\n type StateTopic,\n type ValueOf,\n} from '@sanity/sdk/dashboard'\n\nimport {WEB_WORKER_CONTRACT_VERSION, type WebWorkerType} from './contract.js'\n\n/**\n * The web worker's own declaration.\n * @public\n */\nexport interface WebWorkerInfo {\n readonly name: string\n readonly type: string\n}\n\n/**\n * The message bus as a web worker sees it: the SDK's `MessageBus` without the\n * `subscribe` forms that return observables, which would make the web worker's\n * project install rxjs. There is no `disconnect`: Dashboard owns the connection\n * and ends it when it stops the worker.\n * @public\n */\nexport interface WebWorkerBus extends Omit<MessageBus, 'subscribe'> {\n /** Runs a responder for each event until its signal aborts. */\n subscribe<K extends EventTopic>(\n type: K,\n handler: (message: MessageBusMessage<PayloadOf<K>, ReplyOf<K>, K>) => void,\n options?: MessageBusAbortOptions,\n ): void\n /** Runs a handler for each state value until its signal aborts. */\n subscribe<K extends StateTopic>(\n type: K,\n handler: (value: ValueOf<K>) => void,\n options?: MessageBusAbortOptions,\n ): void\n}\n\n/**\n * Context every service callback receives when its worker starts. Mirrors how a\n * view component receives its `view` — the service receives its own `service`.\n * @deprecated Use {@link WebWorkerProps}.\n * @public\n */\nexport interface ServiceContext {\n readonly bus: WebWorkerBus\n readonly service: WebWorkerInfo\n}\n\n/**\n * Props a web worker function receives when its worker starts. The default\n * export of a web worker's `src` file runs once inside the worker.\n *\n * `bus` is its connection to the Dashboard message bus:\n * `bus.emit` sends an event (such as a dock-badge update), `bus.query` reads the\n * current value of a state topic, and `bus.subscribe` runs a handler on each\n * new value of a state topic, or on each event of an event topic, until its\n * `signal` aborts. A refused, unanswered or timed-out `emit` or `query` rejects\n * with an `Error` named `MessageBusError` whose `code` says why; it is not an\n * instance of the SDK's `MessageBusError` class. When the Dashboard's refusal\n * says how to fix it, the error also carries `fix` and `docsUrl`. A refused\n * `subscribe` has no error: its handler never runs, and the Dashboard reports\n * the refusal in the browser console.\n *\n * An event handler answers the sender with `message.reply(value)` or refuses\n * with `message.reject(reason)`; one that throws refuses with code\n * `HANDLER_THREW`. For example, a worker that keeps a snapshot for its app's\n * views, which listen with `useWorker` first and then post to it. A view's post\n * arrives on `workers.post` as `{name, payload}`, and `workers.message` reaches\n * only this app's views:\n *\n * ```ts\n * export default ({bus}: WebWorkerProps) => {\n * const controller = new AbortController()\n * bus.subscribe('workers.post', (message) => message.reply(snapshot), {\n * signal: controller.signal,\n * })\n * // Views that are already listening post again.\n * bus.emit('workers.message', {type: 'welcome'})\n * return () => controller.abort()\n * }\n * ```\n *\n * The function can return a disposer, which runs when Dashboard stops the\n * worker. By then the bus is closed: subscriptions have ended, `emit` and\n * `query` reject with code `ABORTED`, and `subscribe` throws that error.\n * @public\n */\nexport interface WebWorkerProps {\n readonly bus: WebWorkerBus\n readonly worker: WebWorkerInfo\n}\n\n/**\n * A service callback. Runs once inside the worker on start; returns an optional\n * disposer the host calls before terminating the worker.\n * @deprecated Default-export a plain function that receives {@link WebWorkerProps} instead.\n * @public\n */\nexport type ServiceCallback = (context: ServiceContext) => (() => void) | void\n\n/** The callback shape each service type defines, keyed by type. */\ninterface ServiceCallbacksByType {\n worker: ServiceCallback\n}\n\n/**\n * The result of `unstable_defineService`: the author's callback, the service\n * type, and the internal contract version the worker artifact targets.\n * @deprecated Default-export a plain function that receives {@link WebWorkerProps} instead.\n * @public\n */\nexport interface DefinedService<TType extends WebWorkerType = WebWorkerType> {\n readonly run: ServiceCallbacksByType[TType]\n readonly type: TType\n /** @internal */\n readonly version: typeof WEB_WORKER_CONTRACT_VERSION\n}\n\n/**\n * Define a Sanity Dashboard background service. The first argument narrows the\n * callback shape — `\"worker\"` runs the callback inside a Web Worker with the\n * bus described on {@link WebWorkerProps}.\n *\n * Identity at runtime: returns the callback tagged with its type and the contract\n * version, for the CLI build to generate a worker artifact from. Used as the\n * default export of a service's `src` file.\n * @deprecated Default-export a plain function that receives {@link WebWorkerProps} from the web worker's `src` file instead.\n * @public\n */\nexport function unstable_defineService<TType extends WebWorkerType>(\n type: TType,\n run: ServiceCallbacksByType[TType],\n): DefinedService<TType> {\n return {run, type, version: WEB_WORKER_CONTRACT_VERSION}\n}\n\n/**\n * @deprecated Use `WebWorkerBus`.\n * @public\n */\nexport type ServiceBus = WebWorkerBus\n\n/**\n * @deprecated Use `WebWorkerInfo`.\n * @public\n */\nexport type ServiceInfo = WebWorkerInfo\n"],"names":["WEB_WORKER_CONTRACT_VERSION","unstable_defineService","type","run","version"],"mappings":"AAWA,SAAQA,2BAA2B,QAA2B,gBAAe;AAkH7E;;;;;;;;;;CAUC,GACD,OAAO,SAASC,uBACdC,IAAW,EACXC,GAAkC;IAElC,OAAO;QAACA;QAAKD;QAAME,SAASJ;IAA2B;AACzD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/workbench-cli",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.16.1",
|
|
4
4
|
"description": "Internal implementation detail of the Sanity CLI's unstable workbench support. Not intended for direct use.",
|
|
5
5
|
"homepage": "https://github.com/sanity-io/cli",
|
|
6
6
|
"bugs": "https://github.com/sanity-io/cli/issues",
|
|
@@ -66,30 +66,30 @@
|
|
|
66
66
|
},
|
|
67
67
|
"dependencies": {
|
|
68
68
|
"@module-federation/runtime": "2.9.3",
|
|
69
|
-
"@module-federation/vite": "1.23.
|
|
70
|
-
"@sanity/cli-core": "^3.
|
|
69
|
+
"@module-federation/vite": "1.23.11",
|
|
70
|
+
"@sanity/cli-core": "^3.15.1",
|
|
71
71
|
"@sanity/sdk": "^3.12.0",
|
|
72
72
|
"@sanity/types": "^6.22.0",
|
|
73
|
-
"@vitejs/plugin-react": "^6.
|
|
74
|
-
"form-data": "^4.0.
|
|
73
|
+
"@vitejs/plugin-react": "^6.3.0",
|
|
74
|
+
"form-data": "^4.0.6",
|
|
75
75
|
"rxjs": "^7.8.2",
|
|
76
|
-
"semver": "^7.8.
|
|
76
|
+
"semver": "^7.8.6",
|
|
77
77
|
"tar": "^7.5.22",
|
|
78
|
-
"vite": "^8.3.
|
|
78
|
+
"vite": "^8.3.8",
|
|
79
79
|
"zod": "^4.6.7"
|
|
80
80
|
},
|
|
81
81
|
"devDependencies": {
|
|
82
82
|
"@eslint/compat": "^2.1.0",
|
|
83
83
|
"@repo/package.config": "0.0.1",
|
|
84
84
|
"@repo/tsconfig": "3.70.0",
|
|
85
|
-
"@sanity/cli-test": "
|
|
85
|
+
"@sanity/cli-test": "25.0.1",
|
|
86
86
|
"@sanity/eslint-config-cli": "^1.1.3",
|
|
87
87
|
"@sanity/pkg-utils": "^12.3.4",
|
|
88
|
-
"@swc/cli": "^0.8.
|
|
89
|
-
"@swc/core": "^1.
|
|
88
|
+
"@swc/cli": "^0.8.2",
|
|
89
|
+
"@swc/core": "^1.16.22",
|
|
90
90
|
"@types/node": "^22.20.5",
|
|
91
91
|
"@types/react": "^19.3.0",
|
|
92
|
-
"@types/semver": "^7.
|
|
92
|
+
"@types/semver": "^7.8.0",
|
|
93
93
|
"@vitest/coverage-istanbul": "^5.1.0",
|
|
94
94
|
"eslint": "^10.7.0",
|
|
95
95
|
"jsdom": "^29.1.1",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/actions/build/services/artifact.ts"],"sourcesContent":["import {SERVICE_CONTRACT_VERSION, type ServiceType} from '../../../contract.js'\nimport {type GeneratedArtifact} from '../artifact.js'\n\n/** The worker bus client the generated `worker.js` imports; see the extension-artifacts plugin's alias. */\nexport const WORKER_BUS_ENTRY = '@sanity/workbench-cli/_internal_worker_bus'\n\n/** Subdirectory under the federation runtime dir where service artifacts live. */\nconst SERVICES_DIR_NAME = 'services'\n\nconst SERVICE_TYPES: readonly ServiceType[] = ['worker']\n\n/**\n * A service to generate a worker artifact for. The `src` file default-exports\n * an `unstable_defineService(...)` result; the build emits a self-contained Web\n * Worker bundle plus a loader module that hands the host its URL.\n * @internal\n */\nexport interface ServiceArtifact {\n /** Service name, unique within the app. */\n name: string\n /** Path to the service `src` file, relative to the app root (or absolute). */\n src: string\n /** Service type, e.g. `\"worker\"`. */\n type: string\n}\n\n/**\n * Expand each service into its two generated artifacts: a self-contained worker\n * bundle (imports the user's `src`, runs the callback) and a loader module the\n * host loads to read the worker's URL. Only the loader is a federation expose —\n * the host reaches the worker bundle through it, never directly.\n */\nexport function serviceArtifacts(services: readonly ServiceArtifact[]): GeneratedArtifact[] {\n return services\n .filter((service) => (SERVICE_TYPES as readonly string[]).includes(service.type))\n .flatMap((service): GeneratedArtifact[] => {\n const dir = `${SERVICES_DIR_NAME}/${service.name}`\n return [\n {\n path: `${dir}/worker.js`,\n source: ({resolveImport}) =>\n serviceWorkerArtifactSource({\n importPath: resolveImport(service.src),\n service,\n }),\n },\n {\n expose: `./${dir}`,\n path: `${dir}/index.js`,\n source: () => serviceLoaderArtifactSource({service}),\n },\n ]\n })\n}\n\n/**\n * Source for one service's **worker** bundle — the Web Worker entry. Imports\n * the user's `unstable_defineService` result and runs its callback with the\n * service's own declaration (mirroring how a view component receives its\n * `view`) and a message bus client (`workerBus.ts`), then wires the returned\n * disposer to the host's terminate message.\n * Crashes — and the worker's `console.*`, which is patched to forward to the\n * host — are surfaced through the host logger (the host owns logging; a worker's\n * own console isn't visible in the page DevTools anyway).\n */\nfunction serviceWorkerArtifactSource(input: {\n importPath: string\n service: {name: string; type: string}\n}): string {\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport service from ${JSON.stringify(input.importPath)}\nimport { createWorkerBus } from ${JSON.stringify(WORKER_BUS_ENTRY)}\n\nconst SERVICE = { type: ${JSON.stringify(input.service.type)}, name: ${JSON.stringify(input.service.name)} }\n\n// Bridge the worker's console to the host. A worker's own console isn't visible\n// in the page DevTools, so patch console.* to forward each call as a message\n// the host re-emits through the workbench logger — any console.log in the\n// service (or its deps) just shows up in the page console.\nconst __format = (arg) => {\n if (typeof arg === 'string') return arg\n try { return JSON.stringify(arg) } catch (_) { return String(arg) }\n}\nfor (const __level of ['log', 'info', 'warn', 'error', 'debug']) {\n const __native = typeof console[__level] === 'function' ? console[__level].bind(console) : () => {}\n console[__level] = (...args) => {\n __native(...args)\n try {\n self.postMessage({ kind: 'workbench.worker.log', payload: { level: __level, message: args.map(__format).join(' ') } })\n } catch (_) {}\n }\n}\n\nconst { bus, close: closeBus, receive: receiveBus } = createWorkerBus()\n\nlet dispose\ntry {\n const result = service.run({ bus, service: SERVICE })\n if (typeof result === 'function') dispose = result\n} catch (error) {\n self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(error) } })\n}\n\nself.addEventListener('message', (event) => {\n if (!event.data) return\n if (event.data.kind === 'workbench.worker.terminate') {\n // Close the bus first: the host has disconnected, so the disposer's bus calls must fail at once.\n closeBus()\n try { dispose && dispose() } finally { self.close() }\n } else {\n receiveBus(event.data)\n }\n})\n\nself.addEventListener('error', (event) => {\n self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(event.message || event) } })\n})\n\n// An async run callback (or async work it kicks off) rejects without hitting\n// the synchronous try/catch above; module workers surface that as\n// 'unhandledrejection' on self, not 'error'. Forward it so the crash reaches\n// the host either way.\nself.addEventListener('unhandledrejection', (event) => {\n self.postMessage({ kind: 'workbench.worker.error', payload: { message: String(event.reason) } })\n})\n`\n}\n\n/**\n * Source for one service's **loader** — the module-federation expose. Hands the\n * host the worker bundle's URL (via Vite `?worker&url`) plus the service's\n * type/version.\n *\n * A URL (not an inlined worker) on purpose: the host can't `new Worker()` it\n * directly — cross-origin in dev/prod, and `?worker&inline` only self-contains\n * the worker in a build, not under `sanity dev`. Instead the host bootstraps a\n * same-origin worker that dynamically `import()`s this URL, so the worker\n * resolves its own imports against the app origin. Works in dev and build alike.\n *\n * No HMR boundary: a worker lives in its own `?worker&url` module graph with no\n * accepting importer, so Vite full-reloads the page on a `src` edit (which\n * re-loads the worker with the new code) — in-place worker HMR isn't possible.\n */\nfunction serviceLoaderArtifactSource(input: {service: {name: string; type: string}}): string {\n return `\\\n// This file is auto-generated on 'sanity build' / 'sanity dev'\n// Modifications to this file are automatically discarded\nimport workerUrl from './worker.js?worker&url'\n\n/** URL of the worker bundle, on the app's origin. */\nexport const url = workerUrl\n/** Service type and contract version, surfaced for the host to dispatch on. */\nexport const type = ${JSON.stringify(input.service.type)}\nexport const name = ${JSON.stringify(input.service.name)}\nexport const version = ${SERVICE_CONTRACT_VERSION}\n`\n}\n"],"names":["SERVICE_CONTRACT_VERSION","WORKER_BUS_ENTRY","SERVICES_DIR_NAME","SERVICE_TYPES","serviceArtifacts","services","filter","service","includes","type","flatMap","dir","name","path","source","resolveImport","serviceWorkerArtifactSource","importPath","src","expose","serviceLoaderArtifactSource","input","JSON","stringify"],"mappings":"AAAA,SAAQA,wBAAwB,QAAyB,uBAAsB;AAG/E,yGAAyG,GACzG,OAAO,MAAMC,mBAAmB,6CAA4C;AAE5E,gFAAgF,GAChF,MAAMC,oBAAoB;AAE1B,MAAMC,gBAAwC;IAAC;CAAS;AAiBxD;;;;;CAKC,GACD,OAAO,SAASC,iBAAiBC,QAAoC;IACnE,OAAOA,SACJC,MAAM,CAAC,CAACC,UAAY,AAACJ,cAAoCK,QAAQ,CAACD,QAAQE,IAAI,GAC9EC,OAAO,CAAC,CAACH;QACR,MAAMI,MAAM,GAAGT,kBAAkB,CAAC,EAAEK,QAAQK,IAAI,EAAE;QAClD,OAAO;YACL;gBACEC,MAAM,GAAGF,IAAI,UAAU,CAAC;gBACxBG,QAAQ,CAAC,EAACC,aAAa,EAAC,GACtBC,4BAA4B;wBAC1BC,YAAYF,cAAcR,QAAQW,GAAG;wBACrCX;oBACF;YACJ;YACA;gBACEY,QAAQ,CAAC,EAAE,EAAER,KAAK;gBAClBE,MAAM,GAAGF,IAAI,SAAS,CAAC;gBACvBG,QAAQ,IAAMM,4BAA4B;wBAACb;oBAAO;YACpD;SACD;IACH;AACJ;AAEA;;;;;;;;;CASC,GACD,SAASS,4BAA4BK,KAGpC;IACC,OAAO,CAAC;;;oBAGU,EAAEC,KAAKC,SAAS,CAACF,MAAMJ,UAAU,EAAE;gCACvB,EAAEK,KAAKC,SAAS,CAACtB,kBAAkB;;wBAE3C,EAAEqB,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACE,IAAI,EAAE,QAAQ,EAAEa,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACK,IAAI,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoD1G,CAAC;AACD;AAEA;;;;;;;;;;;;;;CAcC,GACD,SAASQ,4BAA4BC,KAA8C;IACjF,OAAO,CAAC;;;;;;;;oBAQU,EAAEC,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACE,IAAI,EAAE;oBACrC,EAAEa,KAAKC,SAAS,CAACF,MAAMd,OAAO,CAACK,IAAI,EAAE;uBAClC,EAAEZ,yBAAyB;AAClD,CAAC;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/actions/build/services/workerBus.ts"],"sourcesContent":["// Runs inside the service's Web Worker, bundled by Vite from the generated\n// `worker.js`. Keep it free of Node and of runtime imports: `@sanity/sdk` is\n// only ever imported for types.\nimport {\n type MessageBusEmitResult,\n type MessageBusErrorCode,\n type MessageBusMessage,\n type MessageBusMeta,\n} from '@sanity/sdk/dashboard'\n\nimport {type ServiceBus} from '../../../defineService.js'\n\nconst DEFAULT_TIMEOUT_MS = 5000\n\ninterface RequestOptions {\n signal?: AbortSignal\n timeout?: number | null\n}\n\ntype Outcome = {error: Error; ok: false} | {ok: true; value: unknown}\n\ntype Answer =\n | {error: {code: 'HANDLER_THREW' | 'REFUSED'; message: string}; ok: false}\n | {ok: true; value: unknown}\n\n// What a host refusal can carry besides its code and message, such as the fix\n// and docs link for one of the Dashboard's coded errors.\ninterface RefusalDetails {\n docsUrl?: string\n fix?: string\n}\n\ntype HostMessage =\n | {\n error: RefusalDetails & {code: MessageBusErrorCode; message: string}\n id: number\n kind: 'workbench.bus.reply'\n ok: false\n }\n | {id: number; kind: 'workbench.bus.reply'; ok: true; value: unknown}\n | {id: number; kind: 'workbench.bus.value'; value: unknown}\n | {\n id: number\n kind: 'workbench.bus.message'\n messageId: number\n meta: MessageBusMeta\n payload: unknown\n type: string\n }\n | {kind: 'workbench.bus.cancel'; messageId: number}\n\n// Mirrors the SDK's MessageBusError: importing the class would pull the SDK\n// runtime into the worker bundle.\nconst busError = (code: MessageBusErrorCode, message?: string, details?: RefusalDetails): Error =>\n Object.assign(new Error(message || code), {\n code,\n docsUrl: details?.docsUrl,\n fix: details?.fix,\n name: 'MessageBusError',\n })\n\n/**\n * The worker's side of the `workbench.bus.*` wire contract. The host relays\n * each request to the Dashboard bus and stamps it with the worker's identity,\n * so the client only tracks ids.\n * @internal\n */\nexport function createWorkerBus(): {\n /**\n * The service author's API. The host owns the connection, opening it and ending it when\n * it terminates the worker, so the worker cannot end it.\n */\n bus: ServiceBus\n /**\n * The generated entry's terminate hook, not the author's. It sends nothing to\n * the host, which has already disconnected; it only marks the client closed so\n * the disposer's bus calls reject `ABORTED` at once instead of waiting out the\n * local timeout. Hence not `disconnect`.\n */\n close: () => void\n /**\n * The generated `worker.js` is the single `message` listener on `self` and\n * routes every kind (terminate to the disposer, `workbench.bus.*` here), the\n * way the host's `runWorker` routes to its relay.\n */\n receive: (data: unknown) => void\n} {\n const pending = new Map<number, (outcome: Outcome) => void>()\n // The worker can't tell a state topic from an event topic, so it stores every\n // handler alike; the host's `value` or `message` decides how it is called.\n const subscriptions = new Map<number, (value: unknown) => unknown>()\n const inFlight = new Map<number, AbortController>()\n let nextId = 0\n let closed = false\n\n // Posts a request and returns a function that creates its promise on first\n // call. Until then a reply, even an error, is only held: a rejected promise\n // nobody awaits would reach the worker's 'unhandledrejection' forwarder as a crash.\n function request(message: Record<string, unknown>, options: RequestOptions = {}) {\n const {signal, timeout} = options\n const id = ++nextId\n let outcome: Outcome | undefined\n let onOutcome: ((result: Outcome) => void) | undefined\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const settle = (result: Outcome) => {\n if (outcome) return\n outcome = result\n clearTimeout(timer)\n pending.delete(id)\n signal?.removeEventListener('abort', onAbort)\n onOutcome?.(result)\n }\n const onAbort = () => {\n self.postMessage({id, kind: 'workbench.bus.abort'})\n settle({error: busError('ABORTED'), ok: false})\n }\n\n if (closed || signal?.aborted) {\n outcome = {error: busError('ABORTED'), ok: false}\n } else {\n // An omitted timeout must stay absent on the wire, so the host applies its default.\n self.postMessage(timeout === undefined ? {...message, id} : {...message, id, timeout})\n pending.set(id, settle)\n // A host that predates the bus never replies; time out here too so the call still settles.\n if (timeout !== null) {\n timer = setTimeout(\n () => settle({error: busError('TIMEOUT'), ok: false}),\n timeout ?? DEFAULT_TIMEOUT_MS,\n )\n }\n signal?.addEventListener('abort', onAbort, {once: true})\n }\n\n let promise: Promise<unknown> | undefined\n return () =>\n (promise ??= new Promise((resolve, reject) => {\n onOutcome = (result) => (result.ok ? resolve(result.value) : reject(result.error))\n if (outcome) onOutcome(outcome)\n }))\n }\n\n // Matches the SDK's `invokeResponder`, so a responder behaves the same in a\n // worker as on the page.\n function respond(\n handler: (message: MessageBusMessage<unknown, unknown, string>) => unknown,\n {messageId, meta, payload, type}: Extract<HostMessage, {kind: 'workbench.bus.message'}>,\n ) {\n const controller = new AbortController()\n inFlight.set(messageId, controller)\n const answer = (result: Answer) => {\n if (inFlight.get(messageId) !== controller) return false\n inFlight.delete(messageId)\n self.postMessage({...result, kind: 'workbench.bus.answer', messageId})\n return true\n }\n const warnIfIgnored = (answered: boolean, action: string) => {\n if (answered) return\n // eslint-disable-next-line no-console -- the worker's console is bridged to the host logger\n console.warn(\n `Message bus ${action} ignored for \"${type}\": no waiting caller or already replied`,\n )\n }\n const fail = () => answer({error: {code: 'HANDLER_THREW', message: 'HANDLER_THREW'}, ok: false})\n\n try {\n const result = handler({\n meta,\n payload,\n reject: (reason) =>\n warnIfIgnored(\n answer({error: {code: 'REFUSED', message: reason ?? 'REFUSED'}, ok: false}),\n 'reject',\n ),\n reply: (value) => warnIfIgnored(answer({ok: true, value}), 'reply'),\n signal: controller.signal,\n type,\n })\n if (result instanceof Promise) result.catch(fail)\n } catch {\n fail()\n }\n }\n\n const bus = {\n emit: (topic: string, payload?: unknown, options?: RequestOptions) => {\n const awaitReply = request({kind: 'workbench.bus.emit', payload, topic}, options)\n const result: MessageBusEmitResult<unknown> = {\n catch: (onRejected) => awaitReply().then(undefined, onRejected),\n finally: (onFinally) => awaitReply().finally(onFinally),\n // eslint-disable-next-line unicorn/no-thenable -- awaiting arms reply failure handling; fire-and-forget does not.\n then: (onFulfilled, onRejected) => awaitReply().then(onFulfilled, onRejected),\n }\n return result\n },\n query: (topic: string, options?: RequestOptions) =>\n request({kind: 'workbench.bus.query', topic}, options)(),\n subscribe: (topic: string, handler: (value: unknown) => unknown, options?: RequestOptions) => {\n if (closed) throw busError('ABORTED')\n const signal = options?.signal\n if (signal?.aborted) return\n const id = ++nextId\n self.postMessage({id, kind: 'workbench.bus.subscribe', topic})\n subscriptions.set(id, handler)\n signal?.addEventListener(\n 'abort',\n () => {\n if (subscriptions.delete(id)) self.postMessage({id, kind: 'workbench.bus.abort'})\n },\n {once: true},\n )\n },\n }\n\n return {\n // The topic generics only exist at the call site; the wire carries plain strings.\n bus: bus as unknown as ServiceBus,\n close: () => {\n closed = true\n subscriptions.clear()\n const controllers = [...inFlight.values()]\n inFlight.clear()\n for (const controller of controllers) controller.abort()\n for (const settle of pending.values()) settle({error: busError('ABORTED'), ok: false})\n },\n receive: (data) => {\n const message = data as HostMessage\n switch (message.kind) {\n case 'workbench.bus.cancel': {\n const controller = inFlight.get(message.messageId)\n // Forget it first so an abort listener's reply is ignored.\n inFlight.delete(message.messageId)\n controller?.abort()\n return\n }\n case 'workbench.bus.message': {\n const handler = subscriptions.get(message.id)\n if (handler) respond(handler, message)\n return\n }\n case 'workbench.bus.reply': {\n const settle = pending.get(message.id)\n if (message.ok) {\n settle?.({ok: true, value: message.value})\n return\n }\n // A refused subscription has no promise to reject. The Dashboard prints the refusal.\n subscriptions.delete(message.id)\n settle?.({\n error: busError(message.error.code, message.error.message, message.error),\n ok: false,\n })\n return\n }\n case 'workbench.bus.value': {\n subscriptions.get(message.id)?.(message.value)\n }\n }\n },\n }\n}\n"],"names":["DEFAULT_TIMEOUT_MS","busError","code","message","details","Object","assign","Error","docsUrl","fix","name","createWorkerBus","pending","Map","subscriptions","inFlight","nextId","closed","request","options","signal","timeout","id","outcome","onOutcome","timer","settle","result","clearTimeout","delete","removeEventListener","onAbort","self","postMessage","kind","error","ok","aborted","undefined","set","setTimeout","addEventListener","once","promise","Promise","resolve","reject","value","respond","handler","messageId","meta","payload","type","controller","AbortController","answer","get","warnIfIgnored","answered","action","console","warn","fail","reason","reply","catch","bus","emit","topic","awaitReply","onRejected","then","finally","onFinally","onFulfilled","query","subscribe","close","clear","controllers","values","abort","receive","data"],"mappings":"AAAA,2EAA2E;AAC3E,6EAA6E;AAC7E,gCAAgC;AAUhC,MAAMA,qBAAqB;AAuC3B,4EAA4E;AAC5E,kCAAkC;AAClC,MAAMC,WAAW,CAACC,MAA2BC,SAAkBC,UAC7DC,OAAOC,MAAM,CAAC,IAAIC,MAAMJ,WAAWD,OAAO;QACxCA;QACAM,SAASJ,SAASI;QAClBC,KAAKL,SAASK;QACdC,MAAM;IACR;AAEF;;;;;CAKC,GACD,OAAO,SAASC;IAoBd,MAAMC,UAAU,IAAIC;IACpB,8EAA8E;IAC9E,2EAA2E;IAC3E,MAAMC,gBAAgB,IAAID;IAC1B,MAAME,WAAW,IAAIF;IACrB,IAAIG,SAAS;IACb,IAAIC,SAAS;IAEb,2EAA2E;IAC3E,4EAA4E;IAC5E,oFAAoF;IACpF,SAASC,QAAQf,OAAgC,EAAEgB,UAA0B,CAAC,CAAC;QAC7E,MAAM,EAACC,MAAM,EAAEC,OAAO,EAAC,GAAGF;QAC1B,MAAMG,KAAK,EAAEN;QACb,IAAIO;QACJ,IAAIC;QACJ,IAAIC;QAEJ,MAAMC,SAAS,CAACC;YACd,IAAIJ,SAAS;YACbA,UAAUI;YACVC,aAAaH;YACbb,QAA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F;wBACA,qFAAqF;wBACrFjC,cAAce,MAAM,CAAC1B,QAAQmB,EAAE;wBAC/BI,SAAS;4BACPS,OAAOlC,SAASE,QAAQgC,KAAK,CAACjC,IAAI,EAAEC,QAAQgC,KAAK,CAAChC,OAAO,EAAEA,QAAQgC,KAAK;4BACxEC,IAAI;wBACN;wBACA;oBACF;gBACA,KAAK;oBAAuB;wBAC1BtB,cAAc2C,GAAG,CAACtD,QAAQmB,EAAE,IAAInB,QAAQ4C,KAAK;oBAC/C;YACF;QACF;IACF;AACF"}
|
package/dist/defineService.js
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { SERVICE_CONTRACT_VERSION } from './contract.js';
|
|
2
|
-
/**
|
|
3
|
-
* Define a Sanity Dashboard background service. The first argument narrows the
|
|
4
|
-
* callback shape — `"worker"` runs the callback inside a Web Worker.
|
|
5
|
-
*
|
|
6
|
-
* The callback receives `bus`, its connection to the Dashboard message bus:
|
|
7
|
-
* `bus.emit` sends an event (such as a dock-badge update), `bus.query` reads the
|
|
8
|
-
* current value of a state topic, and `bus.subscribe` runs a handler on each
|
|
9
|
-
* new value of a state topic, or on each event of an event topic, until its
|
|
10
|
-
* `signal` aborts. A refused, unanswered or timed-out `emit` or `query` rejects
|
|
11
|
-
* with an `Error` named `MessageBusError` whose `code` says why; it is not an
|
|
12
|
-
* instance of the SDK's `MessageBusError` class. When the Dashboard's refusal
|
|
13
|
-
* says how to fix it, the error also carries `fix` and `docsUrl`. A refused
|
|
14
|
-
* `subscribe` has no error: its handler never runs, and the Dashboard reports
|
|
15
|
-
* the refusal in the browser console.
|
|
16
|
-
*
|
|
17
|
-
* An event handler answers the sender with `message.reply(value)` or refuses
|
|
18
|
-
* with `message.reject(reason)`; one that throws refuses with code
|
|
19
|
-
* `HANDLER_THREW`. For example, a service that keeps a snapshot for its app's
|
|
20
|
-
* views, which listen with `useWorker` first and then post to it. A view's post
|
|
21
|
-
* arrives on `workers.post` as `{name, payload}`, and `workers.message` reaches
|
|
22
|
-
* only this app's views:
|
|
23
|
-
*
|
|
24
|
-
* ```ts
|
|
25
|
-
* export default unstable_defineService('worker', ({bus}) => {
|
|
26
|
-
* const controller = new AbortController()
|
|
27
|
-
* bus.subscribe('workers.post', (message) => message.reply(snapshot), {
|
|
28
|
-
* signal: controller.signal,
|
|
29
|
-
* })
|
|
30
|
-
* // Views that are already listening post again.
|
|
31
|
-
* bus.emit('workers.message', {type: 'welcome'})
|
|
32
|
-
* return () => controller.abort()
|
|
33
|
-
* })
|
|
34
|
-
* ```
|
|
35
|
-
*
|
|
36
|
-
* The callback can return a disposer, which runs when Dashboard stops the
|
|
37
|
-
* worker. By then the bus is closed: subscriptions have ended, `emit` and
|
|
38
|
-
* `query` reject with code `ABORTED`, and `subscribe` throws that error.
|
|
39
|
-
*
|
|
40
|
-
* Identity at runtime: returns the callback tagged with its type and the contract
|
|
41
|
-
* version, for the CLI build to generate a worker artifact from. Used as the
|
|
42
|
-
* default export of a service's `src` file.
|
|
43
|
-
* @public
|
|
44
|
-
*/ export function unstable_defineService(type, run) {
|
|
45
|
-
return {
|
|
46
|
-
run,
|
|
47
|
-
type,
|
|
48
|
-
version: SERVICE_CONTRACT_VERSION
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
//# sourceMappingURL=defineService.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/defineService.ts"],"sourcesContent":["import {\n type EventTopic,\n type MessageBus,\n type MessageBusAbortOptions,\n type MessageBusMessage,\n type PayloadOf,\n type ReplyOf,\n type StateTopic,\n type ValueOf,\n} from '@sanity/sdk/dashboard'\n\nimport {SERVICE_CONTRACT_VERSION, type ServiceType} from './contract.js'\n\n/**\n * The service's own declaration, surfaced to the callback.\n * @public\n */\nexport interface ServiceInfo {\n readonly name: string\n readonly type: string\n}\n\n/**\n * The message bus as a service sees it: the SDK's `MessageBus` without the\n * `subscribe` forms that return observables, which would make the service's\n * project install rxjs. There is no `disconnect`: Dashboard owns the connection\n * and ends it when it stops the worker.\n * @public\n */\nexport interface ServiceBus extends Omit<MessageBus, 'subscribe'> {\n /** Runs a responder for each event until its signal aborts. */\n subscribe<K extends EventTopic>(\n type: K,\n handler: (message: MessageBusMessage<PayloadOf<K>, ReplyOf<K>, K>) => void,\n options?: MessageBusAbortOptions,\n ): void\n /** Runs a handler for each state value until its signal aborts. */\n subscribe<K extends StateTopic>(\n type: K,\n handler: (value: ValueOf<K>) => void,\n options?: MessageBusAbortOptions,\n ): void\n}\n\n/**\n * Context every service callback receives when its worker starts. Mirrors how a\n * view component receives its `view` — the service receives its own `service`.\n * @public\n */\nexport interface ServiceContext {\n readonly bus: ServiceBus\n readonly service: ServiceInfo\n}\n\n/**\n * A service callback. Runs once inside the worker on start; returns an optional\n * disposer the host calls before terminating the worker.\n * @public\n */\nexport type ServiceCallback = (context: ServiceContext) => (() => void) | void\n\n/** The callback shape each service type defines, keyed by type. */\ninterface ServiceCallbacksByType {\n worker: ServiceCallback\n}\n\n/**\n * The result of `unstable_defineService`: the author's callback, the service\n * type, and the internal contract version the worker artifact targets.\n * @public\n */\nexport interface DefinedService<TType extends ServiceType = ServiceType> {\n readonly run: ServiceCallbacksByType[TType]\n readonly type: TType\n /** @internal */\n readonly version: typeof SERVICE_CONTRACT_VERSION\n}\n\n/**\n * Define a Sanity Dashboard background service. The first argument narrows the\n * callback shape — `\"worker\"` runs the callback inside a Web Worker.\n *\n * The callback receives `bus`, its connection to the Dashboard message bus:\n * `bus.emit` sends an event (such as a dock-badge update), `bus.query` reads the\n * current value of a state topic, and `bus.subscribe` runs a handler on each\n * new value of a state topic, or on each event of an event topic, until its\n * `signal` aborts. A refused, unanswered or timed-out `emit` or `query` rejects\n * with an `Error` named `MessageBusError` whose `code` says why; it is not an\n * instance of the SDK's `MessageBusError` class. When the Dashboard's refusal\n * says how to fix it, the error also carries `fix` and `docsUrl`. A refused\n * `subscribe` has no error: its handler never runs, and the Dashboard reports\n * the refusal in the browser console.\n *\n * An event handler answers the sender with `message.reply(value)` or refuses\n * with `message.reject(reason)`; one that throws refuses with code\n * `HANDLER_THREW`. For example, a service that keeps a snapshot for its app's\n * views, which listen with `useWorker` first and then post to it. A view's post\n * arrives on `workers.post` as `{name, payload}`, and `workers.message` reaches\n * only this app's views:\n *\n * ```ts\n * export default unstable_defineService('worker', ({bus}) => {\n * const controller = new AbortController()\n * bus.subscribe('workers.post', (message) => message.reply(snapshot), {\n * signal: controller.signal,\n * })\n * // Views that are already listening post again.\n * bus.emit('workers.message', {type: 'welcome'})\n * return () => controller.abort()\n * })\n * ```\n *\n * The callback can return a disposer, which runs when Dashboard stops the\n * worker. By then the bus is closed: subscriptions have ended, `emit` and\n * `query` reject with code `ABORTED`, and `subscribe` throws that error.\n *\n * Identity at runtime: returns the callback tagged with its type and the contract\n * version, for the CLI build to generate a worker artifact from. Used as the\n * default export of a service's `src` file.\n * @public\n */\nexport function unstable_defineService<TType extends ServiceType>(\n type: TType,\n run: ServiceCallbacksByType[TType],\n): DefinedService<TType> {\n return {run, type, version: SERVICE_CONTRACT_VERSION}\n}\n"],"names":["SERVICE_CONTRACT_VERSION","unstable_defineService","type","run","version"],"mappings":"AAWA,SAAQA,wBAAwB,QAAyB,gBAAe;AAmExE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CC,GACD,OAAO,SAASC,uBACdC,IAAW,EACXC,GAAkC;IAElC,OAAO;QAACA;QAAKD;QAAME,SAASJ;IAAwB;AACtD"}
|