feat(release): prepare 1.1.0 candidate

This commit is contained in:
Yun Chan 2026-08-29 18:33:45 +09:00
parent 5a34f66981
commit 5205dcdfa9
736 changed files with 115667 additions and 12203 deletions

View file

@ -0,0 +1,50 @@
import AsyncStorage from '@react-native-async-storage/async-storage'
import { createUuidV4 } from '../../lib/random-id'
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
const PREFIX = 'd3ro:meeting-document-generation:v1:'
function requireUuid(value: string): void {
if (!UUID_PATTERN.test(value)) throw new Error('invalid_generation_identity')
}
function storageKey(userId: string, meetingId: string, templateId: string): string {
requireUuid(userId)
requireUuid(meetingId)
requireUuid(templateId)
return `${PREFIX}${userId}:${meetingId}:${templateId}`
}
export async function getOrCreateGenerationIdempotencyKey(
userId: string,
meetingId: string,
templateId: string,
): Promise<string> {
const key = storageKey(userId, meetingId, templateId)
const existing = await AsyncStorage.getItem(key)
if (existing !== null && UUID_PATTERN.test(existing)) return existing
if (existing !== null) await AsyncStorage.removeItem(key)
const created = createUuidV4()
await AsyncStorage.setItem(key, created)
return created
}
export async function clearGenerationIdempotencyKey(
userId: string,
meetingId: string,
templateId: string,
): Promise<void> {
await AsyncStorage.removeItem(storageKey(userId, meetingId, templateId))
}
export async function clearAllGenerationIdempotencyKeys(userId: string): Promise<void> {
requireUuid(userId)
const accountPrefix = `${PREFIX}${userId}:`
const keys = (await AsyncStorage.getAllKeys()).filter((key) => key.startsWith(accountPrefix))
if (keys.length > 0) await AsyncStorage.multiRemove(keys)
}
export async function clearEveryGenerationIdempotencyKey(): Promise<void> {
const keys = (await AsyncStorage.getAllKeys()).filter((key) => key.startsWith(PREFIX))
if (keys.length > 0) await AsyncStorage.multiRemove(keys)
}

View file

@ -0,0 +1,3 @@
export * from './types'
export * from './template-service'
export * from './generation-idempotency'

View file

@ -0,0 +1,446 @@
import type { RealtimeChannel, SupabaseClient } from '@supabase/supabase-js'
import type {
Database,
DictationTemplateField,
MeetingDocument,
TemplateKind,
UserTemplate,
UserTemplateSelection,
} from '@d3ro/api-client'
import { SUPABASE_URL } from '@d3ro/core/supabase-config'
import { supabase } from '../../lib/supabase'
import type {
GenerateMeetingDocumentOptions,
GeneratedMeetingDocument,
TemplateDraft,
TemplateLibrary,
} from './types'
export type TemplateServiceErrorCode =
| 'auth'
| 'builtin'
| 'conflict'
| 'forbidden'
| 'in-progress'
| 'network'
| 'not-found'
| 'provider'
| 'quota'
| 'server'
| 'validation'
export class TemplateServiceError extends Error {
constructor(
public readonly code: TemplateServiceErrorCode,
message: string,
public readonly retryable = false,
) {
super(message)
this.name = 'TemplateServiceError'
}
}
export interface TemplateSubscription {
unsubscribe: () => Promise<void>
}
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
const FIELD_ID_PATTERN = /^[A-Za-z][A-Za-z0-9_-]*$/
const TEMPLATE_COLUMNS = 'id,user_id,template_kind,builtin_key,name,description,fields,output_format,template_type,system_prompt,is_builtin,revision,created_at,updated_at'
const SELECTION_COLUMNS = 'user_id,template_kind,template_id,revision,updated_at'
function db(): SupabaseClient<Database> {
return supabase as unknown as SupabaseClient<Database>
}
function requireUuid(value: string, label: string): void {
if (!UUID_PATTERN.test(value)) {
throw new TemplateServiceError('auth', `A valid ${label} is required`)
}
}
function normalizeSingleLine(value: string): string {
return value.trim().replace(/\s+/g, ' ')
}
export function sanitizeTemplateSearch(value: string): string {
return value
.trim()
.slice(0, 100)
.replace(/[\\%_,().'";]/g, ' ')
.replace(/\s+/g, ' ')
.trim()
}
export function normalizeTemplateField(
field: DictationTemplateField,
index: number,
): DictationTemplateField {
const id = normalizeSingleLine(field.id)
const name = normalizeSingleLine(field.name)
const label = normalizeSingleLine(field.label)
const promptText = normalizeSingleLine(field.promptText)
if (
!FIELD_ID_PATTERN.test(id)
|| id.length > 80
|| name.length < 1
|| name.length > 80
|| label.length < 1
|| label.length > 120
|| promptText.length < 1
|| promptText.length > 500
|| typeof field.required !== 'boolean'
|| !Number.isSafeInteger(field.maxDurationSec)
|| field.maxDurationSec < 1
|| field.maxDurationSec > 1800
) {
throw new TemplateServiceError('validation', `Template field ${index + 1} is invalid`)
}
return {
id,
name,
label,
promptText,
required: field.required,
maxDurationSec: field.maxDurationSec,
}
}
export function normalizeTemplateDraft(
kind: TemplateKind,
draft: TemplateDraft,
): Required<Pick<TemplateDraft, 'name'>> & Omit<TemplateDraft, 'name'> {
const name = normalizeSingleLine(draft.name)
const description = draft.description === null || draft.description === undefined
? null
: normalizeSingleLine(draft.description) || null
if (name.length < 1 || name.length > 120 || (description?.length ?? 0) > 1000) {
throw new TemplateServiceError('validation', 'Template name or description is invalid')
}
if (kind === 'dictation') {
const fields = (draft.fields ?? []).map(normalizeTemplateField)
const fieldIds = new Set(fields.map((field) => field.id.toLocaleLowerCase('en-US')))
const fieldNames = new Set(fields.map((field) => field.name.toLocaleLowerCase('en-US')))
const outputFormat = draft.outputFormat?.trim() ?? ''
if (
fields.length < 1
|| fields.length > 50
|| fieldIds.size !== fields.length
|| fieldNames.size !== fields.length
|| outputFormat.length < 1
|| outputFormat.length > 20000
) {
throw new TemplateServiceError('validation', 'Dictation template fields or output are invalid')
}
return { name, description, fields, outputFormat, systemPrompt: null }
}
const systemPrompt = draft.systemPrompt?.trim() ?? ''
if (systemPrompt.length < 1 || systemPrompt.length > 12000) {
throw new TemplateServiceError('validation', 'Meeting document prompt is invalid')
}
return { name, description, fields: [], outputFormat: null, systemPrompt }
}
function toServiceError(error: unknown): TemplateServiceError {
if (error instanceof TemplateServiceError) return error
const candidate = error as { code?: unknown; message?: unknown }
const code = typeof candidate?.code === 'string' ? candidate.code : ''
const message = typeof candidate?.message === 'string'
? candidate.message
: 'Template request failed'
const lower = message.toLowerCase()
if (
error instanceof TypeError
|| lower.includes('network request failed')
|| lower.includes('failed to fetch')
|| lower.includes('networkerror')
|| lower.includes('abort')
) return new TemplateServiceError('network', message, true)
if (code === 'PT409' || lower.includes('revision_conflict')) {
return new TemplateServiceError('conflict', message, true)
}
if (lower.includes('builtin_template_immutable')) {
return new TemplateServiceError('builtin', message)
}
if (code === '42501') return new TemplateServiceError('forbidden', message)
if (code === 'P0002') return new TemplateServiceError('not-found', message)
if (code === 'PGRST301' || lower.includes('jwt')) {
return new TemplateServiceError('auth', message)
}
if (code.startsWith('22')) return new TemplateServiceError('validation', message)
return new TemplateServiceError('server', message, true)
}
function assertTemplate(value: UserTemplate | null, userId: string): UserTemplate {
if (
value === null
|| !UUID_PATTERN.test(value.id)
|| value.user_id !== userId
|| !['dictation', 'meeting_document'].includes(value.template_kind)
|| !Number.isSafeInteger(value.revision)
|| value.revision < 1
|| !Array.isArray(value.fields)
) throw new TemplateServiceError('server', 'Server returned an invalid template')
return value
}
async function rpc<T>(name: string, params: Record<string, unknown> = {}): Promise<T> {
const { data, error } = await supabase.rpc(name as never, params as never)
if (error !== null) throw toServiceError(error)
return data as T
}
export async function loadTemplateLibrary(
userId: string,
kind?: TemplateKind,
searchValue = '',
): Promise<TemplateLibrary> {
requireUuid(userId, 'authenticated user')
const search = sanitizeTemplateSearch(searchValue)
try {
await rpc<UserTemplate[]>('bootstrap_user_templates_v1')
let templateQuery = db()
.from('user_templates')
.select(TEMPLATE_COLUMNS)
.eq('user_id', userId)
.order('is_builtin', { ascending: false })
.order('created_at', { ascending: true })
.order('id', { ascending: true })
if (kind !== undefined) templateQuery = templateQuery.eq('template_kind', kind)
if (search.length > 0) {
templateQuery = templateQuery.or(`name.ilike.%${search}%,description.ilike.%${search}%`)
}
const [templateResult, selectionResult] = await Promise.all([
templateQuery,
db()
.from('user_template_selections')
.select(SELECTION_COLUMNS)
.eq('user_id', userId),
])
if (templateResult.error !== null) throw templateResult.error
if (selectionResult.error !== null) throw selectionResult.error
const templates = (templateResult.data ?? [])
.map((row) => assertTemplate(row as UserTemplate, userId))
const selections: TemplateLibrary['selections'] = {}
for (const selection of selectionResult.data ?? []) {
if (selection.user_id !== userId || !UUID_PATTERN.test(selection.template_id)) {
throw new TemplateServiceError('server', 'Server returned an invalid template selection')
}
selections[selection.template_kind] = selection
}
return { templates, selections }
} catch (error) {
throw toServiceError(error)
}
}
export async function createTemplate(
userId: string,
kind: TemplateKind,
draft: TemplateDraft,
): Promise<UserTemplate> {
requireUuid(userId, 'authenticated user')
const normalized = normalizeTemplateDraft(kind, draft)
try {
const created = await rpc<UserTemplate>('create_user_template_v1', {
p_template_kind: kind,
p_name: normalized.name,
p_description: normalized.description ?? null,
p_fields: normalized.fields ?? [],
p_output_format: normalized.outputFormat ?? null,
p_system_prompt: normalized.systemPrompt ?? null,
})
return assertTemplate(created, userId)
} catch (error) {
throw toServiceError(error)
}
}
export async function updateTemplate(
userId: string,
current: UserTemplate,
draft: TemplateDraft,
): Promise<UserTemplate> {
requireUuid(userId, 'authenticated user')
if (current.user_id !== userId) throw new TemplateServiceError('auth', 'Template owner mismatch')
if (current.is_builtin) throw new TemplateServiceError('builtin', 'Builtin templates are immutable')
const normalized = normalizeTemplateDraft(current.template_kind, draft)
try {
const updated = await rpc<UserTemplate>('update_user_template_v1', {
p_template_id: current.id,
p_expected_revision: current.revision,
p_name: normalized.name,
p_description: normalized.description ?? null,
p_fields: normalized.fields ?? [],
p_output_format: normalized.outputFormat ?? null,
p_system_prompt: normalized.systemPrompt ?? null,
})
return assertTemplate(updated, userId)
} catch (error) {
throw toServiceError(error)
}
}
export async function deleteTemplate(
userId: string,
current: UserTemplate,
): Promise<void> {
requireUuid(userId, 'authenticated user')
if (current.user_id !== userId) throw new TemplateServiceError('auth', 'Template owner mismatch')
if (current.is_builtin) throw new TemplateServiceError('builtin', 'Builtin templates are immutable')
try {
const deleted = await rpc<boolean>('delete_user_template_v1', {
p_template_id: current.id,
p_expected_revision: current.revision,
})
if (deleted !== true) throw new TemplateServiceError('server', 'Template was not deleted')
} catch (error) {
throw toServiceError(error)
}
}
export async function selectTemplate(
userId: string,
template: UserTemplate,
currentSelection: UserTemplateSelection | undefined,
): Promise<UserTemplateSelection> {
requireUuid(userId, 'authenticated user')
if (template.user_id !== userId) throw new TemplateServiceError('auth', 'Template owner mismatch')
if (
currentSelection !== undefined
&& (currentSelection.user_id !== userId || currentSelection.template_kind !== template.template_kind)
) throw new TemplateServiceError('auth', 'Template selection owner mismatch')
try {
const selected = await rpc<UserTemplateSelection>('select_user_template_v1', {
p_template_id: template.id,
p_expected_revision: currentSelection?.revision ?? null,
})
if (
selected.user_id !== userId
|| selected.template_id !== template.id
|| selected.template_kind !== template.template_kind
|| !Number.isSafeInteger(selected.revision)
) throw new TemplateServiceError('server', 'Server returned an invalid selection')
return selected
} catch (error) {
throw toServiceError(error)
}
}
export function renderDictationTemplate(
template: UserTemplate,
fieldValues: Record<string, string>,
): string {
if (template.template_kind !== 'dictation' || template.output_format === null) {
throw new TemplateServiceError('validation', 'A dictation template is required')
}
for (const field of template.fields) {
const value = fieldValues[field.id]?.trim() ?? ''
if (field.required && value.length === 0) {
throw new TemplateServiceError('validation', `Required field is missing: ${field.label}`)
}
}
let output = template.output_format
for (const field of template.fields) {
const escapedName = field.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
output = output.replace(
new RegExp(`\\{\\{${escapedName}\\}\\}`, 'g'),
fieldValues[field.id]?.trim() ?? '',
)
}
return output.replace(/\{\{[^}]+\}\}/g, '').trim()
}
function generationError(status: number, body: unknown): TemplateServiceError {
const code = isRecord(body) && typeof body.error === 'string' ? body.error : ''
if (status === 401) return new TemplateServiceError('auth', code)
if (status === 403) return new TemplateServiceError('forbidden', code)
if (status === 404) return new TemplateServiceError('not-found', code)
if (status === 409) return new TemplateServiceError('in-progress', code, true)
if (status === 429) return new TemplateServiceError('quota', code, true)
if ([502, 503, 504].includes(status)) return new TemplateServiceError('provider', code, true)
if (status === 400) return new TemplateServiceError('validation', code)
return new TemplateServiceError('server', code || 'Document generation failed', true)
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
export async function generateMeetingDocument(
options: GenerateMeetingDocumentOptions,
): Promise<GeneratedMeetingDocument> {
requireUuid(options.meetingId, 'meeting id')
requireUuid(options.templateId, 'template id')
requireUuid(options.idempotencyKey, 'idempotency key')
if (options.accessToken.trim().length < 20) {
throw new TemplateServiceError('auth', 'An authenticated session is required')
}
const title = normalizeSingleLine(options.title)
if (title.length < 1 || title.length > 160) {
throw new TemplateServiceError('validation', 'Document title is invalid')
}
try {
const response = await fetch(`${SUPABASE_URL}/functions/v1/generate-meeting-document`, {
method: 'POST',
headers: {
Authorization: `Bearer ${options.accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
meetingId: options.meetingId,
templateId: options.templateId,
idempotencyKey: options.idempotencyKey,
title,
...(options.model === undefined ? {} : { model: options.model }),
}),
signal: options.signal,
})
const body: unknown = await response.json().catch(() => null)
if (!response.ok) throw generationError(response.status, body)
if (!isRecord(body) || !isRecord(body.document) || typeof body.idempotent !== 'boolean') {
throw new TemplateServiceError('server', 'Server returned an invalid generated document')
}
const document = body.document as MeetingDocument
if (document.meeting_id !== options.meetingId || document.template_id !== options.templateId) {
throw new TemplateServiceError('server', 'Generated document linkage is invalid')
}
return { document, idempotent: body.idempotent }
} catch (error) {
throw toServiceError(error)
}
}
export function subscribeToTemplates(
userId: string,
onRemoteChange: () => void,
onStatus: (status: string) => void,
): TemplateSubscription {
requireUuid(userId, 'authenticated user')
let channel: RealtimeChannel | null = supabase
.channel(`mobile-templates-${userId}`)
.on(
'postgres_changes',
{ event: '*', schema: 'public', table: 'user_templates', filter: `user_id=eq.${userId}` },
onRemoteChange,
)
.on(
'postgres_changes',
{ event: '*', schema: 'public', table: 'user_template_selections', filter: `user_id=eq.${userId}` },
onRemoteChange,
)
.subscribe(onStatus)
return {
unsubscribe: async (): Promise<void> => {
if (channel === null) return
const active = channel
channel = null
await supabase.removeChannel(active)
},
}
}

View file

@ -0,0 +1,43 @@
import type {
DictationTemplateField,
MeetingDocument,
TemplateKind,
UserTemplate,
UserTemplateSelection,
} from '@d3ro/api-client'
export type {
DictationTemplateField,
MeetingDocument,
TemplateKind,
UserTemplate,
UserTemplateSelection,
}
export interface TemplateDraft {
name: string
description?: string | null
fields?: DictationTemplateField[]
outputFormat?: string | null
systemPrompt?: string | null
}
export interface TemplateLibrary {
templates: UserTemplate[]
selections: Partial<Record<TemplateKind, UserTemplateSelection>>
}
export interface GenerateMeetingDocumentOptions {
accessToken: string
meetingId: string
templateId: string
idempotencyKey: string
title: string
model?: 'claude-haiku-4-5-20251001' | 'claude-sonnet-4-6' | 'claude-opus-4-6'
signal?: AbortSignal
}
export interface GeneratedMeetingDocument {
document: MeetingDocument
idempotent: boolean
}